我想在Zend Framework 2表单中为select的选项添加自定义HTML属性。
这是我的Form类的部分代码:
$this->add(array(
'name' => 'lieuRemplissage',
'type' => 'Select',
'attributes' => array(
'class' => 'form-control',
),
'options' => array(
'label' => _('Lieu pré-enregistré'),
),
));
我在控制器中填充我的选项值,如下所示:
$form = new \Vente\Form\Vente;
foreach($this->getAdminLieuDeVenteTable()->fetchAll() as $lieu) {
$optionsLieu[$lieu->getId()] = $lieu->getNom();
}
$form->get('lieuRemplissage')->setValueOptions($optionsLieu);
但是现在,对于每个选项,我想为所有选择选项添加一个html属性,但每个选项的值都不同。
有没有办法在ZF2中实现这一目标?
感谢。
答案 0 :(得分:10)
是的,这可以使用ZF2
传入选项值中的属性。值应为数组格式:
//视图中的示例:
$select=new \Zend\Form\Element\Select('test');
$select->setValueOptions(
[
['attributes'=>['data-key'=>'value'],'value'=>'myValue','label'=>'myLabel']
]
);
echo $this->formselect($select);
打印:
<select name="test"><option value="myValue" data-key="value">myLabel</option></select>
编辑:
您提供的属性必须是有效的HTML属性,您不能放置任何随机键/值对。 例如data- *就像以下一样好:
protected $validGlobalAttributes = array(
'accesskey' => true,
'class' => true,
'contenteditable' => true,
'contextmenu' => true,
'dir' => true,
'draggable' => true,
'dropzone' => true,
'hidden' => true,
'id' => true,
'lang' => true,
'onabort' => true,
'onblur' => true,
'oncanplay' => true,
'oncanplaythrough' => true,
'onchange' => true,
'onclick' => true,
'oncontextmenu' => true,
'ondblclick' => true,
'ondrag' => true,
'ondragend' => true,
'ondragenter' => true,
'ondragleave' => true,
'ondragover' => true,
'ondragstart' => true,
'ondrop' => true,
'ondurationchange' => true,
'onemptied' => true,
'onended' => true,
'onerror' => true,
'onfocus' => true,
'oninput' => true,
'oninvalid' => true,
'onkeydown' => true,
'onkeypress' => true,
'onkeyup' => true,
'onload' => true,
'onloadeddata' => true,
'onloadedmetadata' => true,
'onloadstart' => true,
'onmousedown' => true,
'onmousemove' => true,
'onmouseout' => true,
'onmouseover' => true,
'onmouseup' => true,
'onmousewheel' => true,
'onpause' => true,
'onplay' => true,
'onplaying' => true,
'onprogress' => true,
'onratechange' => true,
'onreadystatechange' => true,
'onreset' => true,
'onscroll' => true,
'onseeked' => true,
'onseeking' => true,
'onselect' => true,
'onshow' => true,
'onstalled' => true,
'onsubmit' => true,
'onsuspend' => true,
'ontimeupdate' => true,
'onvolumechange' => true,
'onwaiting' => true,
'role' => true,
'aria-labelled-by' => true,
'aria-described-by' => true,
'spellcheck' => true,
'style' => true,
'tabindex' => true,
'title' => true,
'xml:base' => true,
'xml:lang' => true,
'xml:space' => true,
);
答案 1 :(得分:7)
我刚想出来并希望在这里分享,因为我在寻找同一个问题时看到了这个问题。应该用建议的方式给出相同的结果,但直接使用选项&#39;表单类中的属性;如果将数据对象传递给表单构造以填充像我这样的选项,则特别有用。
$this->add(array(
'name' => 'lieuRemplissage',
'type' => 'Select',
'attributes' => array(
'class' => 'form-control',
),
'options' => array(
'label' => _('Lieu pré-enregistré'),
'value' => 123
'attributes' => array(
'data-key' => 'value_for_data_attribute_goes_here',
),
),
));