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

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);
}

Related

Laravel 8 Dynamic Dependent Input

it's been a while since I stuck in this problem. So I want to make a dynamic selection, when I select a nis (student_id) then the column nama (name) is filled with the student name.
Input form
Output i want
method create
public function create()
{
return view('admin.counseling.create', [
'title' => 'Tambah Bimbingan dan Konseling',
'students' => Student::all()
]);
}
create_blade.php
<form action="/admin/counseling/store" method="post" enctype="multipart/form-data">
#csrf
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Nomor Induk Siswa</label>
<select name="nis" required class="form-control" id="nis">
<option value="0" disabled="true" selected="true">-Pilih-</option>
#foreach($students as $student)
<option value="{{$student->id}}">{{$student->nis}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label>Nama</label>
<input type="text" class="form-control" name="name" required />
</div>
</div>
</div>
<div class="row">
<div class="col text-right">
<button
type="submit"
class="btn btn-success px-5"
>
Simpan
</button>
</div>
</div>
</div>
</form>
I have watched and read some questions with similar problems, and yet I still didn't get it
UPDATE
My method in my controller
public function find_nis(Request $request)
{
$data = Student::find($request->id); //Counseling::with('student', 'student.student_class')->where('student_id', $request->id)->first();
return response()->json(['view' => view('admin.counseling.create', ['data' => $data])->render()]);
}
My Ajax in create.blade.php
<script type="text/javascript">
$(document).ready(function (){
$(document).on('change','.student_nis',function () {
var student_id = $(this).val();
var a = $(this).parent();
console.log(student_id);
var op="";
$.ajax({
type : 'GET',
url : '{!! URL::to('find_nis') !!}',
data : 'id=' + student_id,
success:function(data){
console.log(data);
a.find('.student_name').val(data.name);
},
error:function(){
}
});
});
});
</script>
My Route
Route::get('/admin/counseling/find_nis', [CounselingController::class, 'find_nis'])->name('find_nis');
this is output in my browser console when i select nis 1212
i think for getting response from DB without refresh page you should use ajax,
post student_id with ajax to Controller get username from DB and return your view like this:
in your blade:
first you must set this meta tag inside of :
<meta name="csrf-token" content="{{ csrf_token() }}">
then config and post your data with ajax like this:
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var studentId = $("input[name=student]").val();
$.ajax({
xhrFields: {withCredentials: true},
type:'POST',
url:"{{ route('getStudentInfo') }}",
data:{studentId:studentId},
success:function(data){
$('html').html(data.view);
}
});
</script>
in your Controller inside of getStudentInfo():
$student = DB::table('user')->find($studen_id);
$username = $student->username;
return response()->json(['view' => view('admin.counseling.create', compact('username'))->render()]);
Here the working solutions
*Route
Route::get('/admin/counseling/find_student', [CounselingController::class, 'find_nis'])->name('find_student');
*Controller
public function create()
{
return view('admin.counseling.create', [
'title' => 'Tambah Bimbingan dan Konseling',
'students' => Student::all(),
'problems' => Problem::all()
]);
}
public function find_nis(Request $request)
{
$student = Student::with('student_class')->findOrFail($request->id);
return response()->json($student);
}
*blade
<div class="container-fluid mt--7">
<div class="mt-8">
<div class="dashboard-content">
<div class="row">
<div class="col-12">
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="/admin/counseling/store" method="post" enctype="multipart/form-data">
#csrf
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Nomor Induk Siswa</label>
<select name="nis" required class="form-control" id="nis">
<option value="0" disabled="true" selected="true">-Pilih-</option>
#foreach($students as $student)
<option value="{{$student->id}}">{{$student->nis}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label>Nama</label>
<input type="text" class="form-control" name="student_name" id="student_name" disabled required/>
</div>
<div class="form-group">
<label>Kelas</label>
<input type="text" class="form-control" name="student_class_name" id="student_class" disabled required/>
</div>
<div class="form-group">
<label>Permasalahan</label>
<div class="row">
<div class="col">
#foreach ($problems as $problem)
<div class="form-check">
<input type="checkbox" id="" name="problem_name[]" value="{{ $problem->name }}">
<label class="fs-6 fw-light">{{ $problem->name }}</label>
</div>
#endforeach
</div>
</div>
</div>
<div class="form-group">
<label>Bobot Permasalahan</label>
<select name="priority" required class="form-control" id="nis">
<option value="null" disabled="true" selected="true">-Pilih-</option>
<option value="1">Normal</option>
<option value="3">Penting</option>
<option value="5">Sangat Penting</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col text-right">
<button
type="submit"
class="btn btn-success px-5"
>
Simpan
</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
*ajax
<script type="text/javascript">
$(document).ready(function (){
$(document).on('change', '#nis', function() {
var student_id = $(this).val();
var a = $('#student_name').parent();
$.ajax({
type : 'GET',
url : '{{ route('find_student') }}',
data : 'id=' + student_id,
success:function(data){
a.find('#student_name').val(data.name);
},
error:function(){
}
});
});
$(document).on('change', '#nis', function() {
var student_id = $(this).val();
var a = $('#student_class').parent();
$.ajax({
type : 'GET',
url : '{{ route('find_student') }}',
data : 'id=' + student_id,
success:function(data){
a.find('#student_class').val(data.student_class.name);
},
error:function(){
}
});
});
});
</script>

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>);
});

Laravel - Validate textinput value with database value

I am using Laravel-5.8 for a web application. In the project I want the users to set goals using these two tables:
class GoalType extends Model
{
protected $table = 'goal_types';
protected $fillable = [
'name',
'parent_id',
'is_current',
'max_score',
];
public function children()
{
return $this->hasMany('App\Models\GoalType', 'parent_id');
}
public function goals()
{
return $this->hasMany('App\Models\Goal');
}
}
class Goal extends Model
{
protected $table = 'appraisal_goals';
protected $fillable = [
'goal_type_id',
'employee_id',
'weighted_score',
'goal_description',
'goal_title',
];
public function goaltype()
{
return $this->belongsTo('App\Models\GoalType','goal_type_id');
}
}
As shown in the diagram below, GoalType is an hierarchical table. Only the parent have the max_score:
Controller
public function create()
{
$userCompany = Auth::user()->company_id;
$categories = GoalType::with('children')->where('company_id', $userCompany)->whereNull('parent_id')->get();
return view('goals.create')
->with('categories', $categories);
}
public function store(StoreGoalRequest $request)
{
$employeeId = Auth::user()->employee_id;
$goal = new Goal();
$goal->goal_type_id = $request->goal_type_id;
$goal->employee_id = $employeeId;
$goal->weighted_score = $request->weighted_score;
$goal->save();
Session::flash('success', 'Goal is created successfully');
return redirect()->route('goals.index');
}
create.blade
<div class="row">
<div class="col-md-12">
<!-- general form elements -->
<div class="card card-secondary">
<!-- /.card-header -->
<!-- form start -->
<form method="POST" action="{{route('goals.store')}}">
#csrf
<div class="card-body">
<div class="form-body">
<div class="row">
<div class="col-12 col-sm-6">
<div class="form-group">
<label class="control-label"> Goal Type:<span style="color:red;">*</span></label>
<select id="goal_type" class="form-control" name="goal_type_id">
<option value="">Select Goal Type</option>
#foreach ($categories as $category)
#unless($category->name === 'Job Fundamentals')
<option disabled="disabled" value="{{ $category->id }}" {{ $category->id == old('category_id') ? 'selected' : '' }}>{{ $category->name }}</option>
#if ($category->children)
#foreach ($category->children as $child)
#unless($child->name === 'Job Fundamentals')
<option value="{{ $child->id }}" {{ $child->id == old('category_id') ? 'selected' : '' }}> {{ $child->name }}</option>
#endunless
#endforeach
#endif
#endunless
#endforeach
</select>
</div>
</div>
<div class="col-12 col-sm-6">
<div class="form-group">
<label class="control-label"> Goal Title:<span style="color:red;">*</span></label>
<input type="text" name="goal_title" placeholder="Enter goal title here" class="form-control">
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<label>Goal Description</label>
<textarea rows="2" name="goal_description" class="form-control" placeholder="Enter Goal Description here ..."></textarea>
</div>
</div>
<div class="col-12 col-sm-4">
<div class="form-group">
<label class="control-label"> Weight:</label>
<input type="number" name="weighted_score" placeholder="Enter weighted score here" class="form-control">
</div>
</div>
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-primary">{{ trans('global.save') }}</button>
<button type="button" onclick="window.location.href='{{route('goals.index')}}'" class="btn btn-default">Cancel</button>
</div>
</form>
</div>
<!-- /.card -->
</div>
<!--/.col (left) -->
</div>
From the diagram above, GoalType (goal_type_id) dropdown contains all the children fields from goal_types. What I want to achieve is this:
When Goal Type is selected from the dropdown, the system goes to the goals table (Goal). It displays total weighted_score based on employee_id and goal_type_id.
When the user tries to enter data into weight text field (weighted_score), the application adds the value in the text field to the result in number one (1) above. If the result is more than the max_score in goal_types (GoalType) based on the parent max_score, then an error message is displayed.
How do I achieve this?
Thank you.
You have to use AJAX for this, if you're unfamiliar with it, you can read about it here: https://www.w3schools.com/xml/ajax_intro.asp
I would also use JQuery to make things simpler. This way, you can do like this:
When Goal Type is selected from the dropdown, the system goes to the goals table (Goal). It displays total weighted_score based on employee_id and goal_type_id.
here you have to send to backend the goal type the user selected, for that, set an on change event in the combobox that triggers the AJAX request:
$('#goal_type').change(request_goals($('#goal_type').val()))
And the request_goals function should be like this:
function request_goals(){
$.ajax({
method: "GET",
dataType: 'json',
url: /*YOUR CONTROLLER URL*/,
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
console.log("error");
},
success: function (response) {
/* HERE DO WHAT YOU NEED */
}
}
You will have to create a route and a controller function that returns the data you need.
When the user tries to enter data into weight text field (weighted_score), the application adds the value in the text field to the result in number one (1) above. If the result is more than the max_score in goal_types (GoalType) based on the parent max_score, then an error message is displayed.
Here you should do the same trick, set an event handler in the weighted_score field that sends an ajax request.
I hope it can help you.
If you want to archive it without AJAX calls, you can submit the form on select box change: <select name="goal_type_id" onchange="this.form.submit()">
In the controller you can catch the old input with old("goal_type_id"). You can query/calculate now the total weighted_score.

How to display data to textfield from combo selection in laravel

I'd like to display data to textfield based on combo/drop box selection in laravel 5.8. then save the data. is there complete tutorial how to do it from model, view and controller.
In Customer Controller
public function create()
{
$customer= Customer::all();
return view('Customer.create', compact('Customer'));
}
in view create.blade
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>CUSTOMER</strong>
<select type="text" class="form-control" name="kde_cust" id="cde_customer" required>
<option value=""> -- PICK CUST-- </option>
#foreach($cust as $cust)
<option value="{{ $cust->cde_cust }}" selected>{{ $cust->nme_customer }}</option>
#endforeach
</select>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>NAME</strong>
<input type="text" name="cust_name" id="cust_name" class="form-control" value="{{ $cust->nme_customer }}">
</div>
</div>
This should helps:
Create a route to get the user address:
Route::get('user-address/{user_id}','YourController#method')->name('user.address');
Your controller method should look like this:
public function yourFunction($cde_customer)
{
$customer = Customer::where('cde_customer', $cde_customer)->first();
$address = $customer->address;
return response()->json([
'address' => $address,
]);
}
Add this script to your blade:
$("#cde_customer").on('change', function(){
var user_id = $(this).val();
$.ajax({
url: '/user-address/' + user_id,
method: 'GET',
success: function(response){
$("#textfield").html(response.address);
}
});
});
Hope it helps.

Dropdown based on one table passing to other fields using ajax laravel

I'm having problem with regards to selected dropdown passing fields value to other input.
Basically I have one table (plans) which have id, plan_name, price. So i want to pass price to the other input.
So I expect the output that if I selected one of the choices the price will be on the price input.
blade.php
<div class="control-group">
<label class="control-label">Plan</label>
<div class="controls">
<select name="plan_id" id="plan_id" class="plan" style="width:220px">
<option value="0">Select</option>
#foreach($plans as $plan)
<option value="{{ $plan->id}}" >{{$plan->plan_name}}</option>
#endforeach
</select>
</div>
</div>
<div class="control-group">
<label class="control-label">Price</label>
<div class="controls">
<input class="plan_price" type="number" name="price" id="price">
</div>
</div>
Here is the ajax i tried:
$(document).ready(function(){
$(document).on('change','.plan',function(){
//console.log("hmm its change");
var plan_id=$(this).val();
console.log(plan_id);
$.ajax({
type: 'get';
url:'{!!URL::to('findPrice')!!}',
data:{'id':plan_id},
dataType:'json',
success:function(data){
console.log("price");
console.log(data.price);
a.find('.plan_price').val(data.price);
},error:function(){
}
})
})
});
in my controller I have this function:
I dont know if this is also correct on the where part.
public function findPrice(Request $request){
$p = Plan::select('price')->where('id',$request->id)->first();
return response()->json($p);
}
Route::
Route::get('/findPrice','SubscriptionController#findPrice');

Resources