I'm trying to make the following select2 selection field in laravel voyager admin panel sortable with sortable.js.
<select id="selected-items" class="form-control select2" name="selected_items[]" multiple="multiple">
<?php $default = null; ?>
@if(isset($items))
@if (! empty($selectedValues))
@foreach($selectedValues as $selectedVal)
@foreach($items as $option)
@if ( $selectedVal == $option->$itemId )
<option value="{{ $option->$itemId }}" selected="selected">{{ $option->$itemTitle }} {{ $option->slug ? '(' . $option->slug. ')' : '' }}</option>
@endif
@endforeach
@endforeach
@foreach($items as $option)
@if ( ! in_array($option->$itemId, $selectedValues) )
<option value="{{ $option->$itemId }}">{{ $option->$itemTitle }} {{ $option->slug ? '(' . $option->slug. ')' : '' }}</option>
@endif
@endforeach
@else
@foreach($items as $option)
<option value="{{ $option->$itemId }}">{{ $option->$itemTitle }} {{ $option->slug ? '(' . $option->slug. ')' : '' }}</option>
@endforeach
@endif
@endif
</select>
I
use the following code
var el = document.querySelector('.select2-selection__rendered');
var sortable = Sortable.create(el);
it actually makes the selected options sortable and draggable. but it doesn't save. when I close the page or add a new item it goes back to the first state that it was.
I tried storing in the localStorage... but still the order of the selected_items[] does not change... I think the order of the selected_items[] needs to change in order for this to get saved .
var select2List = document.querySelector('.select2-selection__rendered');
Sortable.create(select2List, {
group: "localStorage-example",
store: {
/**
* Get the order of elements. Called once during initialization.
* @param {Sortable} sortable
* @returns {Array}
*/
get: function (sortable) {
var order = localStorage.getItem(sortable.options.group.name);
return order ? order.split('|') : [];
},
/**
* Save the order of elements. Called onEnd (when the item is dropped).
* @param {Sortable} sortable
*/
set: function (sortable) {
var order = sortable.toArray();
localStorage.setItem(sortable.options.group.name, order.join('|'));
}
}
})