phpformszend-framework2labelzend-form2

How to add attributes to a label generated with Zend/Form in Zend framework 2


I'm adding forms to my page using Zend/Form.

I'm adding elements by defining them as follows:

    $this->add(array(
            'name' => 'value',
            'attributes' => array(
                    'type'  => 'text',
                    'id' => 'value',
                    'autocomplete' => 'off',
                    'placeholder' => 'Cost',
            ),
            'options' => array(
                    'label' => 'Cost',
            ),
    ));

As you can see there is a 'label' => 'cost' node, this generated a label to go with the input element.

How do I add classes, attributes to this label ?


Solution

  • Please try this, i haven't tested or used this, but going by the source it should function properly:

    $this->add(array(
        'name'       => 'value',
        'attributes' => array(),
        'options'    => array(
            'label_attributes' => array(
                'class'  => 'mycss classes'
            ),
            // more options
        ),        
    ));
    

    If this does not function, please leave me a comment. If it won't function, it is not possible using this approach, since the FormLabel restricts the validAttributes quite a bit:

    protected $validTagAttributes = array(
        'for'  => true,
        'form' => true,
    );