1

I create a form to edit an existing object in database.

One of the field is a string, and cannot be blank or empty.

In order to display a validation error message if the value is blank at form submit, I add the following NotBlank constraint into the form type class:

...
->add(
    'firstname',
    null,
    [
        'label' => 'user.firstname',
        'constraints' => [
            new Assert\NotBlank()
        ]
    ]
)
...

I also specify the attribute type (string) into the entity:

...
private string $firstname;
...
public function setFirstname(string $firstname) {
    $this->firstname = $firstname;
}
...
public function getFirstname(): string {
    return $this->firstname;
}

When I submit the form with a blank value, I expect to see a normal form validation error message telling me the value cannot be blank. Instead, I get the following Symfony error:

Expected argument of type "string", "null" given at property path "firstname".

If I remove the type string from the entity attribute declaration, then I do not get that Symfony error anymore and the validation error message is displayed as expected.

Is there anyway to keep declaring attributes types while applying a NotBlank constraint on it ?

I have noticed that unexpected behavior only occurs when I use a form to edit an existing object but not when I create a brand new object in database. In that last case, setting a blank value with a NotBlank constraint and declaring the attribute type into the entity (private string $firstname) does not cause any issue and the form validation error message (telling the field cannot be blank) is displayed correctly.

jean553
  • 621
  • 10
  • 29
  • 1
    Set [`'empty_data' => ''`](https://symfony.com/doc/current/reference/forms/types/text.html#empty-data) in the form options. – msg May 31 '21 at 12:15
  • @msg Exactly what I was looking for. Indeed, using empty_data as a field property into the form type class solved my issue. Thanks a lot. – jean553 May 31 '21 at 13:21
  • 1
    You could also solve it by changing your typehint to `?string`, but that might not be desirable. The "new entity" thing throws me off, though, surely it has to do with it being [uninitialized](https://stackoverflow.com/questions/59265625#59265626), but it *shouldn't* be the case. – msg May 31 '21 at 14:35
  • Did you try to use `propertyPath` with a custom function, for example "get/setFormFirstname" ? https://symfony.com/doc/current/reference/forms/types/form.html#property-path With this option you can "decouple" your entity from your form without using a DTO for example. – qdequippe Jun 01 '21 at 07:18

0 Answers0