Skip to content

Form submission - handleRequest raises exception when editing trying to set null instead of validate data #39106

Closed
@sabat24

Description

@sabat24

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.

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