Reputation: 1256
I am working on a Symfony 3.3 project that uses Sonata. I have created two entities: Question and QuestionGallery. I am using a many-to-many relationship and sonata_type_model to allow users to nest a set of Questions within each Question Gallery. My formMapper->add() call looks like this:
$formMapper
->add('name')
->add('visible')
->add(
'questions',
'sonata_type_model',
['expanded' => false, 'by_reference' => true, 'multiple' => true, 'required' => false]
)
;
So far so good. Now I want to allow users to reorder the Question objects in an arbitrary order of their choosing. That's where I run into a problem: Even when I remove an item from the middle of the list and re-append it at the end, it reverts to being in the middle when I save the QuestionGallery. I believe the Questions are being ordered by ID, in other words.
In the short term, I have simple added a "rank" field the Question entity, which works well enough. But I am curious: Is there a built-in way to allow arbitrary reordering without introducing an extra field that users must manually fill out? (Bonus karma if you know of a way that allows users to drag and drop the entities.)
Upvotes: 1
Views: 1251
Reputation: 66
You can use doctrine mapping with annotation:
/**
..ect..
*@ORM\OrderBy({"ranking" = "ASC"})
*/
protected $questions;
And in your Admin:
$formMapper
->add(
'questions',
'sonata_type_collection',
[
'expanded' => false,
'by_reference' => true,
'multiple' => true,
'required' => false
],
[
'edit' => 'inline',
'inline' => 'table',
'sortable' => 'ranking',
'order' => 'ASC'
]
)
;
Upvotes: 5