ZF2将自定义属性添加到选择表单元素中的选项 [英] ZF2 Add custom attribute to option in a select form element

查看:41
本文介绍了ZF2将自定义属性添加到选择表单元素中的选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Zend Framework 2表单的选择选项中添加自定义HTML属性.

I would like to add a custom HTML attribute to an option of a select in a Zend Framework 2 Form.

这是我的Form类中的(部分)代码:

This is my (partial) code from my Form class:

$this->add(array(
        'name' => 'lieuRemplissage',
        'type' => 'Select',
        'attributes'    => array(
            'class'     => 'form-control',
        ),
        'options'   => array(
            'label' => _('Lieu pré-enregistré'),
        ),
    ));

我这样在控制器中填充选项值:

I populate my options values in my controller like this :

$form = new \Vente\Form\Vente;
foreach($this->getAdminLieuDeVenteTable()->fetchAll() as $lieu) {
       $optionsLieu[$lieu->getId()] = $lieu->getNom();
    }
    $form->get('lieuRemplissage')->setValueOptions($optionsLieu);

但是现在,对于每个选项,我想为所有选择选项添加一个html属性,但每个选项的值都不同.

But now, for each option I want to add an html attribute to all select options but with a different value for each one.

有没有办法在ZF2中实现这一目标?

Is there a way do achieve that in ZF2 ?

谢谢.

推荐答案

我只是想出了这一点,并想在这里分享,因为我在搜索同一问题时看到了这个问题.应该以建议的方式给出相同的结果,但应直接在表单类中使用options的属性;如果将数据对象传递给表单构造以填充像我这样的选项,则特别有用.

I just figured this out and wanted to share here since I saw this question while I was searching for the same question. Should give the same result with the suggested way but directly using options' attributes in form class; especially useful if passing data object to form construct to populate options like me.

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

这篇关于ZF2将自定义属性添加到选择表单元素中的选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆