Skip to content

[Form] Optional empty text fields are always NULL instead of the empty string #22192

@curry684

Description

@curry684
Q A
Bug report? yes
Feature request? no
BC Break report? no
RFC? no
Symfony version master (likely 3.x and 2.x as well)

Consider a basic data class:

class MyClass
{
  private $value = '';

  public function setValue(string $value)
  {
    $this->value = $value;
  }

  public function getValue(): string
  {
    return $this->value;
  }
}

Map a basic form with the field optional:

$form = $this->createFormBuilder(new MyClass())
            ->add('value', TextareaType::class, [
                'required' => false,
            ])
            ->add('create', SubmitType::class)
            ->getForm();
// etc.

Submit the form with the field empty and we get an InvalidArgumentException:

Expected argument of type "string", "NULL" given
in vendor/symfony/symfony/src/Symfony/Component/PropertyAccess/PropertyAccessor.php at line 275

As the value itself is empty, the Form sets its $modelData to NULL, while $normData and $viewData are correctly the empty string. PropertyPathMapper::mapFormsToData subsequently attempts to set the property to null, which would have been fine if not for the type hinting in the setter, causing the exception.

edit: if I remove the type hint from the setter I then get a Doctrine error as the field itself is mandatory yet NULL was inserted. I most definitely want users to be able to have the empty string in there, not null. So this is in the Form component, not the PropertyAccess end doing as it's told.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions