Validating dynamically loaded choices in Symfony 2

后端 未结 5 1348
独厮守ぢ
独厮守ぢ 2020-12-08 16:08

I have a choice field type named *sub_choice* in my form whose choices will be dynamically loaded through AJAX depending on the selected value of the parent choice field, na

5条回答
  •  生来不讨喜
    2020-12-08 16:31

    you cannot not build the sub_choice validation because during you config its validator you don't know which values are valid (values depend on value of parent_choice).

    What you can do is to resolve parent_choice into entity before you make new YourFormType() in your controller. Then you can get all the possible values for sub_choice and provide them over the form constructor - new YourFormType($subChoice).

    In YourFormType you have to add __construct method like this one:

    /**
     * @var array
     */
    protected $subChoice = array();
    
    public function __construct(array $subChoice)
    {
        $this->subChoice = $subChoice;
    }
    

    and use provided values in form add:

    $builder->add('sub_choice', 'choice', array(
                    'label' => 'Sub Choice',
                    'choices' => $this->subChoice,
                    'virtual' => true
    ));
    

提交回复
热议问题