jezon gonzales
jezon gonzales

Reputation: 41

How to apply select2 in laravel livewire with 1 component in multiple blade file

**Component File**
class PurchaseRequests extends Component
}

 public $show = 'index';

 public function create()
 {
    $this->reset();
    $this->method = 'store';
    $this->show = 'form';
 }

 public function render()
 {
   return view('livewire.purchase_requests.'.$this->show);
 }
}

Blade File index.blade.php form.blade.php

I tried to apply the select2 in index.blade.php and its working but when i try it to form.blade.php its not working. i dont know whats the problem.

Upvotes: 0

Views: 796

Answers (1)

Prospero
Prospero

Reputation: 2352

I don't know what could be causing the issue once I can't see any code. But for my experience with select2 and Livewire I'm going to share with you my codding. This is a simple example for one component and the blade related. component

public $models;
public $selected_item;
protected $listeners = ['selected_select2_item'];  // this listen for the select2 emitted event 

public function hydrate()  // hydrate the select2 element on every re-render
{
   $this->emit('select2');
}

public function mount()
{
  $this->models = Model::all();
}

public function render()
{
   //......
}

public function selected_select2_item($value)  // function load from listener
{
   dd($value); 
}

and in the blade component

@section('content')
//......

<select id="select2_element" wire:change="$emit('selected_select2_item',$event.target.value)">
  @foreach($models as $model)  
    <option value="{{$model->id}}">{{$model->name}}</option>
  @endforeach
</select>

//......
@endsection

@section('custom_scripts')
  <script>
    $(document).ready(function() {

            window.initSelectDrop=()=>{
                $('#select2_element').select2({
                    placeholder: '-- Select model--',
                    allowClear: true});
            }

            initSelectDrop();

            $('#select2_element').on('change', function (e) {
                livewire.emit('selected_select2_item', e.target.value)
            });

            window.livewire.on('select2',()=>{
                initSelectDrop();
            });

        }); 
  </script>
@endsection

Hope this code can help you like it did it before with me! ;)

Upvotes: 1

Related Questions