Zend Forms - Element ID modification to allow re-use

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-07 19:15:06

问题


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.


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; ?>

回答1:


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.




回答2:


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');


来源:https://stackoverflow.com/questions/4440222/zend-forms-element-id-modification-to-allow-re-use

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!