8000 [Form] Choice type empty value · Issue #31572 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content
[Form] Choice type empty value #31572
Closed
Closed
@ghostika

Description

@ghostika

Symfony version(s) affected: 4.2

Description
Given a form type for a department with a field for the leader (UserType with data_class User). The UserType has a field, salutation with the type ChoiceType Radio with the given configuration:

->add(
      'salutation',
      ChoiceType::class,
      [
          'choices' => [
               'male' => 0,
               'female' => 1,
          ],
      'expanded' => true,
      'empty_data' => null,
      'required' => false,
      'placeholder' => null,
]

The leader person is set to required => false.

Expectation
If the form is sent, without filling in the leader, then the value should be null

Happens
The leader is created with data_class and everything is set to null.

In case, the salutation is removed from the types, it works as expected.
After digging in a little bit, I've found in Symfony FormType.phpL136 -> if data_class is set and the form field is not required and is empty, then the value is null. Problem is, the isEmpty check is always false, for the ChoiceType. The Request doesn't contain any value for the choice salutation.
The root of the problem is at isEmpty in Form.phpL724 FormUtil::isEmpty($this->modelData) as the model data for the radio buttons are false.

The only solution I've found so far is a modelTransformer for the choices:

            $builder
                ->get('salutation')
                ->get(0)
                ->addModelTransformer(new CallbackTransformer(
                    function ($value) {
                        return $value;
                    },
                    function ($value) {
                        return false === $value ? null : $value;
                    }
                ));
            $builder
                ->get('salutation')
                ->get(1)
                ->addModelTransformer(new CallbackTransformer(
                    function ($value) {
                        return $value;
                    },
                    function ($value) {
                        return false === $value ? null : $value;
                    }
                ));

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

      0