Open bpsimao opened 4 years ago
How do I install?
I think it's time to make independence from jQuery...
I'm also trying to install into a rails6+webpacker project, and failing miserably. JavaScript is not my strong point (and webpacker seems to have made it 10x as confusing so far) so I have no idea whether I'm failing because I'm missing something, or because its not actually possible currently... clues welcome! :slightly_smiling_face:
You do this in ES6 by custom setting up this package with custom configuration on change. https://github.com/SortableJS/Sortable
Then you need to do post request to '/sortable/reorder', and give the following params:
// pass array of sortable_id's from table in new order
{ rails_sortable: [ sortable_id, ... ] }
To add a bit more context to sergio-rivas's answer from above, this is how I accomplished using this Gem with Rails 6 and webpacker.
import Sortable from 'sortablejs';
var sortables = document.querySelector('#sortable');
Sortable.create(sortable, {
draggable: '.list-group-item',
dataIdAttr: 'data-sortable-id',
onUpdate: function (event) {
const listItems = event.target.querySelectorAll('.list-group-item');
const sortableIds = Array.from(listItems).map(elm => elm.dataset.sortableId)
$.post('/sortable/reorder', { rails_sortable: sortableIds })
}
});
<ul class="sortable">
<li class="list-group-item" data-sortable-id="<%= item.sortable_id %>">
...
Using the onUpdate
from the Sortable library, we can hook into when the drag-n-drop has ended. I used the event
object to find all of the list-group-item
elements within the parent and map over them to get their sortable Ids. Then a quick post request to the /sortable/reorder endpoint.
I did have troubles with the CSRF tokens and ended up disabling enforcement for the reorder endpoint with an initializer as described here.
Case: Rails 6 with webpack