【发布时间】:2016-07-20 09:18:33
【问题描述】:
我的 symfony 表单中有两个实体下拉字段。在前端,我根据第一个下拉选择值的值使用 ajax 更改第二个下拉淹没的选项列表。并在提交表单后,我收到错误消息,
This value is not valid.
下面是代码;
/**
* @ORM\ManyToOne(targetEntity="State")
* @ORM\JoinColumn(name="province_id", referencedColumnName="id")
*/
protected $Province;
/**
* @ORM\ManyToOne(targetEntity="District")
* @ORM\JoinColumn(name="district_id", referencedColumnName="id")
*/
protected $District;
在形式上,
->add('domicileDistrict','entity', [
'label' => ucwords('District'),
'class'=>'GeneralBundle\Entity\District',
'required' => true,
'mapped' => true,
'attr' => ['class' => 'form-control'],
'label_attr' => ['class' => 'control-label'],
])
->add('domicileProvince','entity', [
'label' => ucwords('Province'),
'class'=>'GeneralBundle\Entity\State',
'required' => true,
'attr' => ['class' => 'form-control select2'],
'label_attr' => ['class' => 'control-label'],
])
在前端,
$("#profile_from_type_domicileProvince").change(function() {
var state = $('option:selected', this).val();
getDistrictByState(state);
});
function getDistrictByState(state){
var dict = {
type: "POST",
url: "{{ url('ajax_district_by_stateId') }}?id=" + state,
success: function(e) {
$("#profile_from_type_domicileDistrict option").remove();
$.each(e, function(e, p) {
$("#profile_from_type_domicileDistrict").append($("<option />", {
value: e,
text: p
}));
});
}
};
$.ajax(dict);
}
更新:添加 PRE_SUBMIT 事件;
在@Alsatian 提出建议后,我更新了我的表单并添加了如下事件,但选择第一个下拉菜单时没有任何反应。
$builder->addEventListener(FormEvents::PRE_SUBMIT, [$this, 'preSubmitData']);
public function preSubmitData(FormEvent $event){
$form = $event->getForm();
$data = $event->getData();
if (array_key_exists('Province', $data)) {
$state = $data['Province'];
$event->getForm()
->add('District','entity', [
'label' => ucwords('District'),
'class'=>'GeneralBundle\Entity\District',
'required' => true,
'mapped' => true,
'query_builder' => function(DistrictRepository $repository) use ($state) {
$qb = $repository->createQueryBuilder('d')
->andWhere('d.verified = :verified')
->andWhere('d.active = :active')
->setParameter('verified', true)
->setParameter('active', true);
if ($state instanceof State) {
$qb = $qb->where('d.state = :state')
->setParameter('state', $state);
} elseif (is_numeric($state)) {
$qb = $qb->where('d.state = :state')
->setParameter('state', $state);
} else {
$qb = $qb->where('d.state = 1');
}
return $qb;
},
'attr' => ['class' => 'form-control select2'],
'label_attr' => ['class' => 'control-label'],
]);
}
}
【问题讨论】:
-
PRE_SUBMIT对您要求的第一个选择框的更改没有任何作用。提交表单时,它将填充所需的选项到动态选择框。提交时您仍然收到This value is not valid.错误吗? -
@Jeet 是的,我得到了错误,所以在预提交事件中做了什么,我得到了选定的下拉值并将其转换为对象并设置表单字段数据属性。现在它没有提示任何错误。
标签: javascript php jquery ajax symfony