有没有办法为 Zend_Form 元素名称添加前缀? [英] Is there a way to prefix Zend_Form element name?

查看:31
本文介绍了有没有办法为 Zend_Form 元素名称添加前缀?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个页面,上面有多个表单.几个表单共享一个具有相同名称的元素,如 CustomerID.这意味着元素 ID CustomerID 将与其他表单中的相同 ID 发生冲突.我想找到一种干净的方法来为字段名称加上表单名称的前缀.例如 PaymentProfile_CustomerID.建议?

I have a page that has multiple forms on it. Several of the forms share an element with the same name like CustomerID. This means the element ID CustomerID will collide with that same ID in the other forms. I would like to find a clean way to prefix the field name with the name of the form. For instance PaymentProfile_CustomerID. Suggestions?

到目前为止,我能想到的最好的是:

So far, the best I have been able to come up with is:

class MyForm extends Zend_Form
{
    public function init()
    {
        $this->setName("PaymentProfile");
        ...
        $this->_prefixElementNames();
    }

    private function _prefixElementNames()
    {
        $elements = $this->getElements();
        $formName = $this->getName();

        foreach($elements as $e) {
            $e->setAttrib('id', $formName . '_' . $e->getName());
        }
    }
}

UPDATE @garvey 在下面的回答通过简单的修改效果很好.

public function addElement($element, $name = null, $options = null)
{
    $e = parent::addElement($element, $name, $options);
    if($this->getName())
        // I use setAttrib instead of setName because I only want the ID to be changed.
        // Didn't want the form data to be prefixed, just the unique HTML identifier.
        $element->setAttrib('id', $this->getName() . '_' .  $element->getName());
    return $e;
}

推荐答案

我认为使用 elementsBelongTo 更容易:

I think it's easier to just use elementsBelongTo:

public function init()
{
    $this->setOptions(array(
        'elementsBelongTo' => 'form_name' 
    ));
}

编辑:扩展以备将来使用

使用 elementsBelongTo 将所有表单元素包装在数组中,因此您将获得

Using elementsBelongTo wraps all form elements in array, so you'll get

Zend_Debug::dump($this->_getAllParams())

输出:

["form_name"] => array(
    ["element1"] => "value1"
    ["element2"] => "value2"
)

这篇关于有没有办法为 Zend_Form 元素名称添加前缀?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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