开发者

zend_form decorator on whole form not each individual element

开发者 https://www.devze.com 2023-04-09 22:36 出处:网络
Custom HTML Output on Zend Form Checkbox setLabel Property In adition to this question. I want to apply this to all my form_elements without adding it to each indivi开发者_如何转开发dual form_element

Custom HTML Output on Zend Form Checkbox setLabel Property

In adition to this question.

I want to apply this to all my form_elements without adding it to each indivi开发者_如何转开发dual 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));
}


You could make yourself a class that extends the Zend_Form and overload the createElement method :

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

and then you extends that form :

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

}

You could use that method for a lot of other things. In the past I've used it to define the default decorators on all my form elements.


You can call setElementDecorators() after addElements() to set decorators for all the elements in the form. See more information in the related Zend Framework documentation.

Hope that helps,

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号