简体   繁体   中英

How to add class and id to form element in Zend Framework 2.2.4

The HTML I need:

<label for="text_field_username">User Name</lable>
<input type="text" id="text_field_username" name="text_field_username" class="form-control" />

I want the for of the label to link to the id of the input. This way the user can click on the label to highlight the input. More usefull for checkbox. Also, less important, I want to had a class to the input field.

What I have tried and does not works for me:

echo $this->formRow($form->get('usr_name'));

I also tried to use partial layout.

echo $this->formElement($element);

Before posting this question I came across this documentation framework.zend.com/manual/2.2/en/modules/zend.form.view.helpers.html#formlabel

It does not works. It add the for but it point to nothing. !?

View partials help with the rendering of the form, they don't however deal with the properties of the form elements themselves. This is dealt with by the form class and it's collection of form elements (Ie TextElement)

You can use setAttribute('class', 'class name') on any form element

So within the init() method of your form this should work:

$element = $this->getElement('text_field_username');
$element->setAttribute('class', 'class name');

You can also set this in your inherited form helper class like this:

namespace Application\Form;
use Zend\Form\Form;
class NexForm extends Form
{
public function __construct($name = null)
{
    parent::__construct('Nex');
    $this->setAttribute('method', 'post');
    $this->setAttribute(
        'enctype',
        'multipart/form- data'
    );
    $this->add(array(
        'name' => 'default_widget',

        'attributes' => array(
            'type' => 'text',
            'id'   => 'default_widget',
            'class' => 'mtz-monthpicker-widgetcontainer',
            'required' => 'required',
        ),
        'options' => array(
            'label' => 'Please choose the month of records you want to display:',
        ),
    ));
}
}

and in your view just call:

     $nex=$this->app;   //app is the form object we passed from controller to view
     echo $this->formElement($nex->get('default_widget'));

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