How to dynamic dropdown list in laravel 5.3? - javascript

My html is like this :
<div class="form-group has-feedback{{ $errors->has('kdkotama') ? ' has-error' : '' }}">
<select class="form-control" name="kdkotama" id="kdkotama">
<option value="">---- Pilih Kotama----</option>
#foreach($tkotam as $tkotam)
<option value="{{$tkotam->kdkotama}}">{{$tkotam->nmkotama}}</option>
#endforeach
</select>
#if ($errors->has('kdkotama'))
<span class="help-block">
<strong>{{ $errors->first('kdkotama') }}</strong>
</span>
#endif
</div>
<div class="form-group has-feedback{{ $errors->has('kdsatker') ? ' has-error' : '' }}">
<select class="form-control" name="kdsatker">
<option value="">---- Pilih Satker ----</option>
</select>
#if ($errors->has('kdsatker'))
<span class="help-block">
<strong>{{ $errors->first('kdsatker') }}</strong>
</span>
#endif
</div>
My javascript is like this :
<script>
$(document).ready(function() {
$("#kdkotama").change(function() {
console.log($("#kdkotama").val());
$.getJSON("../dropdowns/satkers/" + $("#kdkotama").val(), function(data) {
var $satkers = $("#kdkotama");
$satkers.empty();
$.each(data, function(index, value) {
$satkers.append('<option value="' + index +'">' + value + '</option>');
});
$("#kdkotama").trigger("change"); /* trigger next drop down list not in the example */
});
});
});
</script>
My routes/web is like this :
Route::get('dropdowns/satkers/{id}', 'DropDownController#getSatkers');
My controller is like this :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\TSatkr
class DropDownController extends Controller
{
public function getSatker($id)
{
$satkers = TSatkr::where('kdkotama', '=', $id)->get();
$options = array();
foreach ($satkers as $satker) {
$options += array($satker->kdsatkr => $satker->nmsatkr);
}
return Response::json($options);
}
}
I added this: console.log ($ ("# kdkotama"). val ()); in javascript. when I select kotama, the results of console.log that appear. but in the console, it did not succeed in calling controller. whereas the code, it looks like it is correct
is there anyone who can help me?

I faced so many problem to generate dynamic drop-down but now I do like this which is more powerful and useful to set dynamic drop-down value.
Lets generate DOM using method which can help us to generate dynamic DOM with one truth or source..
//Controller/HelperController.php
class HelperController
{
public static function ajaxDynamicDropDown($changeDropdown, $replaceDropdown, $url, $empty = []) {
$html = '<script type="text/javascript">';
$html.='jQuery(document).ready(function($) {';
$html.='jQuery("select[name=\'' . $change_dropdown . '\']").change(function(e){';
$html.='jQuery.ajax({';
$html.='type: "'.$action_type.'",';
$html.='url: "' . $url . '",';
$html.='dataType:"json",';
$html.='data: jQuery(this).parents("form").find("input,select").not("[type=hidden][name^=_]").serialize(),';
$html.='success:function(data){';
$html.=' jQuery("select[name=\'' . $replace_dropdown . '\']").find("option:not(:first)").remove();';
if (!empty($empty)) {
foreach ($empty as $key => $emt) {
$html.=' jQuery("select[name=\'' . $emt . '\']").find("option:not(:first)").remove();';
}
}
$html.=' jQuery.each(data, function(key,value){';
$html.=' jQuery("select[name=\'' . $replace_dropdown . '\']").append(\'<option value="\'+key+\'">\'+value+\'</option>\');';
$html.='});';
$html.='}';
$html.='});';
$html.='});';
$html.='});';
$html.='</script>';
return $html;
}
}
Benefit of it is I don't have to write change event for each dropdown. Also no need trigger.
// Blade File:
{!! Form::select('country_id',['1'=>'Test 1','2'=>'Test 2'],null,[]) !!} // First Dropdown with value
{!! Form::select('state_id',[],null,[]) !!} // Second Dropdown will set based on first one.
<script type="text/javascript">
{!! HelperController::ajaxDynamicDropDown('country_id','state_id',URL::to('ajax/states'),['state_id','city_id']) !!}
</script>
Now I am going to use implicit route controller. Using that I get controller methods based on the HTTP request type and name.
Mean in ajax if I used POST method request then in my controller my method name will be like postState() or if GET request then same getState(). For more please click here
//routes.php
Route::controller('ajax', 'AjaxController');
Here is code sample of AjaxController
// AjaxController.php
class AjaxController
{
public function postState()
{
// of course here I get Input by using request()->get('input_name')
return ['1'=>'test'];
}
}
Also you can set old value when validation going false with old() in AjaxController.
You can also use it for multiple dependencies like state if came from country now it can be possible you need to get city from state same method you can use for it..

Related

How to manage dependent dropdown list in php when create and update method is managed in same page

I have written the code to display the dependent dropdown list in php, when I create the record it is working. What changes I need to do while updating the record as I want the create and update method in same page.
Here's the code for reference,
<div class="form-group row m-b-15">
<label class="col-md-4 col-sm-4 col-form-label" for="fin_is_fin_req">
Is Finance Required? * :
</label>
<div class="col-md-4 col-sm-4">
<select name="fin_is_fin_req" id="is_finance" class="form-control" autofocus>
<option value="">-Select Finance-</option>
<?php
$fin_req=array('Yes','No');
foreach ($fin_req as $list) {
if ($allotment->fin_is_fin_req==$list):?>
<option selected value="<?=$list?>">
<?php else:?>
</option>
<option value="<?=$list?>">
<?php endif;?>
<?=$list?></option>
<?php } ?
</select>
</div>
</div>
<div class="form-group row m-b-15 ">
<label class="col-md-4 col-sm-4 col-form-label" for="fin_stage">
Finance Stage * :
</label>
<div class="col-md-4 col-sm-4">
<select name="fin_stage" id="stages" class="form-control">
</select>
</div>
</div>
$(document).ready(function () {
$('#is_finance').on('change', function () {
var finance_value = $("#is_finance").val();
$.ajax({
url: 'ajax/loadstages.php',
method: 'post',
data: 'finance_value=' + finance_value
}).done(function (stages) {
stages = JSON.parse(stages);
stages.forEach(function (stage) {
$('#stages').append('<option value=' + stage.id + '>' + stage.stage_name + '</option>')
})
})
});
});
loadstages.php
if (isset($_POST['finance_value'])) {
if ($_POST['finance_value'] == "Yes") {
$stages = FinStage::select('*', 'state=1');
//select(rows,where)
} else {
$stages = FinStage::select('*', 'state=0');
}
}
echo
json_encode($stages);
//screenshot during insert
//screenshot during update
If I understand you, you are saying that when you open the page, you want that page to show that second select, if the first dropdown has a value saved to it already? If that is the case, you can load it initially with PHP initially or you can adjust your JS to load the first dropdown at page ready:
<script>
// I might consider making this an object for reuse
class FormController
{
fetch(data, page, success)
{
$.ajax({
// Presumably all your ajax files are in this directory
url: `ajax/${page}.php`,
method: 'post',
data: data
}).done(r => {
// If your ajax pages send headers for Content-Type: application/json,
// you can skip the JSON parse if you want to
success(JSON.parse(r));
});
}
}
// If you extend the main form, you can use the ajax
class Finance extends FormController
{
getStages()
{
// Fetch the value from dropdown
const finance_value = $("#is_finance").val();
// Fetch the value of the first dropdown
super.fetch({ finance_value }, 'loadstages', r => {
// Do your append loop from the return
r.forEach(stage => {
$('#stages').append(`<option value=${stage.id}>${stage.stage_name}</option>`);
});
});
}
}
// Document ready
$(() => {
// Create the financial form
var FinForm = new Finance();
// Fetch the select value on page load
FinForm.getStates();
// On change, fetch the value again
$('#is_finance').on('change', () => {
FinForm.getStates();
});
});
</script>
Your PHP probably should be more like:
<?php
# Consider using this header
// header('Content-Type: application/json');
# Set a default, makes sure the json doesn't throw a warning if the condition
# is not set for whatever reason
$stage = [];
if (isset($_POST['finance_value'])) {
$finAffirm = ($_POST['finance_value'] == "Yes");
# You can just do this in one line so there is no duplication
$stages = FinStage::select('*', 'state='.(($finAffirm)? '1' : '0'));
# Fetch only on the affirmative
if ($finAffirm) {
//select(rows,where)
}
}
# It's safer just to exit here
die(json_encode($stages));

How can I succssefully acces an Global Variable from PHP in HTML

Pre Info:
In the PHP I declare a global array ($GLOBALS[]), in it I stow the data for the blade.
On the Blade i have a dropdown. If the dropdown changes, i send via AJAX the value to the Controller.
With the new data i calculate the new information, i want to show on the Blade.
But when I try to get the data in HTML like {{$GLOBALS['MyNumber']}} I only get the initialization value.
<?php
.
.
.
$GLOBALS = array(
'MyNumber' => 1,
'companyCode' => 0
);
class MyClass extends Controller
{
public function getData(){
$GLOBALS['companyCode'] = #$_POST['companyCode'];
if ($GLOBALS['companyCode'] == 902){
$GLOBALS['MyNumber'] = 100; //for the example, I set the data fix
}else{
$GLOBALS['MyNumber'] = 20; //for the example, I set the data fix
}
return response()->json(array('AJAX succses' => $response), 200);
}
.
.
.
In HTML i wanna show an dashboard-card with the new data like this:
I have 4 Cards and 7 Tables with data from SQL.
#section('page_content')
<div class="card #if($GLOBALS['MyNumber'] >95) dashboard-card-success #else card-anger-#endif" id="bkfI">
<div class="dashboard-title">
{{ __('bkf_usage') }} {{ today()->year }}
</div>
<div class="dashboard-content">
<div class="dashboard-number" id="bkf_usage">{{$GLOBALS['MyNumber'] }} %</div>
<div class="dashboard-description"></div>
</div>
</div>
But every time i reload the div (so the color can change) the $GLOBALS['MyNumber'] stays on the init of 1.
But the internal use (if $GLOBALS['companyCode']) works fine. How can i solve this issue? Or can you help me to find a work-around?
Maybe pass all the Vars back via ajax to JS and store tem in an JS variable? So i can still access from HTML to them?
Thank You!

Include id from drop down selector with eloquent laravel and html

I am pushing the 'name' instead of the 'id' value to my database. I need the correct eloquent call in order to display the specialty->id in my database rather than the name of the specialty itself. In this code, I am attempting to get the id in the $talents variable and use it as a value. However, when I attempt this, the selector does not let me choose more than one option. I THINK I NEED MULTIPLE VARIABLES FOR THIS, JUST NOT SURE HOW?
My view:
<div class="container">
{{ csrf_field() }}
<strong>Select Specialty:</strong>
<select id="multiple-checkboxes2" multiple="multiple" name="specialties" value="specialties_id">
#if($specialties)
#foreach($specialties as $specialty)
<option value= "{{ $talents }}">{{$specialty->name}}</option>
#endforeach
#endif
</div>
</select>
{!! Form::close() !!}
<script type="text/javascript">
$(document).ready(function() {
$('#multiple-checkboxes2').multiselect();
});
Client Store Controller
public function store(Request $request)
{
//
Client::create([
'specialties' => $request->specialties,
] );
return redirect('/accounts');
}
display controller
public function display($id)
{
*experimental*
$specialties=Specialty::select('id', 'name')->orderBy('id',
'asc')->get();
$talents=Specialty::select('id')->where('name', $specialties)->get();
*/experimental
return view('accounts/display', compact('accounts', 'specialties', )->withAccount($accounts);
}
}

Laravel 5.2 - Autocomplete Suggest

i'm creating a input autocomplete suggest from list of my database, but i have some problem, my input show the suggest like the picture:
Problem: My controller show 10 items like i want, but the termns doesn't work well, because as you can see if i write my municipality "Milan" it doesn't suggest correctly, actually my controller is showing the first 10 item of my table.
MY CONTROLLER:
public function getData(Request $request) {
$termn = $request->input('municipality');
// controllo
$data = Municipality::where('name', 'LIKE', '%'.$termn.'%')->take(10)
->get();
$results = array();
foreach($data as $v){
$results[]=['id' => $v->id, 'value' => $v->name];
}
//return $results;
return response()->json($results);
}
ROUTES
Route::get('getdata', 'PostController#getData');
JS
$('#searchname').autocomplete({
minLength: 1,
autoFocus: true,
source: $('#route-url').val(),
select: function(e, ui){
console.log(ui.item.id);// it work and show me id of item selected
},
});
VIEW FORM
<!-- Select Basic -->
<div class="form-group">
<label class="col-md-3 control-label" for="seller-Location">Municipality</label>
<div class="col-md-8">
<input
type="text"
name="municipality"
placeholder="comune"
class="form-control input-md"
id="searchname">
<input type="hidden" id="route-url" value="{{ url('getdata') }}">
</div>
</div>
If dd is empty, it's because there is no data for this key :)
Use var_dump($request->all()); or dd($request->all());
You will have the lsit of all parameters available.
I can see on your javascript's code source: $('#route-url').val(),.
So, I guess you will have values like this:
If result of dd is:
'source' => '...' Then, you will have to use $request->input('source')
0 => '...' Then, source is an array. Maybe try with source: {municipality: $('#route-url').val()} ?
If data is empty, then, you have another issue. Read the documentation/examples of the autocomplete library

How to passed selected list in stored procedure using Laravel 5.2

I can get the id of selected list using javascript. Like this.
<script>
function showCategoryOptions(s)
{
console.log(s[s.selectedIndex].value);
}
</script>
But I'm thinking how can I passed the value of the selected list in my stored procedure? How can I make a variable to get the value of selected list and passed it into my stored procedure? For I'm able to get the values.
SQL:
SELECT id FROM categories WHERE category_type = p_SelectedItem;
Here when I'm gonna equal the selected item in list. But still don't have any idea how will do this. Any help would appreciated!
Controller:
public function getDocuments()
{
$resultCategory = DB::table('categories')->get();
$myResult = DB::select('call getCategoryIdStoredProc(?)',array ($category));
return view ('document.create')with('resultCategory', $resultCategory);
}
I passed an array here in $myResult but unfortunately it gives me a error.
Undefined variable: category
Migration:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCategoriesTable extends Migration
{
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('category_type');
});
}
public function down()
{
Schema::drop('categories');
}
}
Routes:
Route::get('/create',
[
'uses' => '\App\Http\Controllers\DocumentController#getDocuments',
'as' => 'document.create',
'middleware' => 'auth',
]);
Form:
<div class = "form-group">
<label for = "category" class = "control-label">Category:</label>
<select onChange = "showCategoryOptions(this)" name = "category" class = "form-control">
#foreach ($resultCategory as $categoryList)
<option value = "{{ $categoryList->id }}">{{ $categoryList->category_type }}</option>
#endforeach
</select>
</div>

Categories

Resources