Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
596 views
in Technique[技术] by (71.8m points)

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

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

use ApiPlatformCoreAnnotationApiResource;
use DoctrineORMMapping as ORM;
use SymfonyComponentValidatorConstraints as Assert;

/**
 * @ApiResource(mercure=true)
 * @ORMEntity(repositoryClass="AppRepositoryEventRepository")
 */
class Event {
    /**
     * @ORMColumn(type="datetime")
     * @AssertDateTime
     * @AssertNotNull
     */
    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:

profiler

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

/**
 * @AssertType("DateTimeInterface")
 */
 private $createdAt;

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...