Symfony2中:更改选择使用Ajax和验证(Symfony2: Change choices w

2019-07-03 17:11发布

方案:我有2所选择的形式。 当用户从第一个选择的东西,第二个选择被用新值填充。 这部分工作正常。

但形式没有得到验证,因为它包含了一些选择,没有在最初的形式允许的。

形成:

<?php

class MyType extends AbstractType
{
    private $category;

    public function __construct($category = null)
    {
        $this->category = $category;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('category', 'choice', array(
            'choices' => array(
                'foo' => 'foo',
                'bar' => 'bar'
            )
        );

        $builder->add('template', 'choice', array(
            'choices' => $this->loadChoices()
        );
    }

    private function loadChoices()
    {
        // load them from DB depending on the $this->category
    }
}

最初,类别为foo 。 所以foo的模板得到加载并设置为选择。 但是,如果用户选择bar ,酒吧模板得到加载。 但形式仍然有foo的选择,不验证。

什么是解决这个的最好方法?

我发现了一个办法是刚刚重新开始在控制器中的表格:

<?php

$form = $this->createForm(new MyType());

if ($request->getMethod() === 'POST') {
    if ($request->request->has($form->getName())
        && isset($request->request->get($form->getName())['category'])) {
            $form = $this->createForm(new MyType($request->request->get($form->getName())['category']));
    }

    // ...
}

这工作,而是因为它抛出我无法测试它IllegalArgumentException设定值时,只是假设默认。 有没有更好的解决方案呢? 提前致谢!

Answer 1:

我觉得你必须使用事件来管理这一点,这是比较正确的做法

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('category', 'choice', array(
        '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'])?$data['category']:null;

        // here u can populate ur choices in a manner u do it in loadChoices
        $choices = array('1' => '1', '2' => '2');
        if ($cat == 'bar') {
            $choices = array('3' => '3', '4' => '4');
        }

        $form->add($ff->createNamed('template', 'choice', null, 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);
}


文章来源: Symfony2: Change choices with ajax and validation