phpsymfonysymfony-formssymfony-validator

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?


Solution

  • I suggest you to use a callback validator.

    For example, in your entity class:

    <?php
    
    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 helps.