FORSMILE
JA
Symfony2021/12/08

Removing the `form-control` Class from Forms: Configuring Form Themes [Symfony]

When generating Forms in Symfony, I was bothered by the automatic application of the Bootstrap class 'form-control' and investigated how to prevent it.

Back to Blog

When I generated a Form in Symfony, I noticed that the Bootstrap class 'form-control' was automatically applied, so I looked into it.

To get straight to the point, the cause was that the Form Theme setting was defaulting to Bootstrap.

WHAT ARE FORM THEMES

Simply put, you can configure the templates for Forms generated by Symfony.

Configuration Location

text
# config/packages/twig.yaml

twig:
    form_themes: ['bootstrap_4_layout.html.twig']

You can change the theme by modifying the `twig.yaml` configuration shown above.

The example above is for when you want to use Bootstrap 4. It seems this is also the default value in recent versions.

Please refer to the official documentation to see what themes are available.

BASIC THEME WITHOUT CLASSES

To prevent Bootstrap's 'form-control' from being automatically defined as a class, as in my example, refer to the following:

text
# config/packages/twig.yaml

    twig:
        form_themes: ['form_div_layout.html.twig']

Furthermore, if you want to set the `form_theme` on a per-Twig file basis, you can do so as shown below.

css
{# this form theme will be applied only to the form of this template #}
{% form_theme form 'bootstrap_5_layout.html.twig' %}

Looking at the official documentation, it seems quite detailed configurations are possible, such as creating custom templates.

Up until now, if I wanted to use an HTML structure different from the one generated by Symfony forms, I would embed the form data directly into tags without using `form_widget`. Creating Form Themes seems to make this much easier to use.

Recommended Symfony Books

There aren't many varieties, and the sheer volume of information for the framework itself means even introductory books offer a substantial read.

📦
Amazon で関連書籍・ツールを検索
Symfony PHP framework book
Amazonで探す →(アソシエイトリンク)