Unable to get select to work with relationships with Livewire
Following the docs, I'm trying to get Livewire to work with relationships and a multi-select.
Code is as follows:
<x-form wire:submit.prevent="submit">
@wire
<x-form-input name="post.title" label="Title" :readonly="!$isEditing" />
<x-form-textarea name="post.description" label="Description" :readonly="!$isEditing" />
@if($isEditing)
<x-form-select name="post.tags[]" :options="$this->allTags" multiple many-relation label="Applicable Tags" />
@endif
@endwire
</x-form>
Whilst the options are populated, the chosen ones are not selected when the form is shown, and any chosen ones are not saved when the form is submitted.
I have the same problem there is no solution, even temporary, before solving the bug?
It is not a bug. Select options does not accept an array/collection of models, it should be array key/value. You either have to prepare the data in your controller or loop the model output.
Slightly dirty but here is an example of how I did it.
<x-form-select name="country_id">
@foreach(\App\Models\Country::all() as $c)
<option value="{{$c->country_id}}">{{$c->country_name}}</option>
@endforeach
</x-form-select>
Laravel form components will automatically set selected.
If it was developed how you describe above then x-form-select would not know which field to use as the value and which to display in the select option.
@Giovanni-Petrella @kurucu @andrecuellar
I have put together a gist to help you with this.
https://gist.github.com/mrl22/9693be99d155213400d6f3eb09657ac5
@Giovanni-Petrella @kurucu @andrecuellar
I have put together a gist to help you with this.
https://gist.github.com/mrl22/9693be99d155213400d6f3eb09657ac5
There is also the laravel helper ->pluck('value', 'key') which I have been using.
Also, I've been having an issue with using Livewire in combination with component selects. I believe this is a Livewire issue though, as I have the same problem with my own simple select component.
EDIT: I found the solution - make sure you are setting wire:model or @wire to 'defer', I had it on lazy but it works perfectly now with defer.