itmammoth / rails_sortable

Easy drag & drop sorting with persisting the arranged order for rails
MIT License
142 stars 37 forks source link

Create Yarn/NPM package #45

Open bpsimao opened 4 years ago

bpsimao commented 4 years ago

Case: Rails 6 with webpack

mybuddyandrew commented 4 years ago

How do I install?

itmammoth commented 4 years ago

I think it's time to make independence from jQuery...

denny commented 4 years ago

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:

sergio-rivas commented 3 years ago

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, ... ] }
TheBrockEllis commented 1 year ago

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.

javascript

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 })
      }
});

html.erb

<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.