Symfony Assert\Expression 将实体 属性 与今天的日期进行比较

Symfony Assert\Expression compare entity property with today's date

我想将 Assert\Expression 添加到我的实体的 属性。 当所选的 "Effective date" (this.getEffective()) 是过去或今天时,应该会弹出错误消息。我只是想不通,如何将那个日期与今天的日期进行比较。

    /**
 * @var boolean
 * @ORM\Column(type="boolean", nullable=true)
 * @Assert\Expression(
 *     "this.getEffective() > today",
 *     message="The effective date must be in the future!")
 */
private $status_stealth;

我对 nowdatetime.now() 进行了相同的尝试,并且 google 大约很多,但我还没有发现有人实际将另一个值与断言表达式中的当前日期进行比较的任何内容。

想法?

您可以在您的实体中定义一个新方法,该方法将return今天的日期时间并在您的表达式中进行比较

/**
 * @var boolean
 * @ORM\Column(type="boolean", nullable=true)
 * @Assert\Expression(
 *     "this.getEffective() > this.getCurrentDate()",
 *     message="The effective date must be in the future!")
 */
private $status_stealth;

public function getCurrentDate(){
    return new \DateTime();
}

默认情况下,表达式语法只支持一个函数,constant()。反过来,表达式验证器带有一个或两个变量(一个验证值和一个上下文对象)。您可以将值传递给实体的验证方法。

/**
 * @Assert\Expression(expression="this.isStatusValid(value)")
 */
private $status;

public function isStatusValid($status) {
    $currentDate = new \DateTimeImmutable();
    return in_array($status, [1, 2, 3]) && $this->targetDate > $currentDate;
}

如果出现一些错误,请调试。

public function isStatusValid($status) {
    $currentDate = new \DateTimeImmutable();
    var_dump($this->targetDate);
    var_dump($currentDate);
    die();
    return in_array($status, [1, 2, 3]) && $this->targetDate > $currentDate;
}

文档链接:Expression Constraint, Expression Syntax.

如果需要,可以使用symfony的表达式:

  $builder->add(
            'start',
            DateTimeType::class,
            [
                'label' => 'Campaign Starts At',
                'data' => $entity->getStart(),
                'required' => true,
                'disabled' => $disabled,
                'widget'  => 'single_text',
                'constraints' => [
                    new Assert\GreaterThan(['value' => 'today'])
                ]
            ]
        );