整个表单上的zend_form装饰器不是每个单独的元素

时间:2011-09-29 10:25:55

标签: zend-framework zend-form

Custom HTML Output on Zend Form Checkbox setLabel Property
提出这个问题。
我想将此应用于我的所有form_elements,而不将其添加到每个form_element


class my_form extends Zend_Form
{
    public function init()
    {
        $this->setAction('')
                ->setMethod('post');
                //shouldn't I be able to set the decorator here?

        $firstname= new Zend_Form_Element_Text('firstname');
        $firstname->setLabel('firstname')
                ->setRequired(true)
                ->getDecorator('label')
                ->setOptions(array('requiredSuffix'=> ' <span class="required">*</span> ', 'escape'=> false))
                //here it works but I don't want it on every element.
                ;

        $lastname= new Zend_Form_Element_Text('lastname');
        $lastname->setLabel('firstname')
                ->setRequired(true)
                ->getDecorator('label')
                ->setOptions(array('requiredSuffix'=> ' <span class="required">*</span> ', 'escape'=> false))
                //here it works but I don't want it on every element.
                ;
        $this->addElements(array($lastname, $firstname));
}

2 个答案:

答案 0 :(得分:3)

您可以自己创建一个扩展Zend_Form的类,并使createElement方法超载:

class My_Base_Form extends Zend_Form 
{
    public function createElement($type, $name, $options = null)
    {
        $element = parent::createElement($type, $name, $options);
        $element->setOptions(
            array('requiredSuffix'=> ' <span class="required">*</span> ')
        );
        $label = $element->getDecorator('Label');

        if (!empty($label)) {
            $label->setOption('escape', false);
        }
        return $element;
    }
}

然后你扩展了这个形式:

class My_Form extends My_Base_Form
{
    public function init()
    {
        ...
        // $firstname= new Zend_Form_Element_Text('firstname'); old version

        // taking advantage of the createElement
        $firstname = $this->createElement('text', 'firstname');
        ...
    }

}

您可以将该方法用于许多其他事情。在过去,我用它来定义所有表单元素的默认装饰器。

答案 1 :(得分:1)

您可以在setElementDecorators()之后调用addElements()为表单中的所有元素设置装饰器。请参阅相关Zend Framework documentation

中的详细信息

希望有所帮助,