I am interested in creating a dynamic dropdown on my form. For store.blade.php it's been successful. But for edit.blade.php, I don't know what to do. I can only set values for the first dropdown column, while the second dropdown column, I can't.
Edit: How to display the values for the idkelas column that have been stored in the Update Form?
Blade
Column1
<select name="idkamar" class="form-control">
<option value="">Pilih kamar</option>
#foreach ($kamar as $key=>$value)
<option value="{{ $key }}"{{ ( $listkamar->idkamar == $key ) ? ' selected' : '' }}>{{ $value }}</option>
#endforeach
</select>
Column2
<select name="idkelas" class="form-control"></select>
Javascript
<script type="text/javascript">
$(document).ready(function() {
$('select[name="idkamar"]').on('change', function() {
var kamarID = $(this).val();
if(kamarID) {
$.ajax({
url: '/kamar/ajax/'+kamarID,
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="idkelas"]').empty();
$.each(data, function(key, value) {
$('select[name="idkelas"]').append('<option value="'+ key +'">'+ value +'</option>');
});
}
});
}else{
$('select[name="idkelas"]').append('<option value="'+ key +'">'+ value +'</option>')
}
});
});
</script>
Controller
public function myformAjax($id)
{
$kelas = DB::table("kelas")
->where("idkamar",$id)
->pluck("name","id");
return json_encode($kelas);
}
public function edit($id)
{
$listkamar = ListKamar::find($id);
$kamar = DB::table("kamar")->pluck('name','id');
return view('listkamar.edit',compact('listkamar','kamar'));
}
You just need to pass $kelas in edit action. And in the view template, you will get all the values of that.
Related
I have two dropdown list in my Laravel page. I am trying to get old value of the dependent dropdown list (categorylist.blade) and make it selected once I fill and post the data. It returns back to the same page if the validation has not successfully completed. I am able to get all values except this one. I have tried Session::put() as well as Session::flash() but did not work. The category list is retrieved once you chose section as it requests the category list from the controller through ajax. How can I get the old value in the category dropdown list after the page refreshed.
Here is my section selection dropdown:
<select class="form-control sectionchoose" name="section_id" id="section_id">
<option value="">Choose Section</option>
#foreach($sections as $section)
<option value="{{$section['id']}}" #if(old('section_id') == $section['id']) selected #endif>{{$section['name']}} </option>
#endforeach
</select>
My categorylist dropdown:
<label class="col-sm-6">Chose Category</label>
<div class="categorylist">
#include('admin.deal-management.categorylist')
</div>
And this is my categorylist view file:
<select class="form-control " name="category_id" id="category_id">
<option value="">Choose Category</option>
#foreach($categories as $category)
<option value="{{$category['id']}}" #if(old('category_id') == $category['id']) selected #endif>
{{$category['category_name']}}
</option>
#endforeach
</select>
and this is my main controller:
public function addEditDeals(DealAddEditRequest $request, $id=null){
//*** post starts here ***/
if($request->isMethod('post')){
$message = 'Updated successfully';
$data=$request->all();
$deal->fill($request->validated());
$deal->save();
return redirect()->back()->with($message);
}
This is my categorylist controller:
public function findCategories(Request $request){
if($request->json()){
$data = $request->all();
$categories = Category::where(['section_id' => $data['id'], 'status'=>1])->get()->toArray();
return view('admin.deal-management.categorylist',compact('categories'));
}
}
And finally, this is the jQuery part:
$(document).ready(function (){
let sectionid = $('.sectionchoose').val();
$.ajax({
headers: {
'X-CSRF-TOKEN' : $('meta[name="csrf-token"]').attr('content')
},
type: 'POST',
datatype: 'json',
url : '/admin/selectsection',
data: {id:sectionid},
success: function(response){
$('.categorylist').html(response)
}, error:function(){
}
})
})
Finally, I was able to find the solution. Whoever has the same issue can use the approach below:
Step 1: Send the Session value through the with() command:
return redirect()->back()->withErrors($validator)
->withInput()->with('cat_id',$data['category_id']);
}
Step 2: Retreive the data in your main blade and attain hidden input:
<input class="cat_id" id="asd" type="hidden" value="{{Session::get('cat_id')}}"/>
Step 3: Get the retreived session value in Jquery:
$(document).ready(function (){
let sectionid = $('.sectionchoose').val();
let cat_id;
if($('#asd').val()){
cat_id = $('#asd').val();
} else {
cat_id = 0;
}
$.ajax({
headers: {
'X-CSRF-TOKEN' : $('meta[name="csrf-token"]').attr('content')
},
type: 'POST',
datatype: 'json',
url : '/admin/selectsection',
data: {id:sectionid, cat_id:cat_id},
success: function(response){
$('.categorylist').html(response)
}, error:function(){
}
})
})
Step 4: Send the session value to your dependent blade again (as cat_id here)
public function findCategories(Request $request){
if($request->json()){
$data = $request->all();
$cat_id = $data['cat_id'] ?? '';
$categories = Category::where(['section_id' => $data['id'], 'status'=>1])->get()->toArray();
return view('admin.deal-management.categorylist',compact('categories','cat_id'));
}
}
Done! As far as I know, there is not any other way to get old value of dependent dropdown list value so far.
Im having trouble to retrieve data into input box right after user select from dropdown. Any suggestion? Last suggest was not working.
internalaudit.blade.php
<div class="form-group">
{!! Form::label('text', 'Doc No', ['class' => 'col-lg-3 control-label']) !!}
<div class="col-lg-10">
<select name="docNo" id="docNo" class="form-control" style="width:250px">
#foreach ($soplists as $soplist)
<option value="{{ $soplist->id }}">{{ $soplist->doc_no }}</option>
#endforeach
</select>
</div>
</div>
<input type="text" class="form-control" name="rev_no" id="rev_no">
<input type="text" class="form-control" name="title" id="title">
Ajax
<script>
$('#docNo').change(function() {
var id = $(this).val();
var url = '{{ route("getDetails", ":id") }}';
url = url.replace(':id', id);
$.ajax({
url: url,
type: 'get',
dataType: 'json',
success: function(response) {
if (response != null) {
$('#rev').val(response.rev_no);
$('#title').val(response.title);
}
}
});
});
Controller
public function internalAudit()
{
/*Generate number*/
$query = Cars::latest()->first(); //get last query
$validators = User::all();
$departments = Department::all();
$isolists = isoList::all();
$soplists = sopList::all();
$ex = explode('/', $query['iaCarRefNo']); //explode last number from DB
$type = strtoupper(Request::segment(2)); //get type from url
if (empty($query->iaCarRefNo)) {
$number = '1';
$nextNumber = 'PLW' . '/' . date('y') . $type . '/' . sprintf("%03d", $number);
} else {
$number = $ex[2] + 1;
$nextNumber = 'PLW' . '/' . date('y') . $type . '/' . sprintf("%03d", $number);
}
return view('cars.internalaudit', compact('nextNumber', 'validators', 'departments', 'isolists', 'soplists'));
}
public function getDetails($id = 0)
{
$data = sopList::where('doc_no', $id)->first();
return response()->json($data);
}
Route
Route::get('get/details/{id}', 'internalAuditController#getDetails')->name('getDetails');
Route::get('/internalaudit', 'internalAuditController#internalAudit');
Route::post('/internalaudit', ['as' => 'internalaudit.store', 'uses' => 'internalAuditController#store']);
Database sop_list table image link
https://ibb.co/SwkJhLc
Dropdown and input image
https://ibb.co/0VN3Z2y
Network tab
https://ibb.co/56w5BLD
Accoding to your console.log there are 2 errors $.ajax is not function and $.(...) datetimepicker is not function beacuse of those errors, now your ajax does not work therefore you need to fix those issues first. Once you fix those issues you will be able to send ajax request and update input fileds.
To fix first problem, download the regular (compressed or not) version of jQuery and include it in your project.
To fix second problem, download relevant datetimepicker and include in your project same like jQuery.
After that update #rev selector to #rev_no
$('#rev_no').val(response.rev_no);
Also use laravel helper function instead echo json_encode();
return response()->json($data);
In your table there is no record for doc_no = 3, in your blade you're using $soplist->id
<option value="{{ $soplist->id }}">{{ $soplist->doc_no }}</option>
So do the same thing on controller,
$data = sopList::where('id', $id)->first();
Or
$data = sopList::find($id);
You gave a wrong id to response, also you should give an id to title input.
<input type="text" class="form-control" name="title" id="title">
<script>
$(document).ready(function(){
$(document).on('change','#docNo',function(){
var id = $(this).val();
var url = '{{ route("getDetails", ":id") }}';
url = url.replace(':id', id);
$.ajax({
type: 'get',
url: url,
dataType: 'json',
success: function(response) {
$('#rev_no').val(response.rev_no);
$('#title').val(response.title);
}
});
});
});
</script>
what is issue with my code, it returns empty drop down. i want drop down of nationality table, in teachers profile.
View:
<select class="form-control" name="nation_id" id="nation_id">
<input type="hidden" name="teacher_nation_id" id="teacher_nation_id"
value="{{ #$teacher->nation_id}}">
</select>
ajax code which returns empty dropdown: Ajax:
<script>
$(document).ready(function($){
$.get('nations-list', function(data) {
let teacher_nation_id = $('#teacher_nation_id').val();
let nations = $('#nation_id');
nations.empty();
$.each(data, function(key, value) {
nations.append("<option value='"+ key +"'>" + value + "</option>");
});
nations.val(teacher_nation_id);
});
});
</script>
My Controller:
public function ajaxrequest(Request $request)
{
$nations = Nation::all()->pluck('nation', 'id');
return response()->json($nations);
}
Here is my route:
Route:
Route::get('nations-list','TeachersController#ajaxrequest');
Try this,
<input type="hidden" name="teacher_nation_id" id="teacher_nation_id"
value="{{ #$teacher->nation_id}}">
<select class="form-control" name="nation_id" id="nation_id">
</select>
<select class="form-control" name="area" id="area">
</select>
Ajax code:
<script type="text/javascript">
$(document).ready(function($){
$('#nation_id').click(function($){
var tid = $('#teacher_nation_id').val();
if(tid){
$.ajax({
type:"get",
url:"{{url('/getNation)}}/"+tid,
success:function(res)
{
$('#nation_id').empty();
$("#nation_id").append('<option>--Select Nation--</option>');
if(res)
{
$.each(res,function(key,value){
$('#nation_id').append($("<option/>", {
value: key,
text: value
}));
});
}
}
});
}
});
$('#nation_id).change(function(){
var nid = $(this).val();
if(nid){
$.ajax({
type:"get",
url:"{{url('/getArea')}}/"+nid,
success:function(res)
{
$("#area").empty();
$("#area").append('<option>--Select Area--</option>');
if(res)
{
$.each(res,function(key,value){
$('#area').append($("<option/>", {
value: key,
text: value
}));
});
}
}
});
}
});
});
</script>
Controller:
public function getNation($id)
{
$nations= DB::table("nations")
->where("teacher_nation_id",$id)
->pluck("nation","id")
->toArray();
return response()->json($nations);
}
public function getArea($id)
{
$areas= DB::table("areas")
->where("nation_id",$id)
->pluck("area","id")
->toArray();
return response()->json($areas);
}
Route:
Route::get('/getNation/{id}','NationsController#getNation);
Route::get('/getArea/{id}','AriasController#getArea);
//Here I assumes that You have different controller named AreasController you can gave name of your controller
Hope it will useful for you..
Good Luck...
can someone please share working example of laravel ajax dropdown. there are so many examples about dependable dropdown, but i want simple dropdown of only one column, i have two tables teacher and nation, when teacher profile is open i want dropdown of nationality using ajax.
i have done it without ajax, but i don't know how to do with ajax.
without ajax:
<select name="nation_id" class="custom-select" >
<option selected value=" ">Choose...</option>
#foreach($nations as $nations)
<option value="{{#$nation_id}}" {{#$teacher->nation_id== $nations->id ? 'selected' : ''}} >{{#$nations->nation}}</option>
#endforeach
Controller:
$nations = nation::all();
<select class="form-control" name="nation_id" id="nation_id">
<option value="">Select nation</option>
#foreach($nations as $nation)
<option value="{{ $nation->nation_id }}">{{ $nation->nation_name }} </option>
#endforeach
</select>
<select class="form-control" name="teacher" id="teacher">
</select>
now the ajax code:
<script type="text/javascript">
$('#nation_id).change(function(){
var nid = $(this).val();
if(nid){
$.ajax({
type:"get",
url:"{{url('/getTeacher)}}/"+nid,
success:function(res)
{
if(res)
{
$("#teacher").empty();
$("#state").append('<option>Select Teacher</option>');
$.each(res,function(key,value){
$("#teacher").append('<option value="'+key+'">'+value+'</option>');
});
}
}
});
}
});
</script>
now in controller file;
public function getTeacher($id)
{
$states = DB::table("teachers")
->where("nation_id",$id)
->pluck("teacher_name","teacher_id");
return response()->json($teachers);
}
And last for route file:
Route::get('/getTeacher/{id}','TeachersController#getTeacher');
Hope this will work..
Good Luck...
Create a route for your method which will fetch all the nations-
Route::get('nations-list', 'YourController#method');
Create a method in your controller for the above route-
public function method()
{
$nations = Nation::all()->pluck('nation', 'id');
return response()->json($nations)
}
Add a select box like this in your HTML-
<select id="nation_id" name="nation_id"></select>
If you want to auto select the option based on a variable then you can do this-
<input type="hidden" name="teacher_nation_id" id="teacher_nation_id" value="{{ $teacher->nation_id ?? '' }}">
And then add this script in your HTML to fetch the nation list on page load-
<script>
$(document).ready(function($){
$.get('nations-list', function(data) {
let teacher_nation_id = $('#teacher_nation_id').val();
let nations = $('#nation_id');
nations.empty();
$.each(data, function(key, value) {
nations.append("<option value='"+ key +"'>" + value + "</option>");
});
nations.val(teacher_nation_id); // This will select the default value
});
});
</script>
I'm trying to use the data of the first dropdown, to fill the second.
An example here:
https://gitlab.com/Bons/laravel5.3_dynamic_dropdown/blob/master/readme.md
Controller functon return data, but second dropdown is empty.
First dropdown:
<span>Country: </span>
<select style="width: 200px" class="country" id="id_country">
<option value="0" disabled="true" selected="true">-Select-</option>
#foreach($countries as $contry)
<option value="{{$contry->id_country}}">{{$contry->name}}</option>
#endforeach
</select>
linked dropdown:
<label>City
<select id="region" class="form-control input-sm" name="region_id">
<option value=""></option>
</select>
</label>
Script:
<script type="text/javascript">
$(document).ready(function(){
$(document).on('change','.country',function(){
console.log("hmm its change");
var id=$(this).val();
console.log(id)
$.ajax({
type:'get',
url:'{!!URL::to('findRegions')!!}',
data:{'id':id},
success:function(data) {
console.log("success");
console.log(data.length);
console.log(data);
$.each(data, function(index,subCatObj){
// console.log(subCatObj.name)
$('#region').append(''+subCatObj.name+'');
});
},
error:function(){
console.log("error");
}
});
});
});
</script>
Route:
Route::get('/findRegions/','GirlsController#findRegions');
Controller function:
public function findRegions(Request $request){
$id=$request->id;
$regions=Region::select('name')
->where('id_country',$id)
->get();
dump($regions);
return $regions;
}
Here is how i did it,
in routes/web.php
Route::post('select-ajax', 'Main#selectAjax')->name('select-ajax');
in Controller : Main.php
public function __construct()
{
View::share('selectAllCountries', Country::pluck("name","id")->all());
}
public function selectAjax(Request $request)
{
if($request->ajax())
{
$getRegion = Region::where('id_country',$request->id)->pluck("nameOfTheRegion","id")->all();
$data = view('ajax-select',compact('getRegion'))->render();
return response()->json(['options'=>$data]);
}
}
then create a simple blade file name ajax-select.blade.php
<option selected disabled>--- Select Region---</option>
#if(!empty($getRegion))
#foreach($getRegion as $key => $value)
<option value="{{ $key }}">{{ $value }}</option>
#endforeach
#endif
Ajax call
{!! Form::select('country',[' '=>'--- Select Country ---']+$selectAllCountries,null,['class'=>'form-control']) !!}
{!! Form::select('region',[' '=>'--- Select Region---'],null,['class'=>'form-control']) !!}
<script>
$("select[name='country']").change(function(){
var id = $(this).val();
var token = $("input[name='_token']").val();
$.ajax({
url: "{{ route('select-ajax') }}",
method: 'POST',
data: {'id':id, '_token':token},
success: function(data) {
$("select[name='region']").html('');
$("select[name='region']").html(data.options);
},
error:function(){
alert("error!!!!");
}
});
});
</script>
Hope this helps