Drag and drop ordering of formset
joewandy opened this issue · comments
Following https://djangosnippets.org/snippets/1053/, I manage to add an additional field that allows the user to reorder rows in the formset
But I wonder if anyone has managed to add a Jquery drag and drop functionality to reorder the formset rows? It would be useful.
I'm doing it right now. With Jquery-ui sortable.
Just doing by a ordering field and that's it. It's quite simple in fact
Any chance you could share the code? Thanks!
Don't know if it will help you:
Of course you've to adapt it to fit your structure
function initSorting(){
$(".section").sortable({
items: ".inline",
handle:".sort-button",
axis: "y",
stop: function(event, ui){
var $current_sort = ui.item.find('.entry-order-field'),
current_val = $current_sort.val(),
$next_sort = ui.item.prev().find('.entry-order-field');
if (!$next_sort.length > 0){
$next_sort = ui.item.next().find('.entry-order-field');
}
var next_val = $next_sort.val();
$current_sort.val(next_val);
$next_sort.val(current_val);
}
});
};
Couldn't get pythdasch to accomplish anything useful (not sure exactly what it's supposed to achieve, since it only manipulates the next and/or the previous row, not all of them), but here's the simple approach I went with (using a table-inline formset):
$('.images tbody').sortable({
axis: 'y',
placeholder: 'ui-state-highlight',
forcePlaceholderSize: 'true',
items: '> tr:not(.hidden)'
});
$('form').submit(function() {
$('.images tbody').find('tr:visible').each(function(index) {
// This should target the order field within the row
$(this).find('input[type="number"]').val(index);
});
})
It initializes the sortable stuff, and then makes sure the order field is set before the form is submitted. Very simple, and works flawlessly.