Elements of same name in Zend_Form

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

3 Replies to “Elements of same name in Zend_Form”

  1. Today I found in my solution 2, Zend_Form_Element::setBelongsTo() can’t work with Zend_Form::populate() or Zend_Form::isValid().

    This is what happens: when the element is rendered with setBelongsTo(), it is taking inputs as array, however, the form is still expecting data as individual.

  2. Hello
    So, if I want to list all options from database and give user freedom to check interested them rows how do I should populate elements on the Zend_Form? addElement (checkbox) shouldn’t work. It will overwrite previous element.

    Best Regards

Leave a Reply

Your email address will not be published. Required fields are marked *