I have a FormType that creates checkboxes groups based on an array that is passed in the creation of that 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));
}
Notice: No setDefaultOptions in Type.
Then I create the form:
//Controller.php
$form = $this->createForm(new PermissaoType($choices, $choicesData), $choicesData);
My Problem: but when I making the handleRequest() of the data sent with POST getData() does not return the change of the form, only that which is set at $choicesData . Could anyone help me on this?
//Controller.php
if ($request->isMethod('POST')) {
$form->handleRequest($request); // Not Work
$data = $form->getData(); // Return $choicesData original
}
Example $choiceData original:
array(
'group1' => array(
'item1' => array('chk1' => false, 'chk2' => false, 'chk3' => false)
)
);
Example of form submitted:
array(
'group1' => array(
'item1' => array( 0 => 'chk1', 1 => 'chk3')
)
);
Example $choiceData returned (after $form->handleRequest() and $form->getData()):
array(
'group1' => array(
'item1' => array('chk1' => false, 'chk2' => false, 'chk3' => false)
)
);
Thank a lot.
I solved with changes below:
Remove second $choicesData to $this->createForm()
$form = $this->createForm(new PermissaoType($choices, $choicesData));
'data' => $this->choicesData[$bundle][$name]
to 'data' => array_keys(array_intersect($this->choicesData[$bundle][$name], array(true)))
In FormType I changed 'mapped' => false
to 'mapped' => true
Thanks @Jovan Perovic
If I remember correctly, you need to encapsulate passed array
with form's name as a key.
For example, if you have something like this in your FormType class:
public function getName(){
return 'some_form_name'
}
Then you should pass:
$data = array(
'some_form_name' => $request->request->all() // Encapsulte `POST` data
);
$form->submit($data);
Or you could encapsulate the data when you send it. Then you could do by-the-book:
$form->handleRequest($request);
Hope this helps...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.