I am working with Symfony 3.4 and have created a custom FormType. I would like to pass some parameters to a form field of this type from a twig template.
According to the Symfony Docs this should be possible:
{# render a widget, but add a "foo" class to it #}
{{ form_widget(form.name, { 'attr': {'class': 'foo'} }) }}
While this does work when using a build in form type such as TextType
I could not find out how to achieve the same for my custom types:
// Form Type class
class MyCustomType extends AbstractType {
public function getBlockPrefix() {
return 'my_custom_type';
}
public function getParent() {
return ChoiceType::class;
}
public function configureOptions(OptionsResolver $resolver) {
$resolver->setDefaults(array(
'translation_domain' => 'app',
));
}
}
// Widget Template
{% block my_custom_type_widget %}
{{ dump(form) }}
{% if form.vars.attr.class is defined %}
{{ form.vars.attr.class }}
{% endif %}
...
{% endblock %}
// Form template
...
{{ form_start(form) }}
{{ form_widget(form.myCustom, {'attr': {'class': 'customClass'}}) }}
...
{{ form_end(form) }}
The customClass
which is added in the form template is not passed to the widget template. The {% if form.vars.attr.class is defined %}
test works, but only the default class formName-myCustom
is available.
So, how do I pass a custom attribute from twig to my custom form type? What do I have to change on my custom type to let it work just like the TextType
where passing a class in Twig is no problem?
Try to merge default class with the new one like in https://github.com/symfony/symfony/blob/5.x/src/Symfony/Bridge/Twig/Resources/views/Form/bootstrap_4_layout.html.twig#L29