I need help with saving a drag n drop menu order. I use http://farhadi.ir/projects/html5sortable to drag and update the list. Each menu item has two hidden fields: id and order. The order is updated dynamically when dropped. I don't know how to turn the fields id and order into a correct array so I can update via AJAX into Laravel.
HTML - Menu :
<div>
<input name="menu[1][id]" type="hidden" value="1">
<input name="menu[1][order]" class="new-order" type="hidden" value="3">
</div>
<div>
<input name="menu[2][id]" type="hidden" value="2">
<input name="menu[2][order]" class="new-order" type="hidden" value="4">
</div>
<div>
<input name="menu[3][id]" type="hidden" value="3">
<input name="menu[3][order]" class="new-order" type="hidden" value="5">
</div>
jQuery - Drag/drop, update order value then send via ajax :
// Sortable options
$('.nav-pages__items').sortable({
handle: '.nav-pages__drag',
items: ':not(.home)'
}).bind('sortupdate', function() {
// When dropped clear list order
$(this).find('input[name=menu]').attr('value', '');
// Then update list order
$('.nav-pages__items li:not(.home)').each(function(i, element) {
element = i+1;
$(this).find('input.new-order').attr('value'),
$(this).find('input.new-order').attr('value', + element);
});
// !! Somehow create array to send/save !!
// Ajax to send
$.post('/menu-update', {
_token: token,
id: id,
order: order
}, function(data) {
if (data.status == 'success') {
console.log('success: ', data);
} else if (data.error == 'error') {
console.log('error: ', data);
};
});
});
PHP/Laravel - Not got this far (without errors):
public function update()
{
$menu = Input::all();
$save = Page::where('id', $menu['id'])->update([
'order' => $menu['order']
]);
if ($save) {
$response = [
'status' => 'success',
'msg' => 'Message here',
'id' => $menu['id'],
'order' => $menu['order'],
];
};
return Response::json($response);
}
To summarise:
- Get the
idandorderfor each field group - Loop though them in js and crate correct array
- Send array to Laravel and update
orderbased onid
Also, if there's a much simpler way to do this, I'm all ears.
$(this).find('input.new-order').attr('value'), $(this).find('input.new-order').attr('value', + element);It looks to me like that firstfind()isn't doing anything -- am I crazy?$(this).find('input.new-order').attr('value')returns in your sortable function? I can't create the final order array without knowing that.input.new-order? Can you show the HTML for that element?