jean553
jean553

Reputation: 733

Forms and Entities - NotBlank constraint with not nullable string entity attribute

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.

Upvotes: 1

Views: 3497

Answers (0)

Related Questions