【问题标题】:How to set validation order in symfony, field validation depends on another field?如何在symfony中设置验证顺序,字段验证取决于另一个字段?
【发布时间】:2022-01-14 23:13:57
【问题描述】:

例如,我有一个包含两个字段的实体:

    /**
     * @Assert\Range(min=1, max=self::SPEND_MAX)
     */
    public ?int $spendMax = null;

    /**
     * @Assert\NotBlank()
     * @Assert\Length(max=255)
     */
    public string $name;

如何设置 spendMax 字段,首先我需要验证字段 name 是否为空,如果为真,我可以开始验证 Range spendMax。 如果 name 为 null,则 spendMax 的验证为 false。

【问题讨论】:

    标签: symfony


    【解决方案1】:

    您可以创建自己的自定义方法来进行验证,并安排在持久化或更新实体之前调用它。

    类似的东西:

    abstract class ValidatableEntity
    {
        /**
         * @ORM\PrePersist
         * @ORM\PreUpdate
         */
        public function validate(): void
        {
            $validator = Validation::createValidatorBuilder()
                                    ->enableAnnotationMapping()
                                    ->getValidator()
            ;
            $violations = $validator->validate($this);
            if (0 !== $violations->count()) {
                throw new ValidationFailedException($this, $violations);
            }
        }
    
        /**
         * Intended to be called from the prePersist Event from EntityPersistenceEventSubscriber service
         * when this object is to be persisted.
         * The method is intended to be overridden in derived classes and does nothing here.
         * If the validation in the derived class is unsuccessful, the method should throw
         * a ValidationFailedException.
         * Note that since the object has not yet been persisted, its ID field will not be defined in this method.
         */
        public function prePersistValidation(EntityManager $entityManager): void
        {
            return;
        }
    
        /**
         * Intended to be called from the preUpdate Event from EntityPersistenceEventSubscriber service
         * when this object is to be updated.
         * The method is intended to be overridden in derived classes and does nothing here.
         * If the validation in the derived class is unsuccessful, the method should throw
         * a ValidationFailedException.
         */
        public function preUpdateValidation(PreUpdateEventArgs $args): void
        {
            // How to get an entity manager here:
            // $entityManager = $args->getObjectManager();
            return;
        }
    

    要使用它,请从这个派生实体类并覆盖 preUpdateValidation 和 prePersistValidation 方法。

    【讨论】:

      猜你喜欢
      • 2011-09-20
      • 2017-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-27
      相关资源
      最近更新 更多