Zend Forms - 元素 ID 修改以允许重用 [英] Zend Forms - Element ID modification to allow re-use

查看:14
本文介绍了Zend Forms - 元素 ID 修改以允许重用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Zend_Form 对象,我想在一个页面中多次重复使用它.我遇到的问题是每次渲染时它都具有相同的元素 ID.我一直无法找到一种方法来在每次呈现表单时为所有 ID 指定一个唯一的前缀或后缀.

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've been unable to find a method for giving all the IDs a unique prefix or suffix each time I render the form.

完整的解决方案

子类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);
    }
}

在视图脚本中循环:

<?php foreach ($this->rows as $row) : ?>
    <?php echo $this->form->setDefaults($row->toArray())->setIdSuffix($row->id); ?>
<?php endforeach; ?>

推荐答案

你可以子类化 Zend_Form 并重载 render 方法来自动生成 id:

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.

这篇关于Zend Forms - 元素 ID 修改以允许重用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆