Symfony2:使用ajax和验证来更改选项

时间:2012-11-10 11:51:52

标签: php forms symfony

场景:我有一个包含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而只是假设默认值。有没有更好的解决方案呢?提前谢谢!

1 个答案:

答案 0 :(得分:21)

我认为你必须使用事件来管理这个,这是更正确的方式

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);
}