Home > database >  How can I create a method in my entity that accepts empty entries?
How can I create a method in my entity that accepts empty entries?

Time:07-16

I want do have the opportunity that in case no desription is added in my form, there will not be an error message. What is the correct way to this?

Here my approach:

in my Controller:

$entity->setDescription($data['description']) ?? null;

my entity:

/**
 * @ORM\Column(type="text", length=65535)
 *
 */
private string $description;




 public function setDescription(string $description): void
    {
        $this->description = $description;
    }

the Error message:

App\Entity\Event::setDescription(): Argument #1 ($description) must be of type string, null given, called in /src/Controller/Admin/myController.php on line 109

CodePudding user response:

In your function, you only set $description type to be string but you put null in to it, so an error occurred.

You can do $entity->setDescription($data['description'] ?? ''); to set the description to empty string if there is no description added by mean description is a null.

Or you can make $description can be null too by:

public function setDescription(?string $description): void
{
    $this->description = $description;
}

In this case you need to check whether the $description is not null in order to be shown in HTML or somewhere.

  • Related