Edit values with Select2

How to return saved values for editing from select2? I have no problem saving, but when trying to edit, the selector does not show the saved value. If I do it using with basic select, I get the value correctly, but it doesn’t work with select2. Any help would be helpful. Thank you!

My component:

<div class="mb-4" wire:ignore>
    <label for="exampleFormControlInput2" class="block text-gray-700 text-sm font-bold mb-2">Genre</label>
    <select name="genre_id" wire:model="genre_id" class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline genre">
           <option></option>
          @foreach($genres as $genre)
          <option value="{{ $genre->id }}">{{ $genre->name }}</option>
          @endforeach
       </select>
</div>

<script>
    $(document).ready(function() {
        $('.genre').select2({
            placeholder: "Seleccione el Género"
        }).prepend('<option selected=""></option>')
        $('.genre').on('change', function(e) {
            @this.set('genre_id', e.target.value);
        });
    });
</script>

Tthe class of my component looks like this:

class Works extends Component
{
    public $works, $title, $lyric_author_id, $music_author_id, $content, $work_id, $user_id, $genre_id;
    public $genres;
    public $genre;
    public $user;
    public $authors;
    public $author;
    public $isOpen = 0;
    public $confirmingWorkDeletion = false;

    protected $messages = [
        'title.required' => 'La obra de llevar un título.',
        'lyric_author_id.required' => 'Se requiere el Autor de la Letra.',
        'music_author_id.required' => 'Se requiere el Autor de la Música.',
        'genre_id.required' => 'Se requiere el Género de la Música.',
        'content.required' => 'Se requiere el Contenido de la Obra.',
    ];

    public function mount()
    {
        $this->works = Work::all();
        $this->genres = Genre::all();
        $this->authors = Author::all();
    }

    public function render()
    {
        return view('livewire.works.index');
    }

    public function create()
    {
        $this->resetInputFields();
        $this->openModal();
    }

    public function openModal()
    {
        $this->isOpen = true;
    }


    public function closeModal()
    {
        $this->isOpen = false;
    }

    private function resetInputFields()
    {
        $this->title = '';
        $this->lyric_author_id = '';
        $this->music_author_id = '';
        $this->genre_id = '';
        $this->content = '';
        // $this->user_id = '';
    }

    public function store()
    {
        $this->validate([
            'title' => 'required',
            'lyric_author_id' => 'required',
            'music_author_id' => 'required',
            'genre_id' => 'required',
            'content' => 'required',
        ]);

        $userId = auth()->user()->id;
        Work::updateOrCreate(['id' => $this->work_id], [
            'title' => $this->title,
            'lyric_author_id' => $this->lyric_author_id,
            'music_author_id' => $this->music_author_id,
            'genre_id' => $this->genre_id,
            'content' => $this->content,
            'user_id' => $userId,
        ]);

        session()->flash(
            'message',
            $this->work_id ? 'Obra actualizada correctamente.' : 'Obra creada con exito.'
        );

        $this->closeModal();
        $this->resetInputFields();
    }

    public function edit($id)
    {
        $work = Work::findOrFail($id);
        $this->work_id = $id;
        $this->title = $work->title;
        $this->lyric_author_id = $work->lyric_author_id;
        $this->music_author_id = $work->music_author_id;
        $this->genre_id = $work->genre_id;
        $this->content = $work->content;
        $this->user_id = $work->user_id;
        
        $this->openModal();
    }

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    public function confirmWorkDeletion($id)
    {
        $this->confirmingWorkDeletion = $id;
    }

    public function deleteWork($id)
    {
        Work::find($id)->delete();

        $this->confirmingWorkDeletion = false;

        session()->flash('message', 'Obra eliminada correctamente.');
    }
}

Can you try this code

<script>
    $(document).ready(function() {
        var genre_select2 = $('.genre').select2({
            placeholder: "Seleccione el Género"
        }).prepend('<option selected=""></option>')
        $('.genre').on('change', function(e) {
            @this.set('genre_id', e.target.value);
        });

        var selected__ = $('.genre').find(':selected').val();
        if(selected__ !="") genre_select2.val(selected__);
    });
</script>
1 Like

have you saved the genre_id data? at your component genre_id undefined?

1 Like

Thank you very much for the help, however it still shows no courage. I experience the error using select2, but with a normal select with html, the value is displayed without problems

Hi,
You are using wire:ignore so there is not need for wire:model=“genre_id” in the select, when you use wire:ignore Livewire will ignore any directive inside that div

So you have to add and set the value using Javascript

<script>
        $(document).ready(function(){
    $('.genre').select2({
        placeholder: "Seleccione el Género"
    }).prepend('<option selected=""></option>')

    $('.genre').on('change', function(e) {
        @this.set('genre_id', e.target.value);
    });             

       function setDropValues(){
            let genre_id='{{$genre_id}}'
            if (genre_id!='')
            {
                $('.genre').val(genre_id);
                $('.genre').trigger('change');
            }
        }
           This will work for the first time the page is load, bind the value to select2     
          setDropValues();

});

hope that help

1 Like

Thanks a lot!!! You have solved my problem! Happy New Year!

1 Like