Zend Forms - Element ID modification to allow re-use
I have a Zend_Form
object that I want to re-use several times in one page. The problem I'm having is that each time it's rendered it has the same element IDs. I'v开发者_开发问答e been unable to find a method for giving all the IDs a unique prefix or suffix each time I render the form.
Complete Solution
Subclass Zend_Form
:
class My_Form extends Zend_Form
{
protected $_idSuffix = null;
/**
* Set form and element ID suffix
*
* @param string $suffix
* @return My_Form
*/
public function setIdSuffix($suffix)
{
$this->_idSuffix = $suffix;
return $this;
}
/**
* Render form
*
* @param Zend_View_Interface $view
* @return string
*/
public function render(Zend_View_Interface $view = null)
{
if (!is_null($this->_idSuffix)) {
// form
$formId = $this->getId();
if (0 < strlen($formId)) {
$this->setAttrib('id', $formId . '_' . $this->_idSuffix);
}
// elements
$elements = $this->getElements();
foreach ($elements as $element) {
$element->setAttrib('id', $element->getId() . '_' . $this->_idSuffix);
}
}
return parent::render($view);
}
}
Loop in the view script:
<?php foreach ($this->rows as $row) : ?>
<?php echo $this->form->setDefaults($row->toArray())->setIdSuffix($row->id); ?>
<?php endforeach; ?>
You may subclass Zend_Form and overload render
method to generate id's automatically:
public function render()
{
$elements = $this->getElements();
foreach ($elements as $element) {
$element->setAttrib('id', $this->getName() . '_' . $element->getId();
}
}
This is just a pseudo-code. Of course, you may modify this to suit your needs.
You could add a static integer property (let's say self::$counter)to your Zend_Form inherited class. You increment it on the init() method. For each element you create on your Zend_Form object you append that property to your element :
$element->setAttrib('id', self::$counter + '_myId');
精彩评论