Search code examples
phpsymfonytwigsymfony4symfony3.x

Symfony 3+: Custom form element template


We are finally upgrading to Symfony 3 which however causes some issues.

Current problem I am trying to solve is https://api.symfony.com/2.8/Symfony/Component/Form/FormTypeInterface.html#method_getName witch has been deprecated.

FormTypeInterface#getName() was used to create a nickname witch was used in twig form templates.

Example custom form type:

class MyCustomType extends AbstractType {

    // ...

    public function getName() {
        return 'my_custom';
    }

}

Example template row in Twig:

{% block my_custom_row %}

    {# ... #}

{% endblock %}

Question:

What is the naming convention for custom form types in Symfony 3+? I.e. how should I name the twig blocks to customize the form row/widget/error rendering?


Solution

  • Twig block by default should be named as FormType class without Type suffix. ie. my_custom_row for *_row block.

    Other, more custom way is to add function getBlockPrefix() (https://api.symfony.com/3.1/Symfony/Component/Form/FormTypeInterface.html#method_getBlockPrefix). That function should return exactly the same block name prefix as getName() before, but this is optional and require only if block prefix is different than class name.

    In Symfony4 is also available form option block_name that override defaults.