我有一个 Zend_Form
对象,我想在一个页面中多次重复使用它。我遇到的问题是每次渲染时它都有相同的元素 ID。我一直无法找到一种方法,可以在每次呈现表单时为所有 ID 提供唯一的前缀或后缀。
完整的解决方案
子类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);
}
}
在 View 脚本中循环:
<?php foreach ($this->rows as $row) : ?>
<?php echo $this->form->setDefaults($row->toArray())->setIdSuffix($row->id); ?>
<?php endforeach; ?>
最佳答案
您可以继承 Zend_Form 并重载 render
方法来自动生成 id:
public function render()
{
$elements = $this->getElements();
foreach ($elements as $element) {
$element->setAttrib('id', $this->getName() . '_' . $element->getId();
}
}
这只是一个伪代码。当然,您可以修改它以满足您的需要。
关于php - Zend Forms - 元素 ID 修改以允许重复使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4440222/