Is there a way to prefix Zend_Form element name?

I have a page that has multiple forms. Some forms have an element with the same name as CustomerID. This means that the ID element ID will clash with the same ID in other forms. I would like to find a clean way to prefix the field name with the form name. For example, PaymentProfile_CustomerID. Suggestions?

So far, the best I could come up with is:

class MyForm extends Zend_Form
{
    public function init()
    {
        $this->setName("PaymentProfile");
        ...
        $this->_prefixElementNames();
    }

    private function _prefixElementNames()
    {
        $elements = $this->getElements();
        $formName = $this->getName();

        foreach($elements as $e) {
            $e->setAttrib('id', $formName . '_' . $e->getName());
        }
    }
}

      

UPDATE @ garvey's answer below works well with a simple modification.

public function addElement($element, $name = null, $options = null)
{
    $e = parent::addElement($element, $name, $options);
    if($this->getName())
        // I use setAttrib instead of setName because I only want the ID to be changed.
        // Didn't want the form data to be prefixed, just the unique HTML identifier.
        $element->setAttrib('id', $this->getName() . '_' .  $element->getName());
    return $e;
}

      

+3


source to share


2 answers


It seems to me like just using elementsBelongTo

:

public function init()
{
    $this->setOptions(array(
        'elementsBelongTo' => 'form_name' 
    ));
}

      

edit : extended for future use

Usage elementsBelongTo

wraps all form elements in an array, so you get



Zend_Debug::dump($this->_getAllParams())

      

outputs:

["form_name"] => array(
    ["element1"] => "value1"
    ["element2"] => "value2"
)

      

+3


source


I researched your problem. And I think the best way is to extend the Zend_Form class like this:

class Cubique_Form extends Zend_Form
{
    public function addElement($el)
    {
        $el->setName($this->getName() . '_' .  $el->getName());
        parent::addElement($el);
    }
}

      



And creating the form:

$form = new Cubique_Form();
$form->setName('form');
$el = new Zend_Form_Element_Text('element');
$form->addElement($el);

      

+2


source







All Articles