How to Define Conditional Validation in yml

Asked 1 years ago, Updated 1 years ago, 77 views

When defining the form validation function of symfony2 in yml, I would like to make the field B required only if the value of the field A is 1. How do I write such a conditional validation in yml?

Thank you for your cooperation.

symfony2

2022-09-30 13:58

1 Answers

I think the response method will change depending on where the motivation to make it required is.
If you want to control it on the form (browser side), I think JavaScript should handle it rather than Symfony.

If the field A is a validation error if the field B is empty only if the value of the field A is 1, then you can use Callback.

Yaml side

#src/AppBundle/Resources/config/validation.yml
AppBundle\Entity\Author:
    constructs:
        - Callback: validate

Entity side

<?php
  use Symphony\Component\Validator\Context\ExecutionContextInterface;


  class author 
  {
    private$a;

    private$b;

    public function validate(ExecutionContextInterface$context){
      if(!empty($this->a)&empty($this->b)){
        $context->buildViolation('If you have entered A, be sure to enter B.')
          ->atPath('b')
          ->addValidation();          
      }        
    }


  }

This callback validation gives you the flexibility to validate.

Refer to the Symfony documentation for more information.The information is detailed.
http://symfony.com/doc/current/reference/constraints/Callback.html


2022-09-30 13:58

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.