How to add a custom default option to all form types in Symfony 5?

Viewed 126

I need to add a custom option to all types in my project.

The goal is to add a is_translated option that would be false by default, and I could pass true to any field that can be translated, in order to get it in the template and add a flag next to the label.

Translated fields could be TextType, TextareaType, or any of the many custom Types that I have already created. That's why I'd like to add this option to all Types.

To add it to only one Type, I would do :

$resolver->setDefaults([
    'is_translated' => false,
]);

How can I add this option to all the Types ?

1 Answers

I found the solution :

I needed to create a FormExtension, as explained here : https://symfony.com/doc/current/form/create_form_type_extension.html

Form type extensions allow you to modify any existing form field types across the entire system.

Here's the code I came up with :

namespace App\Form\Extension;

use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;

class FormTypeExtension extends AbstractTypeExtension
{
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $view->vars['is_translated'] = $options['translated'];
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'is_translated' => false,
        ]);
    }

    public static function getExtendedTypes(): iterable
    {
        return [FormType::class];
    }
}
Related