Chr*_*ris 19 validation symfony symfony-2.1
我在我的表单中有一个名为*sub_choice*的选择字段类型,其选择将通过AJAX动态加载,具体取决于父选择字段的选定值,名为*parent_choice*.加载选项非常有效,但在提交时验证sub_choice的值时遇到问题.它给出了"此值无效"验证错误,因为提交的值在构建时不在sub_choice字段的选项中.那么有没有办法可以正确验证sub_choice字段的提交值?下面是构建表单的代码.我正在使用Symfony 2.1.
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('parent_choice', 'entity', array(
'label' => 'Parent Choice',
'class' => 'Acme\TestBundle\Entity\ParentChoice'
));
$builder->add('sub_choice', 'choice', array(
'label' => 'Sub Choice',
'choices' => array(),
'virtual' => true
));
}
Run Code Online (Sandbox Code Playgroud)
小智 22
要做到这一点,您需要sub_choice
在提交表单之前覆盖该字段:
public function buildForm(FormBuilderInterface $builder, array $options)
{
...
$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
$parentChoice = $event->getData();
$subChoices = $this->getValidChoicesFor($parentChoice);
$event->getForm()->add('sub_choice', 'choice', [
'label' => 'Sub Choice',
'choices' => $subChoices,
]);
});
}
Run Code Online (Sandbox Code Playgroud)
小智 -6
假设对于子选择你有 id 的权利吗?创建并清空具有一定数量值的数组,并将其作为选择
$indexedArray = [];
for ($i=0; $i<999; $i++){
$indexedArray[$i]= '';
}
然后'choices' => $indexedArray,
:)