Symfony2.6:表单处理带有数组数据而不是实体的请求

时间:2015-01-09 17:59:10

标签: php forms symfony symfony-forms

我有一个FormType,它根据在创建FormType时传递的数组创建复选框组:

//FormType.php

public function __construct(array $choices, array $choicesData)
{
    $this->choices = $choices;
    $this->choicesData = $choicesData;
}

public function buildForm(FormBuilderInterface $builder, array $options)
{
    foreach ($this->choices as $bundle => $class) {
        $choiceBuilder = $builder->create($bundle, 'form', array('virtual' => true));
        foreach ($class as $name => $perm) {
            $choiceBuilder->add(
                    $name, 'choice', array(
                    'choices' => $perm,
                    'multiple' => true,
                    'mapped' => false,
                    'expanded' => true,
                    'required' => 'false',
                    'label' => $name,
                    'data' => $this->choicesData[$bundle][$name]
                )
            );
        }
        $builder->add($choiceBuilder);
    }
    $builder->add('salvar', 'submit', array('label' => false));
}

注意:类型中没有setDefaultOptions。

然后我创建表单:

//Controller.php

 $form = $this->createForm(new PermissaoType($choices, $choicesData), $choicesData);

我的问题:但是当我使用POST getData()发送数据的 handleRequest()时,不会返回更改表单,只有在 $ choicesData 设置的表单。有谁可以帮我这个?

//Controller.php

if ($request->isMethod('POST')) {

    $form->handleRequest($request); // Not Work
    $data = $form->getData(); // Return $choicesData original
}

示例$ choiceData original:

array(
    'group1' => array(
                    'item1' => array('chk1' => false, 'chk2' => false, 'chk3' => false)
    )
);

提交表单的示例:

array(
'group1' => array(
                'item1' => array( 0 => 'chk1', 1 => 'chk3')
    )
);

返回示例$ choiceData(在$ form-> handleRequest()和$ form-> getData()之后):

array(
    'group1' => array(
                    'item1' => array('chk1' => false, 'chk2' => false, 'chk3' => false)
    )
);

非常感谢。

2 个答案:

答案 0 :(得分:1)

我解决了以下更改:

  • 将第二个$ choicesData移至 $ this-> createForm()

    $form = $this->createForm(new PermissaoType($choices, $choicesData));

  • 'data' => $this->choicesData[$bundle][$name]'data' => array_keys(array_intersect($this->choicesData[$bundle][$name], array(true)))

  • FormType 中,我将'mapped' => false更改为'mapped' => true

谢谢@Jovan Perovic

答案 1 :(得分:0)

如果我没记错的话,你需要用表格的名字封装传递的array作为密钥。

例如,如果您在FormType类中有类似的内容:

public function getName(){
    return 'some_form_name'
}

然后你应该通过:

$data = array(
    'some_form_name' => $request->request->all() // Encapsulte `POST` data
);

$form->submit($data);

或者您可以在发送数据时封装数据。然后你可以通过这本书来做:

$form->handleRequest($request);

希望这会有所帮助......