Why do I receive “This value should be of type string” when using a DateTime constraint on Symfony 5?

时光总嘲笑我的痴心妄想 提交于 2020-03-09 05:41:07

问题


I have the following entity (only attached the relevant parts):

use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ApiResource(mercure=true)
 * @ORM\Entity(repositoryClass="App\Repository\EventRepository")
 */
class Event {
    /**
     * @ORM\Column(type="datetime")
     * @Assert\DateTime
     * @Assert\NotNull
     */
    private $createdAt;

    public function __construct() {
        $this->createdAt = new \DateTime();
    }

    public function getCreatedAt(): ?\DateTimeInterface {
        return $this->createdAt;
    }

    public function setCreatedAt(\DateTimeInterface $createdAt): self {
        $this->createdAt = $createdAt;
        return $this;
    }
}

Its repository:

class EventRepository extends ServiceEntityRepository {
    public function __construct(ManagerRegistry $registry) {
        parent::__construct($registry, Event::class);
    }
}

When creating a POST request to the event endpoint (via Postman or the Swagger UI), it fails with the following exception:


回答1:


I believe you are using the wrong of assertion.

Date expects a string or an object that can be cast into a string. And a DateTimeInterface is neither.

You should be using a Type constraint.

/**
 * @Assert\Type("\DateTimeInterface")
 */
 private $createdAt;

The ability to use Assert\Date to validate DateTime objects was deprecated on Symfony 4.2, and on Symfony 5.0 it was removed altogether.



来源:https://stackoverflow.com/questions/60227679/why-do-i-receive-this-value-should-be-of-type-string-when-using-a-datetime-con

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!