dependent dropdown in form edit laravel - php

Hello everyone i need help.
I make dynamic dependent dropdown in Laravel 8, when create data it's work, but when i will edit data, dependent dropdown not selected in view edit.
My code like this,
view.blade
<label class="font-label">Provinsi</label>
<select name="prov_ktp" id="prov_ktp" class="form-control forms-input">
<option value="">Pilih Provinsi</option>
#foreach ($provinsi as $key => $prov)
<option value="{{ $key }}">{{ $prov }}</option>
#endforeach
</select>
<label class="font-label">Kota/Kabupaten</label>
<select name="kab_ktp" id="kab_ktp" class="form-control forms-input">
<option value="">Pilih Kota/Kabupaten</option>
</select>
<script>
$('#prov_ktp').change(function() {
var provinsiID = $(this).val();
if (provinsiID) {
$.ajax({
type: "GET",
url: "{{ url('get-kabupaten') }}?id_provinsi=" + provinsiID,
success: function(res) {
if (res) {
$('#kab_ktp').empty();
$('#kab_ktp').append('<option value="">Pilih Kota/Kabupaten</option>');
$.each(res, function(key, value) {
$('#kab_ktp').append('<option value="' + key + '">' + value + '</option>');
});
} else {
$('#kab_ktp').empty();
}
}
});
} else {
$('#kab_ktp').empty();
$('#kec_ktp').empty();
}
});
</script>
myController
// function display provinsi
public function showDalamNegeri() {
$provinsi = Provinsi::pluck('nama_provinsi', 'id_provinsi');
return view('data_pribadi.dalam_negeri', compact('provinsi'));
}
// function display kabupaten
public function getKabupaten(Request $request) {
$kabupaten = Kabupaten::where('id_provinsi', $request->id_provinsi)->pluck('nama_kabupaten', 'id_kabupaten');
return response()->json($kabupaten);
}
Route for display Kabupaten
Route::get('get-kabupaten', [DataPribadiController::class, 'getKabupaten'])->name('getKabupaten');
Thanks.

Related

The second dropdown value for multiple dropdown value NOT SAVE in database using laravel

Hye everyone! First of all, my coding all about dynamic dropdown value, the issues now is the second dropdown value is not save inside the database. Which part did I missed or wrong?
View:-
<div class="col-md-3">
<select class="shiftPatternID" name="inputShiftPatternID" id="inputShiftPatternID" required style="width: 100%">
<option value="" hidden disabled selected>Please Select</option>
#foreach ($shiftpattern as $singleshiftpattern)
<option value="{{ $singleshiftpattern->id }}">{{ $singleshiftpattern->id }} - {{ $singleshiftpattern->code }}</option>
#endforeach
</select>
</div>
<div class="col-md-3">
<select class="sapCode" name="inputSapCode" id="inputSapCode" required style="width: 100%">
<option value="0" disabled="true" selected="true">Please Select</option>
</select>
</div>
View for second dropdown using jquery script:-
$(document).ready(function() {
$(document).on('change','.shiftPatternID',function() {
var cat_id=$(this).val();
var div=$(this).parent().parent().parent();
var op=" ";
$.ajax({
type: 'get',
url: '{!! URL::to('findSapCode') !!}',
data: {
'id':cat_id
},
success: function(data) {
op+='<option value="0" selected disabled>Please Select</option>';
for (var i=0;i<data.length;i++) {
op += '<option value="'+data[i].id+'">'+data[i].code+' - '+data[i].description+'</option>';
}
$('.sapCode').html('') ;
$('.sapCode').append(op);
},
error: function() {
}
});
});
});
Controller:-
public function store(Request $req)
{
$var_shift_pattern_id = $req ->inputShiftPatternID;
$var_sap_code = $req ->inputSapCode;
$usp_var = new UserShiftPattern;
$usp_var-> shift_pattern_id = $var_shift_pattern_id;
$usp_var-> sap_code = $var_sap_code;
$usp_var->save();
$execute = UserHelper::LogUserAct($req, "User Work Schedule Management", "Create User Work Schedule " .$req->inputUserID);
$feedback_text = "Successfully created User Work Schedule ".$req->inputUserID.".";
$feedback_title = "Successfully Created";
return redirect(route('usp.index', [], false))
->with([
'feedback' => true,
'feedback_text' => $feedback_text,
'feedback_title' => $feedback_title
]);
}
Routes:-
Route::get('/findSapCode','Admin\UserShiftPatternController#findSapCode');
Route::get('/admin/usershiftpattern', 'Admin\UserShiftPatternController#index')->name('usp.index');
Route::post('/admin/usershiftpattern/add', 'Admin\UserShiftPatternController#store')->name('usp.store');
Route::post('/admin/usershiftpattern', 'Admin\UserShiftPatternController#index')->name('usp.index');
The issue is with option value wrongly passed in jquery.It should be data[i].code instead of data[i].id
op+='<option value="'+data[i].code+'">'+data[i].code+" "+data[i].description+'</option>'
Also you might need to update query as well to show description
$data=ShiftPattern::select('code','id','description')->where('id',$request->id)->take(100)->get();

I want text type to be stored in database instead of the id Ajax Laravel 7

I am new to Ajax. So, excuse my lack of knowledge. When I pass the data in the view, I get IDs in my database. Even though I passed text from a dropdown dependent menu is that possible with explanation!
Please see those 2 tables category
and products
I wanted to get the names from category ('Désignation' => first table) in my view - but instead I got the IDs. Please help.
controller
public function create() {
$prod=ProductCat::all();
return view('Achats.create',compact('prod'));
}
public function findProductName(Request $request) {
$data = Product::select('Désignation','id') -> where('catégorie', $request->id) -> take(100) -> get();
return response()->json($data);
}
public function findRef(Request $request) {
$p = Product::select('Référence')->where('id',$request->id)->first();
return response()->json($p);
}
Routes
Route::get('create','AchatController#create')->name('create.Achat');
Route::get('/findProductName','AchatController#findProductName');
Route::get('/findRef','AchatController#findRef');
View
<form action="{{ route('Achat.store')}}" method="POST" enctype="multipart/form-data">
<span>Product Category: </span>
<select style="width: 200px"class="form-control catégorie" name="catégorie" id="catégorie" >
<option value=" " disabled="true" selected="true">-Select-</option>
#foreach($prod as $cat)
<option value="{{$cat->id}}">{{$cat->Désignation}}</option>
#endforeach
</select>
<span>Product Name: </span>
<select name ="Désignation" class="form-control Désignation" id="Désignation" style="width: 200px" >
<option value="" disabled="true" selected="true">Product Name</option>
</select>
<span>Product ref: </span>
<input name="Référence" id="Référence" class="form-control Référence" type="text" >
<br>
ajax
<script type="text/javascript">
$(document).ready(function(){
$(document).on('change','.catégorie',function(){
// console.log("hmm its change");
var cat_id=$(this).val();
// console.log(cat_id);
var div=$(this).parent();
var op=" ";
$.ajax({
type:'get',
url:'{!!URL::to('findProductName')!!}',
data:{'id':cat_id},
success:function(data){
//console.log('success');
//console.log(data);
//console.log(data.length);
op+='<option value="0" selected disabled>chose product</option>';
for(var i=0;i<data.length;i++){
op+='<option value="'+data[i].id+'">'+data[i].Désignation+'</option>';
}
div.find('.Désignation').html(" ");
div.find('.Désignation').append(op);
},
error:function(){
}
});
});
$(document).on('change','.Désignation',function () {
var prod_id=$(this).val();
var a=$(this).parent();
console.log(prod_id);
var op="";
$.ajax({
type:'get',
url:'{!!URL::to('findRef')!!}',
data:{'id':prod_id},
dataType:'json',//return data will be json
success:function(data){
console.log("Référence");
console.log(data.Référence);
// here price is column name in products table data.coln name
a.find('.Référence').val(data.Référence);
},
error:function(){
}
});
});
});
It looks like you are passing the Id as the value, hence the reason for getting the Id in your database table.
Change
#foreach($prod as $cat)
<option value="{{$cat->id}}">{{$cat->Désignation}}</option>
#endforeach
To
#foreach($prod as $cat)
<option value="{{$cat->Désignation}}">{{$cat->Désignation}}</option>
#endforeach
That should help.

Laravel dynamic dropdown fetching data issues

I want to list down the users according to the user_types while inserting so I created the two tables and each table has connections. Each model PHP file has a relationship function. and I created the jquery code and I created the controller function but it's not working I don't know where I making the mistake please help me to fix this problem. I attached all code I have written and the database also.
User Type Database
User Database Table
UserType Id and User Table usty_id has connections
UserType Model
<?php
namespace Asset_Management_System;
use Illuminate\Database\Eloquent\Model;
class UserType extends Model
{
public function userpermission()
{
return $this->hasMany('Asset_Management_System\UserPermission');
}
public function user()
{
return $this->hasMany('Asset_Management_System\User');
}
}
User Model
class User extends Authenticatable
{
public function usertype()
{
return $this->belongsTo('Asset_Management_System\UserType','usty_id');
}
}
Insert Form
<div class="form-group">
<label>User Type</label>
<select class="form-control select2" style="width: 100%;" id="ust_id" name="ust_id">
<option selected="selected">Select User Type</option>
#foreach($UserType as $ust)
<option value="{{$ust->id}}">{{$ust->usty_name}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label>User</label>
<select class="form-control select2" style="width: 100%;" id="user_id" name="user_id">
<option selected="selected">Select User</option>
#foreach($User as $us)
<option value="{{$us->id}}">{{$us->us_fname}} {{$us->us_lname}}</option>
#endforeach
</select>
</div>
Controller
public function show(Request $request)
{
//echo $id;
if (!$request->usty_id) {
$html = '<option value="">'.trans('global.pleaseSelect').'</option>';
} else {
$html = '';
$user = User::where('usty_id', $request->usty_id)->get();
foreach ($user as $us) {
$html .= '<option value="'.$us->id.'">'.$us->us_fname.' '.$us->us_lname.'</option>';
}
}
return response()->json(['html' => $html]);
}
And Jquery
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$("#ust_id").change(function(){
$.ajax({
url: "{{ route('WorkRequest.show') }}?usty_id=" + $(this).val(),
method: 'GET',
success: function(data) {
$('#user_id').html(data.html);
}
});
});
</script>
Route
Route::get('WorkRequest/show', 'WorkRequestController#show')->name('WorkRequest/show');
And this is the error I'm getting when I go to the form
Missing required parameters for [Route: WorkRequest.show] [URI: WorkRequest/{WorkRequest}]. (View: C:\xampp\htdocs\Asset_Management_Laravel\resources\views\layouts\main.blade.php)
Please Help me to solve this issues
This Code is working perfectly
<script type="text/javascript">
$(document).ready(function(){
// Department Change
$('#ust_id').change(function(){
// Department id
var id = $(this).val();
// Empty the dropdown
$('#user_id').find('option').not(':first').remove();
// AJAX request
$.ajax({
url: "{{ route('WorkRequest/show') }}?usty_id=" + id,
type: 'get',
dataType: 'json',
success: function(response){
//alert(response);
$('#user_id').html(response.html);
}
});
});
});
</script>
public function show(Request $request)
{
//echo $id;
$html = '';
$user = User::where('usty_id', $request->usty_id)->get();
foreach ($user as $us)
{
$html .= '<option value="'.$us->id.'">'.$us->us_fname.' '.$us->us_lname.'</option>';
}
return response()->json(['html' => $html]);
}
Replace above Route with this-Route::post('workRequest/get_options','WorkRequestController#getOptions')->name('workRequest.options'); and place above the route::resource() route
And ajax code as below
$("#ust_id").change(function(){
let parameter = {'usty_id': $(this).val()};
$.ajax({
url: "{{ route('workRequest.options') }}",
method: 'POST',
data: parameter,
success: function(data) {
$('#user_id').html(data.html);
}
});
});
Add this Controller method to get options
public function getOptions(Request $request)
{
if (!$request->usty_id) {
$html = '<option value="">'.trans('global.pleaseSelect').'</option>';
} else {
$html = '';
$user = User::where('usty_id', $request->usty_id)->get();
foreach ($user as $us) {
$html .= '<option value="'.$us->id.'">'.$us->us_fname.' '.$us->us_lname.'</option>';
}
}
return response()->json(['html' => $html]);
}

How to get data based on 1st table id contain in 2nd table using ajax codeigniter on dropdown lists

I have three tables like tbl_customers, tbl_items, tbl_customersOrders. I inserted the tbl_customers ID and tbl_items ID into the tbl_customersOrders which as a foreign key. Now think is based on first drop-down lists (here the tbl_customersOrders ID) I can fetch another two fields on other drop-down lists but .... I need the name of the customers which is id matched...also items name which is id matched Like:
what I tried:
Controller Code:
$data['gets_order'] = $this->box_property_model->getCustDataOrder();
Model Code:
public function getCustDataOrder()
{
$this->db->select('*');
$this->db->order_by('customer_orders_id', 'DESC');
$query = $this->db->get('tbl_customer_orders');
return $query->result();
}
View code:
<select name="nestedOrder" class="form-control" >
<option value="">--- Select Order ---</option>
<?php if(!empty($gets_order)) {
foreach($gets_order as $nst){
?>
<option value="<?php echo $nst->customer_orders_id; ?>"><?php echo $nst->new_id_generated; ?></option>';
<?php } } ?>
</select>
<label for="custNested">Customer Name-</label>
<select name="custNested" id="custNested" class="form-control" >
<option value="">Select ITEMS ID</option>
</select>
<label for="ItemsName">Items Name</label>
<select name="items_ids" id="getsitemsName" class="form-control" >
<option value="">Select ITEMS</option>
</select>
<label for="testing">Final ITEM Name</label>
<select name="org_itemsNameValue" id="org_itemsNameValue" class="form-control" >
<option value="">Select ITEMS Name</option>
</select>
JS CODE:
<script type="text/javascript">
$(document).ready(function() {
$('select[name="nestedOrder"]').on('change', function() {
var customID = $(this).val();
alert(customID);
$.ajax({
url: '<?php echo base_url();?>/Box_property/DropdownsAjaxNested/'+customID,
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="custNested"]').empty();
$('select[name="custNested"]').append('<option value="0">--Select CUSTTT--</option>');
$.each(data, function(key, value) {
$('select[name="custNested"]').append('<option value="'+value.customer_id + '">'+ value.customer_name +'</option>');
});
}
});
$.ajax({
url: '<?php echo base_url();?>/Box_property/DropdownsAjaxNestedItems/'+customID,
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="items_ids"]').empty();
$('select[name="items_ids"]').append('<option value="0">--Select --</option>');
$.each(data, function(key, value) {
$('select[name="items_ids"]').append('<option value="'+value.items_id +'">'+ value.items_id +'</option>');
});
}
});
});
$('select[name="items_ids"]').on('change', function() {
var items_ids = $(this).val();
alert(items_ids);
$.ajax({
url: '<?php echo base_url();?>/Box_property/itemsOrdersIDfetch/'+items_ids,
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="org_itemsNameValue"]').empty();
$('select[name="org_itemsNameValue"]').append('<option value="0">--Select ITEMS Name--</option>');
$.each(data, function(key, value) {
$('select[name="org_itemsNameValue"]').append('<option value="'+value.items_id + '">'+ value.items_name +'</option>');
});
}
});
});
});
</script>
In Controller:
public function DropdownsAjaxNested($id) {
$result = $this->db->where("customer_id",$id)->get("tbl_customers")->result();
echo json_encode($result);
}
public function DropdownsAjaxNestedItems($id) {
$result = $this->db->where("customer_orders_id",$id)->get("tbl_items_order")->result();
echo json_encode($result);
}
public function itemsOrdersIDfetch($id){
$result = $this->db->where("items_id",$id)->get("tbl_items_master")->result();
echo json_encode($result);
}

Laravel save option text in php

I have this code select state -> show state cities :
<div class="form-group">
{{ Form::label('state', 'State') }}
<select name="state" id="state" class="form-control">
<option value="">{{ __('Select Province') }}</option>
#foreach ($state->data as $info)
<option value="{{$info->province_id}}">{{$info->province}}</option>
#endforeach
</select>
</div>
<div class="form-group">
{{ Form::label('city', 'City') }}
<select class="form-control" name="city" id="city">
<option value="">{{ __('Select City') }}</option>
</select>
</div>
and this javascript:
<!-- find cities -->
<script type="text/javascript">
$(document).ready(function() {
$('select[name="state"]').on('change', function() {
var provinceID = $(this).val();
if(provinceID) {
$.ajax({
url: '{{ url('admin/getcitylistshipping') }}/'+encodeURI(provinceID),
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="city"]').empty().append("<option value='' selected>Select</option>");
$.each(data.data, function(key, value) {
$('select[name="city"]').append('<option value="'+ value['city_name'] +'">'+ value['type'] + ' - ' + value['city_name'] +'</option>');
});
}
});
}else{
$('select[name="city"]').empty().append("<option value='' selected>Select</option>");
}
});
});
</script>
What I want is to save options text in my database instead of their
value (which is ID).
what I did
As my cities list comes by json and nothing depended on them I changed my values in my script from value="'+ value['city_id'] + to value="'+ value['city_name'] + and I get my city names instead of their id's.
But my issue is with my states (provinces) part, in that part I need to have state id as value in order to return city names but i don't want to save that id in my database, what i want is to save option name.
Here is my store method:
$this->validate($request, array(
'state' => 'nullable',
));
$shipping->state = $request->input('state');
how can I save my selected state text instead of their id in my
controller?
ideas?
SOLVED
I added extra hidden input to my blade and changed my script to:
html
<div name="statehidden" id="statehidden"></div>
script
<script type="text/javascript">
$(document).ready(function() {
$('select[name="state"]').on('change', function() {
var provinceID = $(this).val();
var statename = $("select[name='state'] option:selected").text(); //add this
if(provinceID) {
$.ajax({
url: '{{ url('admin/getcitylistshipping') }}/'+encodeURI(provinceID),
type: "GET",
dataType: "json",
success:function(data) {
$('#statehidden').empty(); //add this
$('#statehidden').append("<input type='text' name='statehidden' id='statehidden' value='"+statename+"'>"); //add this
$('select[name="city"]').empty().append("<option value='' selected>Select</option>");
$.each(data.data, function(key, value) {
$('select[name="city"]').append('<option value="'+ value['city_name'] +'">'+ value['type'] + ' - ' + value['city_name'] +'</option>');
});
}
});
}else{
$('#statehidden').empty(); //add this
$('select[name="city"]').empty().append("<option value='' selected>Select</option>");
}
});
});
</script>

Categories