Order of Symfony form CollectionType field
You need to use finishView method of your form type.
Here is the example of code:
public function finishView(FormView $view, FormInterface $form, array $options){ usort($view['photos']->children, function (FormView $a, FormView $b) { /** @var Photo $objectA */ $objectA = $a->vars['data']; /** @var Photo $objectB */ $objectB = $b->vars['data']; $posA = $objectA->getSortOrder(); $posB = $objectB->getSortOrder(); if ($posA == $posB) { return 0; } return ($posA < $posB) ? -1 : 1; });}
It is possible to combine arrow function https://www.php.net/manual/en/functions.arrow.php with spaceship https://www.php.net/manual/en/migration70.new-features.php with PHP 7.
With the previous example :
public function finishView(FormView $view, FormInterface $form, array $options){ usort($view['photos']->children, fn (FormView $a, FormView $b) => $a->vars['data']->getSortOrder() <=> $b->vars['data']->getSortOrder());}
A more advanced example, ordered any collection from everywhere by using any ordered field :
public function finishView(FormView $view, FormInterface $form, array $options){ $view['blocks']->children = array_merge($view['blockTexts']->children, $view['blockImages']->children); usort($view['blocks']->children, fn (FormView $a, FormView $b) => $a->vars['data']->orderNumber <=> $b->vars['data']->orderNumber);}