Customize the rendering of a choice/entity field in Symfony2
1. Manually rendering. Better if is a individual form for field and not repeated somethere as it requires less time to work.
A) Get name of field you can with form.service.vars.full_name
B) List of choices - form.service.vars.choices
. Its an array of ChoiceView
, to get entity simply access public data
property.
{% for choice in form.service.vars.choices %} {% set service_entity = choice.data %}{% endfor %}
2. Via overriding templates. IF you like to brute-force pick up the name of the blocks which must be overriden.
A) You can only override widget
, label
and errors
blocks as documentation said. You can specify block by widget name(documentation). Something like
{% block _form_service_widget %} {% if expanded %} {{ block('choice_widget_expanded') }} {% else %} {{ block('my_service_widget') }} {% endif %}{% endblock %}{% block my_service_widget %}{% spaceless %} <select {{ block('widget_attributes') }}{% if multiple %} multiple="multiple"{% endif %}> {% if empty_value is not none %} <option value="">{{ empty_value|trans({}, translation_domain) }}</option> {% endif %} {% set options = choices %} {{ block('my_service_options') }} </select>{% endspaceless %}{% endblock my_service_widget %}{% block my_service_options %}{% spaceless %} {% for group_label, choice in options %} {# here you can access choice #} <option value="{{ choice.value }}"{% if choice is selectedchoice(value) %} selected="selected"{% endif %}>{{ choice.label|trans({}, translation_domain) }}</option> {% endfor %}{% endspaceless %}{% endblock my_service_options %}
You can use the choice_attr
option in the form builder:
$builder->add('myField', ChoiceType:class, [ .... 'choice_attr' => function($val, $key, $index) { return ['data' => '...', 'class' => '', ... etc ]; }, ....]);
This will apply attributes to each option
, checkbox
, radio
in your choice (depending on your expanded
and multiple
option choices)