Closed
Description
Symfony version(s) affected: 5.1.5
Description
When I create a new entity and try to send empty description
field the new
action works as expected. It passes handleRquest
and later I get a nice validation message that description
field can't be empty. When I try the same thing but editing entity the $form->handleRequest()
raises an exception "Expected argument of type \"string\", \"null\" given at property path \"description\"."
It should behave just like when I create new entity. It should pass handleRequest
and later return me a validation error.
How to reproduce
// controller - create new Activity action
public function new(Request $request)
{
$activity = new Activity();
$form = $this->createForm(ActivityType::class, $activity);
$form->handleRequest($request);
if ($form->isSubmitted() && ! $form->isValid()) {
// return errors
}
}
// controller - edit exisitng Activity action
public function edit(Request $request, Activity $activity)
{
$form = $this->createForm(ActivityType::class, $activity);
$form->handleRequest($request);
if ($form->isSubmitted() && ! $form->isValid()) {
// return errors
}
}
class Activity
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="text")
*/
private $description;
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(string $description): self
{
$this->description = $description;
return $this;
}
public static function loadValidatorMetadata(ClassMetadata $metadata)
{
$metadata->addPropertyConstraint('description', new NotBlank());
}
}
Possible Solution
I know that I can change my setter to allow null values and then it works fine. But I don't think it should be the correct behaviour.