janw
janw

Reputation: 6662

zend_form decorator on whole form not each individual 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 individual 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));
}

Upvotes: 2

Views: 713

Answers (2)

JF Dion
JF Dion

Reputation: 4054

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.

Upvotes: 3

dinopmi
dinopmi

Reputation: 2673

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,

Upvotes: 1

Related Questions