I have a select2 in a livewire component. Everything works fine but in my edit view, the selected options don't show in the box is selected. When I open the dropdown they show as highlighted, so data is coming from the backend. Please check below codes and output screenshots, Thanks in advance for your kind help.
public $home_categories = [];
public $no_of_products;
public function mount()
{
$category = HomeCategory::all()->first();
$this->home_categories = explode(',', $category->home_categories);
$this->no_of_products = $category->no_of_products;
}
<div class="form-group">
<label for="home_categories" class="col-md-4 control-label">Choose Category</label>
<div class="col-md-6" wire:ignore>
<select class="select2 form-control" name="home_categories[]" multiple="multiple" wire:model="home_categories">
@foreach ($categories as $category)
<option value="{{$category->id}}">{{$category->name}}</option>
@endforeach
</select>
</div>
@push('scripts')
<script>
$(document).ready(function() {
$('.select2').select2();
$('.select2').on('change', function (e) {
var data = $('.select2').select2("val");
@this.set('home_categories', data);
});
});
</script> @endpush
@if (in_array($category->id, $home_categories)) {{'selected'}} @endif
The script, component properties everything As-It-Is only changes in select option tag: like below code:
<select class="select2 form-control" name="home_categories[]" multiple="multiple" wire:model="home_categories">
@foreach ($categories as $category)
<option value="{{$category->id}}" @if (in_array($category->id, $home_categories)){{'selected'}}
@endif>{{$category->name}}</option>
@endforeach