I have an entity Recipe
with a form collection of steps assigned to.
The user is able to sort the steps with drag and drop and some javascript.
To save the new order I added a field step_number
to each step, which is then automatically filled by javascript.
To make sure that the steps are displayed in the right order I use @ORM\OrderBy({"step_number" = "ASC"})
in my Recipe entity.
The only problem is: if the user submits the form and has some errors, the form gets displayed again, but not in the right step order because they are not fetched from the database.
I tried to solve this by manually ordering the collection with an eventListener like this:
$builder->get('steps')->addEventListener(FormEvents::SUBMIT, function(FormEvent $event){
$steps = $event->getData();
$steps[1]->setStepnumber('8');//does not affect the rendered form
$event->setData($steps);
\Doctrine\Common\Util\Debug::dump($event->getData());
//add some logic to sort the steps
});
This is what the dump looks like:
array(2) {
[0]=>
object(stdClass)#1212 (8) {
["__CLASS__"]=>
string(29) "CoBo\RecipeBundle\Entity\Step"
["id"]=>
int(244)
["recipe"]=>
string(31) "CoBo\RecipeBundle\Entity\Recipe"
["step_number"]=>
string(1) "2"
["description"]=>
string(3) "test description 1"
}
[1]=>
object(stdClass)#1220 (8) {
["__CLASS__"]=>
string(29) "CoBo\RecipeBundle\Entity\Step"
["id"]=>
int(245)
["recipe"]=>
string(31) "CoBo\RecipeBundle\Entity\Recipe"
["step_number"]=>
string(1) "8"
["description"]=>
string(4) "test description 2"
}
}
but the modification of $steps[1]->setStepnumber('8');
doesnt affect the rendered form. step[1]
still has the old number.
I dont know what I'm doing wrong here.
A different approach of sorting the steps would be helpfull, too.
You should use FormEvents::PRE_SET_DATA
instead. Because after FormEvents::POST_SUBMIT
the data you set doesn't get set to the form data again. Therefore you don't see the changed data.
Please look at https://github.com/symfony/Form/blob/master/Form.php to see which form event is dispatched after which operations.
Also have a look at official form events documentation.
http://symfony.com/doc/current/components/form/form_events.html