I am trying to build a filter component that actually uses a select2 JS library and when I try to reset all the filters modeled with the select field and Input fields the values reset but the selected select2 value won’t get reset. So, I wanted to refresh/reload the component and I tried to call render() method from resetFilters() but it doesn’t work.
By the way, I tried wire:click="$refresh"
I am using Laravel 8.x with Livewire 2.X installed and I am new for Livewire please help me.
Here is my component’s blade code
<div class="row align-items-end">
<div class="col-md-2">
<div class="form-group">
<label for="dataPerPage">Data Per Page</label>
<x-select-two-field wire:model="dataPerPage" id="dataPerPage" name="dataPerPage" :iteratable="$perPageSet" />
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="name">Filter by Name</label>
<input type="text" class="form-control" name="name" id="name" wire:model.debounce.600ms="schoolName" placeholder="Type School Name" />
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="type">Filter by Category</label>
<x-select-two-field wire:model="schoolCategory" name="type" id="type" place-holder="Select School Category" :iteratable="$schoolCategories" value="type" label="type" />
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="town">Filter by Town</label>
<x-select-two-field wire:model="schoolTown" name="town" id="town" place-holder="Select School Town" :iteratable="$schoolTowns" value="town" label="town" />
</div>
</div>
<div class="col-md-1">
<div class="form-group">
<button class="btn btn-primary btn-block" wire:click="resetFilters">Reset Filter</button>
</div>
</div>
</div>
And here is my resetFilters()
public function resetFilters() {
$this->reset(['schoolName', 'schoolCategory', 'schoolTown']);
}
Lastly, here is my Laravel select-two component code
<div wire:ignore>
<select class="form-control select2" style="width: 100%" id="{{ $id }}" {{ $attributes }}>
@if ($placeHolder)
<option></option>
@endif
@foreach ($iteratable as $iteratableItem)
<option value="{{ $value ? $iteratableItem->{$value} : $iteratableItem }}">
{{ ucwords(implode(' ', explode('-', $label ? $iteratableItem->{$label} : $iteratableItem))) }}
</option>
@endforeach
</select>
</div>
@push('js')
<script>
$(document).ready(function() {
let currentSelect = $('#{{ $id }}');
let isMultiple = currentSelect.attr('multiple') ? true : false;
let placeHolder = '{{ $placeHolder }}';
let selectOptions = {
placeholder: placeHolder,
allowClear: isMultiple
};
currentSelect.select2(selectOptions);
currentSelect.on('change', function() {
let elementName = $(this).attr('wire:model');
var data = $(this).val();
@this.set(elementName, data);
})
});
</script>
@endpush