Livewire magic actions not working Uncaught ReferenceError: $event is not defined - laravel

<div class="row">
<div class="col">
<div class="container">
<div class="card">
<div class="card-body">
<div class="row">
<div class="col">
<div class="mb-5">
<label class="form-label">Order: </label>
<select wire:change="selectOrder($event.target.value)">
#foreach($orders as $option)
<option value="{{$option['id']}}">{{$option['id']}}</option>
#endforeach
</select>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
public function selectOrder($order)
{
$this->order = $order;
$this->products = $this->order->products;
}
here is a live wire component that has a select input I need when changing the select the function selectOrder is executed with the selected value, i use $event magic action but i got the following error.

The $event is the Alpine.js magic property.
So one way to solve it is to have use an Alpine.js event listener, that calls the Livewire method.
<select x-on:change="$wire.selectOrder($event.target.value)">
That said, you could use a property in the Livewire class, and bind the select to a model,
<select wire:model="orderValue">
And then in the component listen for that change.
public $orderValue;
// ...
public function updated($field, $value)
{
if ($field === 'orderValue') {
$this->selectOrder($value);
}
}

Related

laravel livewire error Undefined variable $_instance

I have a form with which I add posts. I want to integrate CKEDITOR, to manipulate the content in textarea. to initialize the editor, I use the following code :
<script src="ckeditor/ckeditor.js">
ClassicEditor
.create(document.querySelector('#post_content'))
.then(editor=>{
editor.model.document.on('change:data',(e)=>{
#this('post_content').set('post_content', e.editor.getData());
});
})
.catch(error=>{
console.error(error);
});
</script>
When I submit form, I get the following error :
> Undefined variable $_instance
here's my form, I mention that without CKEDITOR, it works
<form wire:submit.prevent="addNewPost()" method="post" id="createPostForm" enctype="multipart/form-data">
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-md-9">
<div class="mb-3">
<label for="" class="form-label">
Titlu
</label>
<input type="text" wire:model="post_title" name="post_title" class="form-control" placeholder="Titlul articolului" value="{{old('post_title')}}">
<span class=" text-danger ">#error('post_title') {{$message}}#enderror</span>
</div>
<div wire:ignore class="mb-3">
<label for="" class="form-label">
Continutul articolului
</label>
<textarea wire:model="post_content"class="ckeditor form-control" id="post_content" name="post_content" cols="30" rows="10" >{{$post_content}}</textarea>
<span class="text-danger">#error('post_content'){{$message}}#enderror</span>
</div>
</div>
<div class="col-md-3">
<div class="mb-3">
<div class="form-label">
Categoria articolului
</div>
<select wire:model="post_category" name="post_category" id="" class="form-select">
<option value="">--Nu ati ales nimic--</option>
#foreach (\App\Models\SubCategory::all() as $category)
<option value="{{$category->id}}">{{$category->subcategory_name}}</option>
#endforeach
</select>
<span class="text-danger">#error('post_category'){{$message}}#enderror</span>
</div>
<div class="mb-3">
<div class="form-label">
Imaginea articolului
</div>
<input type="file" wire:model="post_image" name="post_image" class="form-control">
<span class="text-danger ">#error('post_image'){{$message}}#enderror</span>
</div>
<div class="image-holder mb-2" style="max-width: 250px;">
<img src="" alt="" class="img-thumbnail" id="image-previewer" data-ijabo-default-img=''>
</div>
<button type="submit" id="sub" class="btn btn-primary">Salveaza</button>
</div>
</div>
</div>
</div>
</form>
And this is my component Posts.php
<?php
namespace App\Http\Livewire;
use App\Models\Post;
use Livewire\Component;
Use Livewire\WithFileUploads;
use App\Traits\ShowToastrTrait;
class Posts extends Component
{
use withFileUploads;
use showToastrTrait;
public $post_title, $post_content, $post_category, $post_image;
protected $rules = [
'post_title' => 'required|unique:posts,post_title|max:255',
'post_content' => 'required',
'post_image' => 'required|mimes:jpeg,png,jpg,gif,svg|max:2048',
'post_category' => 'required'];
protected $messages = [
'post_title.required' => 'Introduceti titlul articolului',
'post_title.unique' => 'Exista deja un asemenea titlu',
'post_content.required' => 'Introduceti continutul articolului',
'post_image.required' => 'Atasati o imagine articolului',
'post_image.mimes' => 'Imaginea trebuie sa fie in format jpeg/png/jpg/gif/svg',
'post_category.required' => 'Selectati categoria articolului',
];
public function addNewPost(){
dd($this);
$this->validate();
$post = Post::addNewPost($this);
if(!$post){
$this->showToastr('Articolul nu a putut fi adaugat','error');
}
$this->showToastr('Articolul a fost adaugat cu succes','success');
$this->reset();
}
public function render()
{
return view('livewire.posts');
}
}
I assume you have the script and the component view in separate files and that's why you get an error on #this('post_content').set('post_content', e.editor.getData()); line.
According to the docs, both should be placed in the same file (component file), then #this will be available in the script (you can read more about that here)
Example: let's assume you have a form component that will look like this:
<form>
<!-- your form elements -->
</form>
#push('scripts')
<script>
// accessing #this here should work
</script>
#endpush
Hope it helps :)

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.

pass user request in form action route in laravel 8

here is my simple form
<form id="test-form" class="white-popup-block mfp-hide">
<div class="popup_box ">
<div class="popup_inner">
<h3>Make an Appointment</h3>
<form action="{{route('doctorwithdatepopup',['date'=>$date,'id'=>$doctorsid])}}" method="POST">
#csrf
<div class="row">
<div class="col-xl-6">
<input id="datepicker" placeholder="Pick date" name="date">
</div>
#php
$Department = DB::table('departments')->orderBy('id','desc')->get();
#endphp
<div class="col-xl-6">
<select class="form-select wide" id="departmentid" name="departmentid">
<option data-display="Select Department">Department</option>
#foreach ($Department as $item)
<option value="{{$item->id}}">{{$item->name}}</option>
#endforeach
</select>
</div>
<div class="col-xl-12">
<select class="form-select wide" id="doctorsid" name="doctorsid" class="">
</select>
</div>
<br>
<br>
<div class="col-xl-12">
<button type="submit" class="boxed-btn3">Search</button>
</div>
</div>
</form>
</div>
</div>
</form>
inaction ['date'=>$date,'id'=>$doctorsid] these two data I want pass based on user selection how can I do that?
for example
$date = $request->date
this one can handle in the controller but in action URL how can I pass user enter values ?
Little tricky. Try to make 2 routes for that, first route to get user form requests. Second, your "doctorwithdatepopup" routes.
web.php
Route::post('url', [YourController::class, 'store'])->name('storeform');
Route::get('url2/{date}/{id}', [YourController::class, 'show'])->name('doctorwithdatepopup');
YourController.php
public function store(Request $request)
{
// Some Validation, Logic, etc
return redirect()->route('doctorwithdatepopup', ['date' => $request->date, 'id' => $doctorId]);
}
public function show($date, $id)
{
return view('your view', compact('date', 'id'));
}

How to stay data on dropdown list after page reloading in laravel 5.7?

I am creating task like dependent dropdown but i want to stay data as it is after reloading of page. I am successful to achieve this task for first dropdown but i am confuse how can i stay data for second dropdown Plz need help. I am putting value in session and check in option value but i am confuse in second option value that how can i check session value in javascript option value.
Blade :
<?php $reason_id=Session::get('reason_id');?>
<div class="row">
<div class="col-lg-4">
<span><label><b>Reason for return</b></label></span>
</div>
<div class="col-lg-8 mt-1">
<div class="form-group">
<select class="form-control" id="reason" name="reason">
<option readonly>Select reason</option>
#foreach($reason as $id => $p_reason)
<option value="{{ $id }}" #if($reason_id==$id) selected="selected"#endif>{{$p_reason}}</option>
#endforeach
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-4">
<span><label><b>Reason Details</b></label></span>
</div>
<div class="col-lg-8 mt-1">
<div class="form-group">
<select class="form-control" id="reason_detail" name="reason_detail">
</select>
</div>
</div>
</div>
javascript:
$(document).ready(function(){
$('#reason').change(function(){
var ID = $(this).val();
if(ID){
$.ajax({
type:"GET",
url:"{{url('get-reason-details')}}?reason_id="+ID,
success:function(res){
if(res){
$("#reason_detail").empty();
$("#reason_detail").append('<option>Select Reason Detail</option>');
$.each(res,function(key,value){
$("#reason_detail").append('<option value="'+key+'">'+value+'</option>');
});
}else{
$("#reason_detail").empty();
}
}
});
}else{
$("#reason_detail").empty();
}
});
controller:
public function set_session(Request $req)
{
$data=$req->all();
Session::put('reason_id',$data['reason']);
Session::put('reason_detail_id',$data['reason_detail']);
$data=DB::table('product_details')->select('product_details.*')->where('product_id',$data['product_id'])->first();
$reason=DB::table('reason')->pluck('description','reason_id');
return view('returnproduct',['reason'=>$reason],['data'=>$data->product_id]);
}
public function get_reason($id)
{
$data=DB::table('product_details')->select('product_details.*')->where('product_id',$id)->first();
$reason=DB::table('reason')->pluck('description','reason_id');
return view('returnproduct',['reason'=>$reason],['data'=>$data->product_id]);
}
public function get_reason_details(Request $req)
{
$reason_detail_id=Session::get('reason_detail_id');
$reason_details = DB::table("reason_details")
->where("reason_id",$req->reason_id)
->pluck("reason_detail","reason_detail_id");
return response()->json($reason_details);
}

Resources