我正在寻找一些关于使用 Symfony2 进行动态 Ajax 选择的示例。 这篇文章似乎是解决我的疑虑的正确方法,但出了点问题。
我有 Simfony2.3,但出现错误:
An exception has been thrown during the rendering of a template ("Automatic initialization is only supported on root forms. You should set the "auto_initialize" option to false on the field "template".") in UserRegBundle:Default/en:index.html.twig at line 8.
这是我的FormType.php:
$builder->add('category', 'choice', array(
'mapped' => false,
'auto_initialize' => false,
'choices' => array(
'foo' => 'foo',
'bar' => 'bar'
)
));
$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('template')) {
$form->remove('template');
}
$cat = isset($data->category)?(string)$data->category:null;
// here u can populate ur choices in a manner u do it in loadChoices
$choices = array('ff' => 'ff', 'ee' => 'ee');
if ($cat == '1') {
$choices = array('dd' => 'dd', 'vv' => 'vv');
}
$form->add($ff->createNamed('template', 'choice', array('mapped' => false, 'auto_initialize' => false), compact('choices')));
};
// Register the function above as EventListener on PreSet and PreBind
$builder->addEventListener(FormEvents::PRE_SET_DATA, $func);
$builder->addEventListener(FormEvents::PRE_BIND, $func);
参考引用的帖子,我把 $data->category 而不是 $data['category'] 因为我收到了这个数组错误:
FatalErrorException: Error: Cannot use object of type var\www\...\Entity\User as array in /var/www/.../Bundle/MyBundle/Form/FormType.php line 101
此外,我将此选项放入 createNamed
array('auto_initialize' => false)
因为我收到了这个错误:
An exception has been thrown during the rendering of a template ("Automatic initialization is only supported on root forms. You should set the "auto_initialize" option to false on the field "template".") in UserRegBundle:Default/en:index.html.twig at line 8.
现在我遇到了这个错误,我对此一无所知:
An exception has been thrown during the rendering of a template ("Notice: Array to string conversion in /var/www/examples/test4/www/vendor/symfony/symfony/src/Symfony/Component/Form/Extension/Core/ChoiceList/ChoiceList.php line 458") in UserRegBundle:Default/en:index.html.twig at line 8.
任何人都可以帮助我吗?:/