Skip to content
This repository has been archived by the owner on Jan 2, 2024. It is now read-only.

Unable to get select to work with relationships with Livewire #47

Open
kurucu opened this issue Jan 20, 2021 · 4 comments
Open

Unable to get select to work with relationships with Livewire #47

kurucu opened this issue Jan 20, 2021 · 4 comments

Comments

@kurucu
Copy link

kurucu commented Jan 20, 2021

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.

@Giovanni-Petrella
Copy link

I have the same problem there is no solution, even temporary, before solving the bug?

@mrl22
Copy link
Contributor

mrl22 commented Apr 5, 2022

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.

@mrl22
Copy link
Contributor

mrl22 commented Apr 5, 2022

@Giovanni-Petrella @kurucu @andrecuellar

I have put together a gist to help you with this.

https://gist.github.com/mrl22/9693be99d155213400d6f3eb09657ac5

@punkfairie
Copy link

punkfairie commented Dec 11, 2022

@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.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants