【发布时间】:2017-03-15 18:27:26
【问题描述】:
我正在使用 symfony 2.8 和 php 7 并且确实遇到了用地理数据(国家/州/省/市/邮编)填写表格的问题。
我只需要 5 个选择框,第一个已经填满,其他的在我之前更改选择后重新加载。例如,如果我更改国家/地区,则选择的州将充满新值。
我今天阅读了很多示例,但仍然不知道如何运行它。
这是我的代码:
如果有 5 个方法返回数组,你可以通过名称了解它们返回的内容:
private function getCountryList()
private function getStatesList( $idCountry )
private function getProvinceList( $idState )
private function getCityList( $idProvince )
private function getZipList( $idCity )
这是我的表格:
$locationForm = $builder->create('location', FormType::class, array('data_class' => 'M3\CoreBundle\Entity\Location',
'by_reference' => true));
$locationForm->add('GeoCountryId', ChoiceType::class, array(
'label' => 'Country',
'choices' => $this->getCountryList(),
));
$locationForm->add('GeoStateId', ChoiceType::class, array('label' => 'State', 'choices' => array()));
$locationForm->add('GeoProvinceId', ChoiceType::class, array('label' => 'Province', 'choices' => array()));
$locationForm->add('GeoCityId', ChoiceType::class, array('label' => 'City', 'choices' => array()));
$locationForm->add('GeoZipCodeId', ChoiceType::class, array('label' => 'Zip Code', 'choices' => array()));
我尝试添加一些这样的事件
$locationForm->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) {
$data = $event->getData();
$form = $event->getForm();
$country = $form->get('GeoCountryId')->getData();
//here i tried a lot of things
$form->get('GeoStateId')->setData($this->getStatesList($country));
}
);
我尝试了很多东西,但一无所获。我阅读了本手册http://symfony.com/doc/2.8/form/dynamic_form_modification.html#form-events-user-data,但也没有任何效果。你能帮帮我吗?
也许我只需要添加javascript事件“更改”以手动选择并加载所有数据?
【问题讨论】:
-
您需要在 JS 中处理它,例如在
onChange事件中使用 ajax 调用服务器以获取下一个select的数据。然后你还需要一个服务器端表单中的事件监听器,但它只是为了能够在提交期间验证表单。