Symfony2 - 动态选择

时间:2013-09-16 15:41:11

标签: php ajax symfony symfony-forms symfony-2.3

我正在寻找一些关于使用Symfony2进行动态Ajax选择的示例。 This post似乎是解决我怀疑的正确方法,但出了点问题。

我是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->类别改为$ 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. 

有人能帮帮我吗? :/

0 个答案:

没有答案