spiridon spiridon - 1 year ago 93
PHP Question

Conditional validation of fields based on other field value in Symfony2

So here is the scenario: I have a radio button group. Based on their value, I should or shouldn't validate other three fields (are they blank, do they contain numbers, etc).

Can I pass all these values to a constraint somehow, and compare them there?

Or a callback directly in the controller is a better way to solve this?

Generally, what is the best practice in this case?


I suggest you to use a callback validator

As Example, in your entity class:


use Symfony\Component\Validator\Constraints as Assert;

 * @Assert\Callback(methods={"myValidation"})
class Setting {

    public function myValidation(ExecutionContextInterface $context)
        if (
                $this->getRadioSelection() == '1' // RADIO SELECT EXAMPLE
                ( // CHECK OTHER PARAMS
                 $this->getFiled1() == null
            $context->addViolation('mandatory params');
       // put some other validation rule here

Otherwise you can build your own custom validator as described here.

Let me know you need more info.

Hope this help