Select2 not showing dropdown list after changing page - livewire - laravel

Hi i have a problem about select2 and livewire, after go to another page and back to dashboard the dropdown list of select2 dissapeared, i checked the source the list still on there and not loaded
<script>
$(document).ready(function() {
$('.live-search').select2({
placeholder: 'Search Services',
// allowClear: true,
});
$('.live-search').on('change', function(e) {
Livewire.emit('servicesId', e.target.value);
});
});
</script>
<div class="form-group" wire:ignore>
<label>Services :</label>
<select class="form-control live-search" wire:model='servicesId'>
#foreach ($data as $service)
<option value="{{ $service->id }}">{{ Str::ucfirst($service->service_name) }} -
Rp.{{ $service->price }}
</option>
#endforeach
</select>
<hr />
</div>

Related

Laravel Livewire Select2 issue with new app

I have standard TALL Stack new APP
& I am trying to make select2 from Laravel 8 & Livewire 2
I have follow this
in my live-wire blade I have added this
<div class="w-1/3 px-3 mb-5" wire:ignore>
<x-jet-label for="uid" value="{{ __('Users') }}" />
<select class="select2 w-full rounded-md border border-gray-200 p-2 focus:outline-none focus:border-gray-500" id="uid" wire:model.defer="uid">
<option value="" selected>Choose User</option>
#if(isset($users))
#foreach($users as $user)
<option value="{{ $user->id }}">{{ $user->name }}</option>
#endforeach
#endif
</select>
<x-jet-input-error for="uid" class="mt-2" />
</div>
at the bottom of this page
#push('scripts')
<script>
$(document).ready(function() {
$('.select2').select2();
});
</script>
#endpush
Its not loading Select2 but there is no error in console.
Also I have added
#livewireStyles
#livewireScripts
in layout blade also.
Do I need to add any extra CSS or JS or what I am doing wrong.
Even I have added this in my blade but still not working
#section('style')
#endsection
#section('scripts')
<script type="text/javascript">
$(document).ready(function () {
$('#FirstOption').select2({
placeholder: 'Select an option',
});
});
</script>
#endsection
Thanks

ajax in laravel not showing. but in console , i can see the get url

I am making 2 dropdown which is the second one is dependent from first one. And here is my view code:
<div class="col-lg-6 col-md-6 col-sm-12">
<div class="form-group">
<label class="form-label">General</label>
<select class="form-control formselect required"
placeholder="Select Category" id="sub_category_name">
<option value="0" disabled selected>Select
Main Category*</option>
#foreach($data as $categories)
<option value="{{ $categories->id }}">
{{ ucfirst($categories->catname) }}</option>
#endforeach
</select>
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-12">
<div class="form-group">
<label class="form-label">Sub</label>
<select class="form-control formselect required"
placeholder="Select Sub Category" id="sub_category">
</select>
</div>
</div>
Then here is my code in controller :
public function index(Request $request)
{
$data = DB::table('cats')->get();
return view('admin.genc.gencEntry')->with('data', $data);
}
public function subcat($id){
echo json_encode(DB::table('subcats')->where('catid', $id)->get());
}
And ajax is here:
<script>
$(document).ready(function () {
$('#sub_category_name').on('change', function () {
let id = $(this).val();
$('#sub_category').empty();
$('#sub_category').append(`<option value="0" disabled selected>Processing...</option>`);
$.ajax({
type: 'GET',
url: 'subcat/' + id,
success: function (response) {
var response = JSON.parse(response);
console.log(response);
$('#sub_category').empty();
$('#sub_category').append(`<option value="0" disabled selected>Select Sub Category*</option>`);
response.forEach(element => {
$('#sub_category').append(`<option value="${element['id']}">${element['subcatname']}</option>`);
});
}
});
});
});
</script>
But when i select a option from first dropdown, second one is not showing anything.
But i can see XHR finished loading: GET "http://www.example.com:8000/genc/subcat/7" in my console.
Can someone tell me where is the error causing the empty dropdown?
It's look like issue with your loop syntax, use it like
$.each(response, function(key,element) {
$('#sub_category').append(<option value="${element['id']}">${element['subcatname']}</option>);
});

How to Display a selected grade with its subject?

I want to when a user select a dropdown from the list, a group of subjects available for that grade must be displayed with checkboxes next to them
My controller
public function create()
{
$grades = Grade::with('subjects')->orderBy('slug', 'asc')->get();
return view('admin.users.create', compact( 'grades'));
}
Blade file
<div class="form-group">
<select id="grade" name="grade" class="form-control #error('grade') is-invalid #enderror" v-model="selectedSubjects">
<option value="">Choose a Grade...</option>
#foreach($grades as $grade)
<option value="{{ $grade->id }}" {{ old('grade', $grade) == $grade->name ? 'selected' : "" }}>{{ $grade->name }}</option>
#endforeach
</select>
</div>
<div class="custom-control custom-checkbox mt-2">
#foreach($grade->subjects as $subject)
<input type="checkbox" class="custom-control-input" id="{{$subject->slug}}" name="subjects[]" :value="selectedSubjects" />
<label class="custom-control-label" for="{{$subject->slug}}">{{$subject->name}}</label>
#endforeach
</div>
vue
<script>
window.addEventListener('load',function(){
var app = new Vue({
el: '#app',
data:{
selectedSubjects: {!! $grade->subjects->pluck('name') !!},
}
});
});
</script>
THIS IS IMPOSSIBLE... I GIVE UP
As per I have understood, you want to select grades from dropdown & show its corresponding checkbox as per subjects for the grades.
I would suggest to create a vue component for that lets say grades-component,
in your blade you can add,
<form action="" class="form-control">
#csrf
<grade-component :grades='#json($grades)'></grade-component>
</form>
here in blade, $grades is the object(or array) you are passing via compact. Basically it is to pass your data to the component, we will use that with help of props.
Now you can add your GradeComponent.vue in resources->js->components->GradeComponent.vue
GradeComponent.vue
<template>
<div class="container">
<select v-model="selected_grade" #change="onChange($event)">
<option v-for="grade in grading" :value="grade.slug">{{grade.name}}</option>
</select>
<div class="custom-control custom-checkbox mt-2" v-if="subjects !== null" v-for="subject in subjects">
<input type="checkbox" :id="subject.slug" :value="subject.slug"/>
<label :for="subject.slug">{{subject.name}}</label>
</div>
</div>
</template>
<script>
export default{
props: ['grades'],
data: function() {
return {
grading: this.grades,
selected_grade: null,
subjects : null
}
},
methods: {
onChange(event) {
this.grading.forEach((obj, index) => {
if (obj.slug === event.target.value){
this.subjects = obj.subjects;
}
})
}
}
}
</script>
Now finally you can add it in app.js
Vue.component('grade-component', require('./components/GradeComponent.vue').default);
Then compile your vuejs code, I would use npm run watch
A similar one but with fake data, you can see https://jsfiddle.net/bhucho/2yu4nmws/3/,

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>

how to show selected values in multi-select

I'm facing one issue about multi-select.
onchange i'm runnig ajax and on ajax success option appends to multiselect.
but at the time of edit i'm not able to trigger ajax and not able to show selected option in multiselect.
please check my code
form fleds
<div class="form-group {{ $errors->first('preferred_city', 'has-error') }}">
<label class="control-label col-lg-2">Preferred City
: </label>
<div class="col-lg-10">
<select name="preferred_city[]" class="form-control" id="preferred_city" multiple="multiple" style="color: #333">
#foreach($cities as $preferred_city)
#if(!empty($studentsDetails->preferred_city))
<option value="{{$preferred_city->id}}" {{ (in_array($preferred_city->id,\GuzzleHttp\json_decode($studentsDetails->preferred_city) )) ? 'selected' : '' }}>{{$preferred_city->city_name}}</option>
#else
<option value="{{$preferred_city->id}}">{{$preferred_city->city_name}}</option>
#endif
#endforeach
</select>
<span class="help-block">{{ $errors->first('preferred_city', ':message') }}</span>
</div>
</div>
<div class="form-group {{ $errors->first('collage_preferences', 'has-error') }}">
<label class="control-label col-lg-2">College Preferences
: </label>
<div class="col-lg-10">
<select id="collage_preferences" name="collage_preferences[]" class="form-control" multiple="multiple">
</select>
<span class="help-block">{{ $errors->first('collage_preferences', ':message') }}</span>
</div>
</div>
js
collage id's i'm fetching from database
var collage_pref = {!! $studentsDetails->collage_preferences !!}
I'm triggering preferred_city on page load
$(document).ready(function(){
if(studentsDetails !=null){
$('#preferred_city').trigger('change');
// $('#pic_file').trigger('change');
}
});
$('#preferred_city').on('change',function(){
$("#collage_preferences").multiselect('rebuild');
$.ajax({
url:'{{route('student.getInstituteslists')}}',
type:'get',
async: false,
data:{grad_course:$('#grad_course').val(),preferred_city:$('#preferred_city').val()},
success:function(e){
$('#collage_preferences').multiselect('refresh');
e.forEach(function(inst){
var data = '';
data +='<option value="'+ inst.id+'" >'+ inst.institute_name+'</option>';
$('#collage_preferences').append(data);
});
$('.collage_preferences').multiselect('rebuild');
}
});
});
$data = [];
$data['airlines'] = '';
$airlines = (Airline::select('Code','Name')->get())->toArray();
$myairlines = BlackoutAirline::where('SupplierId',$request->SupplierId)->pluck('AirlineCode')->toArray();
foreach($airlines as $airline) {
if(in_array($airline['Code'], $myairlines) ){
$data['airlines'] .= '<option value="'.$airline['Code'].'" selected>'.$airline['Name'].'</option>';
}
else{
$data['airlines'] .= '<option value="'.$airline['Code'].'">'.$airline['Name'].'</option>';
}
}
return json_encode($data);

Resources