问题
I have a page that has multiple forms on it. Several of the forms share an element with the same name like CustomerID. This means the element ID CustomerID will collide with that same ID in the other forms. I would like to find a clean way to prefix the field name with the name of the form. For instance PaymentProfile_CustomerID. Suggestions?
So far, the best I have been able to 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 worked 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;
}
回答1:
I think it's easier to just use elementsBelongTo
:
public function init()
{
$this->setOptions(array(
'elementsBelongTo' => 'form_name'
));
}
edit: expanded for future use
Using elementsBelongTo
wraps all form elements in array, so you'll get
Zend_Debug::dump($this->_getAllParams())
outputs:
["form_name"] => array(
["element1"] => "value1"
["element2"] => "value2"
)
回答2:
I have investigated your issue. And I think the best way is to extend 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 form creation:
$form = new Cubique_Form();
$form->setName('form');
$el = new Zend_Form_Element_Text('element');
$form->addElement($el);
来源:https://stackoverflow.com/questions/9790029/is-there-a-way-to-prefix-zend-form-element-name