php - Zend Forms - 元素 ID 修改以允许重复使用

标签 php zend-framework zend-form zend-form-element

我有一个 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/

相关文章:

PHP持久脚本和最大执行时间

php - CodeIgniter:$this->db->query 中的 LEFT JOIN 返回数据库错误

php - iphone 到 mysql blob 没有插入没有错误

php - 如何在 View 中显示数据

php - php中的缓存策略

php - Zend_Db 使用多个 AND OR 运算符的复杂 WHERE 子句

php - Zend Framework,传递变量查看

php - 如何以编程方式隐藏 Zend_Element_Checkbox 的字段和标签?

php - Zend_Form + DHTML 内容

php - Zend 表单验证