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
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
© 2024 OneMinuteCode. All rights reserved.