Skip to content

Symfony5: setting ['required'=>false] to the form prevents overriding "required" in fields #39943

Closed
@Ser5

Description

@Ser5

Symfony version(s) affected: 5.2.1

Description
The issue stems from here:
https://stackoverflow.com/questions/65823351/symfony5-forms-how-to-disable-required-for-all-fields-by-default

Symfony has the required flag enabled by default for all form fields - the feature I don't need, I need to have it backwards - to have all fields not required by default.

I have two methods on my mind to do this:

  1. Set ['required'=>false] to the very top form
  2. Force ['required'=>false] via an extension

But both methods produce puzzling results:

  • If I don't set any required on the form, then for the individual fields I can set required to whichever I want - true or false
  • If I set ['required'=>true] on the form, I can freely override required also
  • But if on the form I set ['required'=>false], then Symfony refuses to override required on any individual field - required stays false forever
  • The same results I get when forcing ['required'=>false] with the help of an extension

For the demonstration see the test project I put on github. It creates a form and 3 fields inside it.

  • 1st field uses default required
  • 2nd one uses ['required'=>true]
  • 3rd one uses ['required'=>false]

When you run the index.php from CLI, it shows required values for these 3 fields.

You can modify the behavior of the form by using command-line options:

  • No options - form with default required
  • --set=form --required=true - form with ['required'=>true]
  • --set=form --required=false - form with ['required'=>false]
  • --set=ext --required=false - form with required forced to false via an extension

How to reproduce
https://github.com/Ser5/SymfonyRequireBug

git clone https://github.com/Ser5/SymfonyRequireBug.git
cd SymfonyRequireBug/lib/
composer install
cd ../

php index.php
php index.php --set=form --required=true
php index.php --set=form --required=false
php index.php --set=ext --required=false

The main question is: is this behavior intended? I find it totally confusing and counterintuitive. Or is this a bug? Should it be fixed?

Possible Solution
Allow overriding required on form fields despite the value set on the form.

Additional context
Windows 10
PHP 8

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions