Wire:model not working in select2
"""
select class="search form-control product_id" name="product_id" id="product_id" wire:model="search" > @if ($this->result->count() > 0) @foreach ($this->result as $product){{$product->name}} @endforeach @endif
"""
What The Issue Is
From what we can gather from the initial question, was that when the person was changing the select option (wrapped in a select2 plugin) it was not updating the wire:modal it was assigned to.
What a lot of people do not realise, is that Select2 creates its own DOM when it loads. So what you are changing on the drop down, is not the actual dropdown you have coded.
So the first thing you have to do, is wrap the select in a div and ignore it
< div wire:ignore>
SELECT GOES HERE
<-- select2 will put its new domhere -->
</div>
An example of Multiple Select can be seen below (note I have the name of the select different to the variable, to prevent one overriding the other. So although engineer maybe whats on the model, I use engineerSearch[] as the name, as I’m using engineers/engineer elsewhere in the code.)
<div class="form-group row " wire:ignore>
<label for='day' class='control-label col-md-3'>Engineers</label>
<div class='col-md-9'>
<div class="form-control-wrap ">
<div class=''>
<select name="engineerSearch[]" id='engineerSearch' wire:model="engineerSearch" class='form-select-engineerSearch' multiple>
@foreach($engineers as $engineerID => $name)
<option value="{{$engineerID}}">{{$name}}</option>
@endforeach
</select>
<!-- Select2 will insert it's DOM here. -->
</div>
</div>
</div>
</div>
- See: https://laravel-livewire.com/docs/2.x/alpine-js for examples on this (search for wire:ignore)
To fire an event (Say wire:click) on the select. You have to put the JS in livewire file, to fire an event
<script>
$(document).ready(function() {
$('#select2').select2();
$('#select2').on('change', function (e) {
var data = $('#select2').select2("val");
@this.set('foo', data);
});
});
</script>
- See: https://forum.laravel-livewire.com/t/using-livewire-with-select2-selectpicker/18 for examples on this wire:click
LIVEWIRE ERROR:
"""
select class="search form-control product_id" name="product_id" id="product_id" wire:model="search" > @if ($this->result->count() > 0) @foreach ($this->result as $product){{$product->name}} @endforeach @endif
"""
Completed:
2021