Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. !?

like image 647
user457015 Avatar asked Oct 04 '13 09:10

user457015


2 Answers

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 (I.e 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');
like image 87
AlexP Avatar answered Nov 07 '22 23:11

AlexP


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'));
like image 37
9 Digit Avatar answered Nov 07 '22 23:11

9 Digit