Symfony 4 自定义约束 atPath 不起作用

标签 symfony symfony4

我有一个包含日期类型和复选框类型的表单,当复选框被选中时,日期类型只是必填字段。

因此复选框称为overrideDates,日期字段为overrideDate

所以我创建了一个这样的约束:

<?php

namespace App\Validator\Constraints\Instruction;

use App\Validator\Validators\Instruction\MainInstructionValidator;
use Symfony\Component\Validator\Constraint;

/**
 * Class MainInstructionConstraint
 * @package App\Validator\Constraints\Instruction
 * @Annotation
 */
class MainInstructionConstraint extends Constraint{

    /**
     * @var string
     */
    public $overrideDatesError = "You Must Enter An Override Date";

    /**
     * @return string
     */
    public function getTargets() : string{

        return self::CLASS_CONSTRAINT;
    }

    /**
     * @return string
     */
    public function validatedBy() : string{
        return MainInstructionValidator::class;
    }
}

像这样的验证器:

<?php

namespace App\Validator\Validators\Instruction;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 * Class MainInstructionValidator
 * @package App\Validator\Validators\Instruction
 */
class MainInstructionValidator extends ConstraintValidator{

    /**
     * @param mixed $instruction
     * @param Constraint $constraint
     */
    public function validate($instruction, Constraint $constraint){

        if($instruction->isOverridingDates()){

            // make sure the override date is set
            if(!is_null($instruction->getOverrideDate()) || !is_a($instruction->getOverrideDate(),'DateTime')){
                $this->context->buildViolation($constraint->overrideDatesError)
                    ->atPath('overrideDate')->addViolation();
            }
        }

    }
}

验证工作正常,错误消息来自约束正常,但由于某种原因,它没有显示在以下表单上:

form_errors(form.overrideDate)

我的印象是 atPath() 的用途,所以我可以告诉它在哪个表单字段上显示错误,因为我将整个实体传递给验证器。

最佳答案

这现在有点旧了,但这对我有用。

改变

atPath('overrideDate')

atPath('[overrideDate]')

克雷格

关于Symfony 4 自定义约束 atPath 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55417115/

相关文章:

service - 如何在 Symfony 4 中加载供应商类作为服务?

php - WebSocketBundle Symfony 4 集成

Symfony4/Behat 注入(inject)功能不工作 "you have requested a non-existen service"

php - 如何使用 ConsoleLogger 输出日期?

symfony - render(controller()) 的替代品

php - Doctrine ODM 在运行时选择数据库

symfony - 我已经定义了捆绑 Controller 和路由,但我得到 "Error: the controller does neither exist as service nor as class"

symfony - 在 Twig 中显示 Flash 消息的正确方法

Symfony:如何调试意外的 '\' (T_NS_SEPARATOR)

ios - 如何修复错误 "Failed to load ressource : Acces-control-allow-origin cannot contain more than one origin"