Multiple Selection field is blank in edit form, Select2 in edit form not triggering the selected values in edit form- Laravel Livewires - laravel

I have a select2 in a livewire component. Everything works fine but in my edit view, the selected options don't show in the box is selected. When I open the dropdown they show as highlighted, so data is coming from the backend. Please check below codes and output screenshots, Thanks in advance for your kind help.
Livewire Component
public $home_categories = [];
public $no_of_products;
public function mount()
{
$category = HomeCategory::all()->first();
$this->home_categories = explode(',', $category->home_categories);
$this->no_of_products = $category->no_of_products;
}
Blade Component:
<div class="form-group">
<label for="home_categories" class="col-md-4 control-label">Choose Category</label>
<div class="col-md-6" wire:ignore>
<select class="select2 form-control" name="home_categories[]" multiple="multiple" wire:model="home_categories">
#foreach ($categories as $category)
<option value="{{$category->id}}">{{$category->name}}</option>
#endforeach
</select>
</div>
The script inside the livewire:
#push('scripts')
<script>
$(document).ready(function() {
$('.select2').select2();
$('.select2').on('change', function (e) {
var data = $('.select2').select2("val");
#this.set('home_categories', data);
});
});
</script> #endpush

Use this code inside the blade components:
#if (in_array($category->id, $home_categories)) {{'selected'}} #endif
The script, component properties everything As-It-Is only changes in select option tag: like below code:
<select class="select2 form-control" name="home_categories[]" multiple="multiple" wire:model="home_categories">
#foreach ($categories as $category)
<option value="{{$category->id}}" #if (in_array($category->id, $home_categories)){{'selected'}}
#endif>{{$category->name}}</option>
#endforeach

In you component
public function hydrate(){$this->emit('data');}

Related

Using Livewire with multi Select2 multiple input

in one page I have to list the name of the all rooms in a loop and assign employees to the rooms. Some employees uses more than one room. I decided use Livewire for the first time. So I don't have experience with Livewire. I'm using Select2 to choose employees.
My structure is this:
Livewire View
<div>
#foreach(\App\Models\Room::all() as $room)
<div class="row">
<div class="col-2">
<div class="fw-bold">{{$room->room_code}}</div>
<div>
<p>{{$room->name}}</p>
</div>
</div>
<div class="col-8">
<div class="row">
<div class="col-10">
<select class="multiple-select" wire:model="employee.employee" data-placeholder="Choose employee" multiple="multiple">
#foreach(\App\Models\Employee::where('status', 1)->get() as $employee)
<option value="{{$employee->id}}">{{$employee->first_name." ".$employee->last_name}}</option>
#endforeach
</select>
</div>
<div class="col-1">
<button class="btn btn-danger" wire:click="assignSave({{$room->id}})"><i class="fa-solid fa-floppy-disk icon-center"></i></button>
</div>
<div class="col-1 text-success font-22">
<i class="fa-solid fa-check icon-center"></i>
</div>
</div>
</div>
</div>
#endforeach
</div>
Livewire Controller
<?php
namespace App\Http\Livewire;
use Livewire\Component;
class RoomAssign extends Component
{
public $employee = [];
public function render()
{
return view('livewire.room-assign');
}
public function assignSave($room){
dd($this->employee);
}
}
This is the blade
#section('sub-page-content')
<h6 class="mb-0 text-uppercase">Room Assign</h6>
<hr/>
<div class="card">
<div class="card-body">
<livewire:room-assign />
</div>
</div>
#endsection
#section('customjs')
<script src="{{asset('assets/plugins/select2/js/select24.min.js')}}"></script>
<script src="{{asset('assets/js/form-select2.js')}}"></script>
<script>
$('.multiple-select').on('change', function (){
alert('asdasd');
})
</script>
#endsection
Idea is simple. Take room id and employee id and save to a pivot table both information. But I can't evet take employees array. In every loop I have a save button for that room to save records and I want to inform user is process is successful. For information I left a div to show a simple "green tick". Can you help me about taking the employee ids and notify the user?
Need to add wire:ignore for select2. I would also change the $employeevariable in your foreach since you're using it in your Livewire component as well and is more than likely causing a conflict. Use something like $employeeInfo instead for the foreach
<div class="col-10" wire:ignore>
<select class="multiple-select" wire:model="employee" id="employee" data-placeholder="Choose employee" multiple="multiple">
#foreach(\App\Models\Employee::where('status', 1)->get() as $employeeInfo)
<option value="{{$employeeInfo->id}}">{{$employeeInfo->first_name." ".$employeeInfo->last_name}}</option>
#endforeach
</select>
</div>
When using Livewire with select2 you need to setup a listener for the select
public $employee = [];
protected $listeners = [
'employee',
];
public function employee($value)
{
$this->employee = $value;
}
And in your script tag:
$(document).ready(function() {
window.initSelectDrop=()=>{
$('#employee').select2({
placeholder: '{{ __('locale.Select ....') }}',
allowClear: true});
}
initSelectDrop();
$('#employee').on('change', function (e) {
livewire.emit('employee', e.target.value)
});
});
I had this same issue, when Livewire re-renders the component it will break select2 drop downs. Using this approach select2 will act as expected.
public function storeRoomEmployees(Room $room){
$room->employees()->attach($this->employees)
}
/* some suggestions on Your code
1. instead of this #foreach(\App\Models\Room::all() as $room) in your
blade, define a variable in Livewire Controller public $rooms.
2. add mount function
public function mount(){
$this->rooms = Room::all();
}
// mount function runs before the content load
#foreach(\App\Models\Room::all() as $room) -> #foreach($rooms as $room)
*/

my livewire app is returning 404 not found when I selected a dropdown item

I am designing a laravel app, which I used module and livewire. I have a dropdown item which when I selected an item its returned an error 404 NOT FOUND
Here is my livewire component.
I am thinking may the wire:model="selectedSession" and wire:model="selectedTerm" is having problem
please i need your help
<?php
namespace Modules\Student\Http\Livewire;
use Livewire\Component;
use Modules\Student\Entities\Result;
use Modules\Student\Entities\Term;
use Modules\Student\Entities\Section;
class ResultDependance extends Component
{
public $selectedSession = null;
public $selectedTerm = null;
public $results;
public function mount($id)
{
$this->results = Result::with('student', 'section', 'term', 'subject')->where('student_id', $id)->get();
}
public function render()
{
return view('student::livewire.pages.resultdependance',
['terms' => Term::all()],
['sessions' => Section::all()]
);
}
}
my blade.php codes
<div class="section">
<div class="card">
<div class="card-body">
<div class="card-title">
<h4><strong>Result</strong></h4>
<div class="form">
<form action="" method="post">
{{csrf_field()}}
<div class="form-group">
<select name="session" id="" class="form-control form-select" wire:model="selectedSession">
<option selected>Select Session</option>
#foreach($sessions as $session)
<option value="{{$session->id}}">{{$session->section_title}}</option>
#endforeach
</select>
</div>
<br>
<div class="form-group">
<select name="term" id="" class="form-control form-select" wire:model="selectedTerm">
<option selected>Select Term</option>
#foreach($terms as $term)
<option value="{{$term->id}}">{{$term->term}}</option>
#endforeach
</select>
</div>
<input type="button" value="test" wire::loading.attr='disabled'>
<h1 wire:loading>please wait</h1>
</form>
<br>
</div>
</div>
</div>
</div>
</div>
I am designing a laravel app, which I used module and livewire. I have a dropdown item which when I selected an item its returned an error 404 NOT FOUND
Here is my livewire component.
I am thinking may the wire:model="selectedSession" and wire:model="selectedTerm" is having problem
please i need your help
It's missing the logic to filter the results based on the selected session and term.
you can do it by using livewire hooks or by adding this
public function filterResults()
{
$this->results = Result::with('student', 'section', 'term', 'subject')->where('student_id', $id)->where('section_id', $this->selectedSession)->where('term_id', $this->selectedTerm)->get();
}
and in your selectedSession
<select name="session" id="" class="form-control form-select" wire:model.lazy="selectedSession" wire:change="filterResults">
Now when the user changes the selected session or term, the component will filter the results and update the view accordingly.

How to use select2 multiselect with livewire

What I am trying to achieve is, there are two models A and B with a relationship of One to many, where A has many B. So if the records for A and B have already been created, A can be assigned to many B. So I started this current project with livewire, and now I am at a loss. Normal select with multiple works just fine and populates the array in the backend of livewire. But when I use select2 nothing is stored in the array, and when I dd it, it shows an empty array.
Even though livewire provides wonderful set of tools, I am starting to realize that there is a lot of gray areas where things are missing or lacks external support, like select2 here.
Here is what I have done so far:
<div>
<div class="tab-pane fade show active" id="card1" role="tabpanel" aria-labelledby="card1-tab">
<div class="pt-3"></div>
<div class="row" >
<div class="form-group col">
<label for="cards">Enter Cards</label>
<select class="form-control select2" id="cards" multiple="multiple" onchange="this.dispatchEvent(new InputEvent('input'))>
<option disabled="">Select Cards</option>
#foreach($cardsUnassigned as $card)
<option value="{{ $card->id }}">{{ $card->imei_number }}</option>
#endforeach
</select>
</div>
<div class="form-group col">
<label for="technicians" class="">Technicians</label>
<select class="form-control select2" id="technicians" wire:model='techies.'>
<option disabled="">Select Technicians</option>
#foreach($technicians as $tech)
<option value="{{ $tech->id }}">{{ $tech->first_name }}</option>
#endforeach
</select>
</div>
</div>
#foreach($cardSelect as $key => $value)
{{$value}}
#endforeach
<button wire:click="assignCardToTech()" class="btn btn-primary">Submit</button>
</div>
</div>
#push('scripts')
<script>
$('#cards').select2({
placeholder: 'Select Cards to assign'
});
//send data to livewire
$('#technicians').select2({
placeholder: 'Select Technicians'
});
</script>
#endpush
And the backend:
<?php
namespace App\Http\Livewire\Stock\Assigns;
use App\Models\Card;
use App\Models\Sim;
use App\Models\Technician;
use Livewire\Component;
use Livewire\WithPagination;
use Illuminate\Support\Facades\Auth;
class Assigns extends Component
{
public $sortBy_card = 'imei_number';
public $sortBy_sim = 'ip';
public $sortDirection = 'asc';
public $search = '';
public $perPage = 10;
public $cardSelect = [];
public $techies;
public function render()
{
$simsUnassigned = Sim::query()
->whereNull('technician_id')
->searchUnassigned($this->search)
->get();
$cardsUnassigned = Card::query()
->whereNull('technician_id')
->searchUnassignedCard($this->search)
->get();
// dd($cardsUnassigned);
$simsAssigned = Sim::query()
->searchAssigned($this->search)
->orderBy($this->sortBy_sim, $this->sortDirection)
->paginate($this->perPage);
$cardsAssigned = Card::query()
->searchAssignedCard($this->search)
->orderBy($this->sortBy_card, $this->sortDirection)
->paginate($this->perPage);
$technicians = Technician::query()->get();
return view('livewire.stock.assigns.assigns',compact('simsUnassigned','cardsUnassigned','simsAssigned','cardsAssigned','technicians'))
->extends('layouts.base')
->section('content');
}
public function assignCardToTech(){
dd($this->cardSelect);
if($this->cards){
foreach($this->cards as $card){
}
}
}
}
Hopefully this helps.
######## INSIDE LIVEWIRE COMPONENT
public array $locationUsers = [];
protected $listeners = ['locationUsersSelected'];
public function locationUsersSelected($locationUsersValues)
{
$this->locationUsers = $locationUsersValues;
}
######## INSIDE LIVEWIRE BLADE
<div class="col-md-12 mb-3" wire:ignore>
<label for="locationUsers">Select Users</label>
<select id="locationUsers" class="form-control select2" multiple="multiple">
<option value="">--select--</option>
#foreach($this->users as $id => $name)
<option value="{{ $id }}">{{ $name }}</option>
#endforeach
</select>
</div>
######## INSIDE LIVEWIRE SCRIPTS
document.addEventListener('livewire:load', function () {
$('#locationUsers').on('select2:close', (e) => {
#this.emit('locationUsersSelected', $('#locationUsers').select2('val'));
});
$('#locationUsers').val(#this.get('locationUsers')).trigger('change');
});
Your could try adding this to your html
<div class="form-group col-md-6" wire:ignore>
<label for="manager" class="mb-0 h5">Assign Managers:</label>
<select wire:model="reporting_managers" id="manager" class="select-2 multiple='multiple' data-placeholder="Assign Managers">
#foreach ($managers as $manager)
<option value="{{ $manager->id }}" data-name="{{ $manager->name }}">{{ $manager->name }}</option>
#endforeach
</select>
</div>
and then in your javaScript section
$('#manager').on('select2:select', function (e) {
#this.set('reporting_managers', $('#manager').select2('val'));
});
$('#manager').on('select2:unselect', function (e) {
#this.set('reporting_managers', $('#manager').select2('val'));
});
This will directly store your selection in variable in livewire and won't get deselected on render.

select2 on Laravel Livewire does not work

I implemente select2 in a select as the official documentation indicates and I can't get it to work in full.
<div>
<div wire:ignore>
<select class="js-example-basic-single" name="state">
<option value="AL">Alabama</option>
<option value="WY">Wyoming</option>
</select>
<!-- Select2 will insert it's DOM here. -->
</div>
#push('scripts')
<script>
$(document).ready(function() {
$('.js-example-basic-single').select2();
$('.js-example-basic-single').on('change', function (e) {
#this.set('foo', e.target.value);
});
});
</script>
#endpush
if I remove the following script in the view the select2 component renders fine
$('.js-example-basic-single').on('change', function (e) {
#this.set('foo', e.target.value);
});
but of course I lose the desired functionality.
The selct2 add links I use are as follows
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="{{asset('SitioWeb/assets/select2/js/select2.min.js')}}"></script>
what am i missing?
Due to the way select2 works, livewire's wire:model and wire:change may not work with select2. Livewire's wire:model and wire:change work perfectly with the traditional HTML select control. To use select to with livewire's wire:model and wire:change, write a js code to get the selected value from select2, then use Livewire.emit() to send the selected value to your component and handle it from there. Example js code is as follows:
$(document).ready(function() {
$('#id').select2();
$('#id').on('change', function(e) {
Livewire.emit('listenerReferenceHere',
$('#id').select2("val"));
});
});
Your Livewire component :
...
protected $listeners = ['listenerReferenceHere'];
public function listenerReferenceHere($selectedValue)
{
//Do something with the selected2's selected value here
}
I hope this helps... 😊
you can use Bootstrap-select
npm install bootstrap-select
It worked well for me. this my code.
<div class="form-group">
<label for="permissions">{{ __('role.permissions') }}</label>
<div class="col-sm-10">
<div wire:key="UNIQUE_KEY">
<div wire:ignore>
<select id="permissions" wire:model="permissions"
data-live-search="true"
data-actions-box="true"
title="{{__('generic.select')}} {{ __('role.permissions') }}"
name="permissions[]" data-width="100%"
class="selectpicker permissions" multiple>
#foreach($list_permission as $permission)
<option value="{{ $permission->id }}"
data-subtext="{{ $permission->key }} {{ ' -'. $permission->table_name }}">
{{ __('permission.'.$permission->key) }}
</option>
#endforeach
</select>
</div>
</div>
#error('permissions') <span class="text-danger">{{ $message }}</span> #enderror
</div>
</div>
in script :
....
#push('scripts')
<script>
Livewire.restart();
$(function () {
$('.permissions').selectpicker();
});
</script>
#endpush
</div>
in Component
public $permissions = [];
public $old_permissions = [];
public function updatedPermissions()
{
$filter_arrays = array_filter($this->permissions);
$unique = array_unique($filter_arrays);
$this->permissions = $unique;
}
in update :
if (! empty($this->old_permissions)){
$updateRole = $this->role->find($this->modelId)->permissions()->detach();
$updateRole = $this->role->find($this->modelId)->permissions()->sync($validatedData['permissions']);
}elseif ($this->old_permissions != $this->permissions ){
$updateRole = $this->role->find($this->modelId)->permissions()->attach($validatedData['permissions']);
}
I tried hard to combine livewire with select2 and finally found the solution that way.
UsersComponent.php
class Users extends Component
{
public $users = [];
public function mount()
{
$this->users= User::all();
}
public function render()
{
return view('livewire.users');
}
}
then
users.blade.php
<div class="col-sm-12 col-xl-3 m-b-30" wire:ignore >
<div >
<h4 class="sub-title" >USERS</h4>
<select class="js-example-basic-single form-control-warning" name="states" >
#foreach ($users as $user)
<option value="{{ $user->id }}">{{ $user->name}}</option>
#endforeach
</select>
</div>
</div>
index.blade.php
<p>
#livewire(livewire.users)
</p>

Dynamically populated select menus in Laravel5

In a view I have a couple of select menus that are populated by data from two separate tables.
Looking for a way to populate the second select menu depending on the value of the first.
<div class="form-group">
{{Form::label('company', 'Company')}}
<select selected="" class="form-control" id="company" name="company">
#foreach($company as $key)
<option value="">{{$key->name}}</option>
#endforeach
</select>
</div>
<div class="form-group">
{{Form::label('department', 'Department')}}
<select selected="" class="form-control" id="department" name="department">
#foreach($department as $key)
<option =value"">{{$key->name}}</option>
#endforeach
</select>
</div>
This feels like something that shouldn't be too hard, but have yet to find any good information about it.
A way to do this is using javascript. The main idea is to have a partial view with the second select and then call it when the user change something in the first select.
To do this, you need to have two views. The main view will have a call to the second view with a default collection of departments:
<div class="form-group">
{{Form::label('company', 'Company')}}
<select selected="" class="form-control" id="company" name="company">
#foreach($company as $key)
<option value="">{{$key->name}}</option>
#endforeach
</select>
</div>
<div id="second-select" class="form-group">
#include('contents.partial', ['department' => $department])
</div>
The second view (contents.partial) will print the form:
{{Form::label('department', 'Department')}}
<select selected="" class="form-control" id="department" name="department">
#foreach($department as $key)
<option =value"">{{$key->name}}</option>
#endforeach
</select>
Then you'll need a route to call a function to render the second view based on some value:
Route::get('/get/content/{value}', 'ContentController#getContent');
And the function to render the view in ContentController:
public function getContent(Request $request, $value)
{
$department = Department::where('value', $value)->get();
return view('contents.partial', [
'department' => $department
])->render();
}
And to call this, you need a javascript/jquery to identify the change in the select and fire the function in controller
<script>
$(document).ready(function(){
setListener();
});
function setListener() {
$('#company').change(function() {
var value = $(this).val();
$.get( "/get/content/"+value, function( data ) {
$('#second-select').empty();
$('#second-select').append(data);
});
});
}
</script>
This is the main idea, ok?

Resources