Day: December 9, 2009

  • 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
    }
    
  • Limitation of Mage::getModel method

    Magento getModel can not initialise an instance whose class requires more than 1 argument.

    I assume Magento native classes can explode options from the first argument to satisfy getModel. However, if I want to use 3rd party class like Zend_Form_Element inside Magento, there is no ways to use getModel to achieve the same result as

    $element = new Zend_Form_Text('name', $options);
    

    because

    $element = Mage::getModel('moduleName/modelName', 'name');
    

    takes 1 argument which is ‘name’ only. No way to pass $options on.