Symfony2 を使用した Dynamic Ajax Select に関するサンプルを探していました。 この投稿は私の疑問に対する正しい解決策のように見えましたが、何かが間違っていました.
私は 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.
誰でも私を助けてもらえますか?:/