php - 有没有办法为 Zend_Form 元素名称添加前缀?

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

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

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

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 更容易:

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

编辑:扩展以供将来使用

使用 elementsBelongTo将所有表单元素包装在数组中,所以你会得到

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

输出:

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

关于php - 有没有办法为 Zend_Form 元素名称添加前缀?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9790029/

相关文章:

php - php 或 zend 中国际电话号码验证的正则表达式是什么?

php - Curl 以空字符串响应。如何获取更多信息?

php - 按自定义顺序对 Laravel 集合进行排序,而不是 asc 或 desc

php - 如何访问 Model ZF2 中的 getServiceLocator

php - Zend 框架模块和反射

php - 对 <head> 和 <body> 脚本使用 headScript View 助手

zend-framework - 从 Zend_Form 调用助手

php - 如何从 html 表单将大文本内容存储在 db 中

php - 在网格中显示表格中的图像

zend-framework - 向表单添加 csrf 是否存在根本性错误?