Fabian
Fabian

Reputation: 905

Set defaults for all Symfony Form Types

Is it possible to set a default for all Symfony FormTypes?

We are currently working on an API Backend based on Symfony (3.3). In the Frontend we have our entities as objects looking like: {"id": 1, "username": "foo" ..... }

If we want to update the entity, we JSON.stringfy the object and send it to the server.

But if we bind the request to our entities via $form->submit($request) we get an error ("This form should not contain extra fields.") because we don't have (and don't want to use!) "id" in out FormTypes.

So we have to set allow_extra_fields to true in every single FormType

public function setDefaultOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(['allow_extra_fields' => true]);
}

Is there a way to configure this as a default for all FormTypes (without extending an custom FormType or something like this)?

Upvotes: 4

Views: 704

Answers (1)

yceruto
yceruto

Reputation: 9575

You can create a form type extension to change this default value to true for all form types.

Form type extensions are incredibly powerful: they allow you to modify any existing form field types across the entire system.

class MyFormTypeExtension extends AbstractTypeExtension
{    
    public function configureOptions(OptionsResolver $resolver)
    {  
        $resolver->setDefaults(array(
            'allow_extra_fields' => true,
        ));
    }

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

See more about how to register type extensions in Official documentation.

Note: The allow_extra_fields option is defined in FormTypeValidatorExtension , so make sure your custom type extension is registered after it to override the default value, otherwise use the priority tag attribute to ensure it.

Upvotes: 6

Related Questions