简体   繁体   English

如何在Zend Framework 2.2.4中为表单元素添加类和id

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

The HTML I need: 我需要的HTML:

<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. 我希望标签的for链接到输入的id。 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 在发布此问题之前,我遇到了这个文档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. 它添加了for但它没有任何意义。 !? !?

View partials help with the rendering of the form, they don't however deal with the properties of the form elements themselves. 查看partials有助于呈现表单,但它们不会处理表单元素本身的属性。 This is dealt with by the form class and it's collection of form elements (Ie TextElement) 这由表单类及其表单元素集合(即TextElement)处理。

You can use setAttribute('class', 'class name') on any form element 您可以在任何表单元素上使用setAttribute('class', 'class name')

So within the init() method of your form this should work: 因此,在表单的init()方法中,这应该工作:

$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'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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