简体   繁体   中英

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 ?

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,
);

This works well in Zend Framework 2.3 :

$this->add(array(
  'name' => 'userName',
  'attributes' => array(
      'type'  => 'text',
      'class' => 'form-control',
      'placeholder' =>'Username',
  ),
  'options' => array(
      'label' => 'Username',
      'label_attributes' => array('class' => 'control-label')
  ),

));
$element->setOptions(array('label_class' => array('class' => 'control-label')));

Produces code like this:

<label class="control-label">
  <input type="radio" name="option1" id="option1" value="1">
  Option 1
</label>
<label class="control-label">
  <input type="radio" name="option2" id="option2" value="2">
  Option 2
</label>

I have tried this. It works in Zend Framework One.

Note if you use

$element->setOptions(array('label_attributes' => array('class' => 'control-label')));

you get the undesirable effect for some reason of

<label attributes="control-label">
  <input type="radio" name="option1" id="option1" value="1">
  Option 1
</label>

For programmatic approach on ZF2+ try this:

$element->setOptions(array(
    'label_attributes' => array(
        'style' => 'color:gray;'
    )
));

Inspired by Damon's answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM