我建立一個Symfony的應用程序,並使用表單事件與一些jQuery的/ AJAX做全「國家/地區」的東西添加的元素。儘管我有一個小問題,我正在使用格式省 - >城市 - >郊區。現在,據我可以告訴我的代碼是好的,但在執行打,我一個監聽器添加到「城」的部分選擇,它拋出一個錯誤說以下內容:添加事件偵聽器,以形成由事件監聽器
The child with the name "physicalCity" does not exist.
這顯然當我嘗試將事件偵聽器添加到新創建的字段時,會發生這種情況,因此將事件偵聽器添加到由事件偵聽器創建的元素中?
的代碼段是低於...我在做什麼錯?任何幫助將非常感謝!
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('schoolName')
->add('physicalProvince', 'entity', array(
'mapped' => false,
'class' => 'MY\MainBundle\Entity\Province',
'empty_value' => 'Select a province',
'attr' => array(
'class' => 'province',
'data-show' => 'physical-city',
)
));
/*
* For the physical cities
*/
$physicalCityModifier = function(FormInterface $form, Province $province = null) {
if (null !== $province)
$cities = $province->getCities();
else
$cities = array();
$form->add('physicalCity', 'entity', array(
'mapped' => false,
'class' => 'MY\MainBundle\Entity\City',
'empty_value' => 'Select a province first',
'choices' => $cities,
'attr' => array(
'class' => 'city physical-city',
'data-show' => 'physical-suburb'
)
));
};
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function(FormEvent $event) use ($physicalCityModifier) {
$data = $event->getData();
if (is_object($data->getPhysicalSuburb()))
$province = $data->getPhysicalSuburb()->getCity()->getProvince();
else
$province = null;
$physicalCityModifier($event->getForm(), $province);
}
);
$builder->get('physicalProvince')->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) use ($physicalCityModifier) {
$province = $event->getForm()->getData();
$physicalCityModifier($event->getForm()->getParent(), $province);
}
);
/*
* For the physical suburbs
*/
$physicalSuburbModifier = function(FormInterface $form, City $city = null) {
if (null !== $city)
$suburbs = $city->getSuburbs();
else
$suburbs = array();
$form->add('physicalSuburb', null, array(
'choices' => $suburbs,
'empty_value' => 'Select a city first',
'attr' => array(
'class' => 'physical-suburb'
),
));
};
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function(FormEvent $event) use ($physicalSuburbModifier) {
$data = $event->getData();
if (is_object($data->getCity()))
$city = $data->getCity();
else
$city = null;
$physicalSuburbModifier($event->getForm(), $city);
}
);
$builder->get('physicalCity')->addEventListener(
FormEvents::POST_SUBMIT,
function(FormEvent $event) use ($physicalSuburbModifier) {
$city = $event->getForm()->getData();
$physicalSuburbModifier($event->getForm()->getParent(), $city);
}
);
}
偉大的工作!你救了我的一天,謝謝你! :) – Gianluca78
當您編輯此內容時,此功能是否正常工作?對我來說它沒有。你也可以回答你使用Symfony的哪個版本嗎? – Jeet
是的,它爲我工作。這是2.4我相信,記不清了。試着玩查詢構建器的決策案例。你的情況可能有些奇怪。並安裝XDebug!幫助很多。 – iLikeBreakfast