Conditional validation of fields based on other field value in Symfony2

前端 未结 2 1882
花落未央
花落未央 2021-01-04 14:02

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)

相关标签:
2条回答
  • 2021-01-04 14:12

    You need to use validation groups. This allows you to validate an object against only some constraints on that class. More information can be found in the Symfony2 documentation http://symfony.com/doc/current/book/validation.html#validation-groups and also http://symfony.com/doc/current/book/forms.html#validation-groups

    In the form, you can define a method called setDefaultOptions, that should look something like this:

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // some other code here ...
        $builder->add('SOME_FIELD', 'password', array(
            'constraints' => array(
                new NotBlank(array(
                    'message' => 'Password is required',
                    'groups' => array('SOME_OTHER_VALIDATION_GROUP'),
                )),
            )
       ))
    }
    
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'validation_groups' => function (FormInterface $form) {
                $groups = array('Default');
                $data = $form->getData();
    
                if ($data['SOME_OTHER_FIELD']) { // then we want password to be required
                    $groups[] = 'SOME_OTHER_VALIDATION_GROUP';
                }
    
                return $groups;
            }
        ));
    }
    

    The following link provides a detailed example of how you can make use them http://web.archive.org/web/20161119202935/http://marcjuch.li:80/blog/2013/04/21/how-to-use-validation-groups-in-symfony/.

    Hope this helps!

    0 讨论(0)
  • 2021-01-04 14:20

    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.

    0 讨论(0)
提交回复
热议问题