简体   繁体   中英

symfony2 add label attribute to multiple choice list

I want to add different attribute to difference choice list.

->add('list', 'choice_single_select', [
            'choices' => ['gender', 'female', 'newborn', 'oldborn'],
            'required' => false,
            'expanded' => true,
            'multiple' => true,
            'label_attr' => ['class' =>  'listClass'],
            'choice_attr' => function($val, $key, $index) {
                return [
                    'data-ng-click' => 'form.list = (form.list != '.$val.') ? '.$val." : '';",
                    'data-ng-show' => 'aggr.count_'.$val.'.count'
                ];
            },
        ])

I want to set ng-show="gender2" to gender and ng-show="female4" to female label

There is way to add attribute per choice_attr to the input fields, but not for label. So I'm kind of confuse what would be easy way of adding it

I have manage to solve this by using existing choice_attr with customising the twig form theme. It will loop through attributes and only allow title and ng-show to label attribute. (I have removed label_attr usage, but you can use it if you need it.

{% form_theme form _self %}

{% block checkbox_widget -%}
    {% set parent_label_class = parent_label_class|default('') %}

    <div class="checkbox">
        <label{% for attrname, attrvalue in attr %} {% if attrname in ['data-ng-show', 'title'] %}{{ attrname }}="{{ attrvalue }}"{%- endif -%}{% endfor %}>
            <input type="checkbox" {{ block('widget_attributes') }}{% if value is defined %} value="{{ value }}"{% endif %}{% if checked %} checked="checked"{% endif %} />
            {{ translation_domain is same as(false) ? label : label|trans({}, translation_domain) }}
        </label>
    </div>
{%- endblock checkbox_widget %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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