Symfony2 Form Validator - Comparing old and new values before flush

前端 未结 4 576
暗喜
暗喜 2021-02-05 10:40

I was wondering if there is a way to compare old and new values in a validator within an entity prior to a flush.

I have a Server entity which renders to a

4条回答
  •  走了就别回头了
    2021-02-05 10:55

    A complete example for Symfony 2.5 (http://symfony.com/doc/current/cookbook/validation/custom_constraint.html)

    In this example, the new value for the field "integerField" of the entity "NoDecreasingInteger" must be higher of the stored value.

    Creating the constraint:

    // src/Acme/AcmeBundle/Validator/Constraints/IncrementOnly.php;
    

    Creating the constraint validator:

    // src/Acme/AcmeBundle/Validator/Constraints/IncrementOnlyValidator.php
    em = $em;
      }
    
      public function validate($object, Constraint $constraint)
      {
        $new_value = $object->getIntegerField();
    
        $old_data = $this->em
          ->getUnitOfWork()
          ->getOriginalEntityData($object);
    
        // $old_data is empty if we create a new NoDecreasingInteger object.
        if (is_array($old_data) and !empty($old_data))
          {
            $old_value = $old_data['integerField'];
    
            if ($new_value < $old_value)
              {
                $this->context->buildViolation($constraint->message)
                  ->setParameter("%new%", $new_value)
                  ->setParameter('%old%', $old_value)
                  ->addViolation();
              }
          }
      }
    }
    

    Binding the validator to entity:

    // src/Acme/AcmeBundle/Resources/config/validator.yml
    Acme\AcmeBundle\Entity\NoDecreasingInteger:
      constraints:
         - Acme\AcmeBundle\Validator\Constraints\IncrementOnly: ~
    

    Injecting the EntityManager to IncrementOnlyValidator:

    // src/Acme/AcmeBundle/Resources/config/services.yml
    services:
       validator.increment_only:
            class: Acme\AcmeBundle\Validator\Constraints\IncrementOnlyValidator
            arguments: ["@doctrine.orm.entity_manager"]
            tags:
                - { name: validator.constraint_validator, alias: increment_only }
    

提交回复
热议问题