Rob*_*_UK 13 forms validation symfony
我有一个下拉表单元素.最初它开始是空的,但是在用户进行了一些交互之后,它通过javascript填充了值.多数民众赞成.但是,当我提交它时,它总是返回验证错误This value is not valid..
如果我将项目添加到表单代码中的选项列表中,它将验证确定,但是我正在尝试动态填充它,并且预先将项目添加到选项列表不起作用.
我认为这个问题是因为表单正在验证一个空的项目列表.我根本不希望它根据列表进行验证.我已将验证设置为false.我将chocie类型切换为文本,并始终通过验证.
这只会针对添加到选项列表中的空行或项进行验证
$builder->add('verified_city', 'choice', array(
'required' => false
));
Run Code Online (Sandbox Code Playgroud)
类似的问题在这里没有得到回答.
在Symfony 2中验证动态加载的选项
假设你不知道所有可用的选择是什么.它可以从外部Web源加载吗?
经过多年的努力,试图找到它.你基本上需要添加一个PRE_BIND监听器.在绑定准备验证的值之前,您可以添加一些额外的选择.
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormEvent;
public function buildForm(FormBuilderInterface $builder, array $options)
{
// .. create form code at the top
$ff = $builder->getFormFactory();
// function to add 'template' choice field dynamically
$func = function (FormEvent $e) use ($ff) {
$data = $e->getData();
$form = $e->getForm();
if ($form->has('verified_city')) {
$form->remove('verified_city');
}
// this helps determine what the list of available cities are that we can use
if ($data instanceof \Portal\PriceWatchBundle\Entity\PriceWatch) {
$country = ($data->getVerifiedCountry()) ? $data->getVerifiedCountry() : null;
}
else{
$country = $data['verified_country'];
}
// here u can populate choices in a manner u do it in loadChoices use your service in here
$choices = array('', '','Manchester' => 'Manchester', 'Leeds' => 'Leeds');
#if (/* some conditions etc */)
#{
# $choices = array('3' => '3', '4' => '4');
#}
$form->add($ff->createNamed('verified_city', 'choice', null, compact('choices')));
};
// Register the function above as EventListener on PreSet and PreBind
// This is called when form first init - not needed in this example
#$builder->addEventListener(FormEvents::PRE_SET_DATA, $func);
// called just before validation
$builder->addEventListener(FormEvents::PRE_BIND, $func);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14952 次 |
| 最近记录: |