Symfony:在多选中为选项标签添加ID

时间:2016-09-07 08:51:52

标签: php forms symfony symfony-forms

版本:Symfony 3

我的表格中有一个多选项,如下所示,

->add('roles', ChoiceType::class, array(
    'attr'  =>  array('class' => 'form-control',
    'style' => 'margin:5px 0;'),
    'choices' => 
    array
    (
        'ROLE_ADMIN' => array
        (
            $this->get('translator')->trans('Yes') => 'ROLE_ADMIN',
        ),
        'ROLE_TEACHER' => array
        (
            $this->get('translator')->trans('Yes') => 'ROLE_TEACHER'
        ),
        'ROLE_STUDENT' => array
        (
            $this->get('translator')->trans('Yes') => 'ROLE_STUDENT'
        ),
        'ROLE_PARENT' => array
        (
            $this->get('translator')->trans('Yes') => 'ROLE_PARENT'
        ),
    ) 
    ,
    'multiple' => true,
    'required' => true,
    ) )

它在前端/网页中播种如下,

<select multiple="multiple" style="margin:5px 0;" class="form-control" required="required" name="form[roles][]" id="form_roles">
<optgroup label="ROLE_ADMIN">
    <option value="ROLE_ADMIN">Yes</option>
</optgroup>
<optgroup label="attr">
    <option value="checkp">id</option>
</optgroup>
<optgroup label="ROLE_TEACHER">
    <option value="ROLE_TEACHER">Yes</option>
</optgroup>
<optgroup label="ROLE_STUDENT">
    <option value="ROLE_STUDENT">Yes</option>
</optgroup>
<optgroup label="ROLE_PARENT">
    <option value="ROLE_PARENT">Yes</option>
</optgroup>
</select>

现在我想知道如何为select中的每个选项添加ID。例如,

<option id="parent" value="ROLE_PARENT">Yes</option>

谢谢

1 个答案:

答案 0 :(得分:1)

添加choice_attr配置。这样的事情会起作用:

'choice_attr' => function($val) {
    list(, $roleName) = explode('_', $val, 2);

    return ['id' => strtolower($roleName)];
},