It is a rigid rule that Zend_Form can not have elements of same names. If I add a second element with the same name, the first one will be overwritten.
When I started to use Zend_Form, I thought this rule makes life difficult. For example, if the form have “Next” and “Previous” buttons, I must give them different names. How can I tell which button is clicked? I must go through all names. I thought if these buttons could have same name but different value, it was easier to tell which button was clicked.
It was before long I started to enjoy this rigid rule. Take the above example for example, it is NOT a good practice to judge which button was clicked by its value. Because for an internationalised program, the value may change and that is out of the programmers’ control.
What if I want to add 5 text fields for people to fill in information like team members’ name? Two solutions. The first one looks stupid but I did not come across the second one at first.
Solution 1:
class MyNamespace_MyText extends Zend_Form_Element_Text { protected $_name = "text"; public function init() { static $sequence = 0; $this->id = $this->_name . '_' . $sequence; $this->_label = "Label " . ($sequence + 1); $this->_name = $this->_name . '[' . $sequence . ']'; $sequence ++; } }
Solution 2:
for ($sequence = 0; $sequence < 5; ++$sequence) { $element = Mage::getModel('moduleName/modelName', "$sequence") ->setBelongsTo('text'); //my form is inside Magento }
Leave a Reply