AngularJs 1.6 get values of form - php

I'm new to AngularJs and having some struggle.
Angular App:
// getting specs category
$http({
method: 'POST',
url: 'http://localhost/sjb/public/admin/angular/events/deelnemers/edit/specs',
data: {'specid': 11}
}).then(function successCallback(response){
$scope.SpecCategory = response.data;
console.log($scope.SpecCategory);
}, function errorCallback(response) {
alert("Fout met ophalen specs ID 11.");
});
Front-end
<select name="category" ng-model="user.cat_id">
<option ng-repeat="Cat in SpecCategory" ng-selected="Cat.spec_value == editEventUser.cat_id" value="{{Cat.spec_value}}">{{ Cat.spec_name }}</option>
</select>
values
Cat.spec_value = 1
editEventUser.cat_id = 1
But the option is not "selected" ?
Please help; what is wrong that
ng-selected="Cat.spec_value == editEventUser.cat_id"
Doesn't work?

The answer may be in the documentation for ng-select:
Note: ngSelected does not interact with the select and ngModel
directives, it only sets the selected attribute on the element. If you
are using ngModel on the select, you should not use ngSelected on the
options, as ngModel will set the select value and selected options.
Given your current code if you want to use ng-model, you have to remove ng-selected and make it so that user.cat_id is used to match one value in you select.
<select name="category" ng-model="user.cat_id">
<option ng-repeat="Cat in SpecCategory" value="{{Cat.spec_value}}">{{ Cat.spec_name }}</option>
</select>

Related

Laravel 5.6: Get selected value from a dropdown to use it in another

6, I'm using a dropdown to read a column from a database table. All I want is to get the selected value on that dropdown and use it to create a new query that will be populated in a new drop-down.
After reading and see several examples I see people using ajax and other people using laravel HTTP request like $request->get() so i don't know which way to take since I'm not familiar with any of those and even when trying several times can't get it to work.
Can anyone give me an insight into the best/efficient way to do it? Is it possible to do it only using php or some feature in laravel that I'm missing?
Here is my controller:
public function selectsector() //this is the dropdown #1 that works fine
{
$sectors = DB::table('Sectors')->whereBetween('SectorID', [1, 10])->value('SectorID');
return view('besttradesview', ['sectors10' => $sectors]);
}
public function selectsubsector() //dropdown #2 not working
{
$subsectors = DB::table('Sectors')->where('parentid', $sectors)->get();
//this line is not working it does not recognize $sector variable
return view('besttradesview', ['subsectors42' => $subsectors]);
}
View with dropdow #1: sector and #2: subsector
<form method="GET">
<div class="selectsector">
<Select class="selectsector" name = "sector">
#foreach($sectors10 as $sector)
<option>{{ $sector->SectorName }}</option>
#endforeach
</select>
<Select class="selectsubsector" name = "subsector">
#foreach($subsectors42 as $subsector)
<option>{{ $subsector->SectorName }}</option>
#endforeach
</select>
</form>
Routes:
Route::get('kitysoftware/besttrades', 'SectorsController#selectsector');
Route::get('kitysoftware/besttrades', 'SectorsController#selectsubsector');
Getting error: Undefined variable: sectors
Ok, i managed to do it using javascript and ajax function with json datatype. I'm new at JavaScript and it took me a while so i'm taking the time to publish the details for the newcomers. Here we go:
The View file:
The trick is to use a html hidden object that captures a route + prefix like in this line before the dropdowns:
<input type="hidden" name="application_url" id="application_url" value="{{URL::to(Request::route()->getPrefix()) }}"/>
The name of this object is "application_url" which we'll be using later in the javascript code to complete the url that the routes needs.
DropDown#1 with name "sectorSelect":
<label class="selectsector">Sector:</label>
<Select class="selectsector" id="sectorSelect" name="sectorSelect" >
<option value=""> -- Please select sector --</option>
#foreach ($sectors10 as $sector)
<option value="{{ $sector->SectorID }}">{{ $sector->SectorName }}</option>
#endforeach
</select>
DropDown #2 with name: "SubsectorSelect"
<label class="selectsector">SubSector:</label>
<Select class="selectsector" id="subSectorSelect" name="subSectorSelect">
<option value=""> -- Select an option --</option> // you don't have to do nothing here since this will be populated it from a query depending on the dropdown#1 selected value
</select>
Now in the web.php routes file:
Route::get('kitysoftware/sectors/subsectors/{id}', 'SectorsController#selectsubsector');
We are creating a route with an {id} parameter. This will be the selected value in dropdown #1. Then we call the "selectsubsector" method in the Sectorscontroller.
Controller:
First dropdown query:
public function selectsector()
{
$sectors = DB::table('Sectors')->select('SectorName', 'SectorID')-
>whereBetween('SectorID', [1, 10])->get();
return view('besttradesview', ['sectors10' => $sectors]);
Second Dropdown query (selectsubsector method):
public function selectsubsector($sectorId)
{
$subsectors = DB::table('Sectors')->select('SectorName', 'SectorID')->where('parentid', $sectorId)->get();
return response()->json($subsectors); //this line it's important since we are sending a json data variable that we are gonna use again in the last part of the view.
}
Final part of the view file The javaScript + ajax function
<script type="text/javascript">
$('#sectorSelect').change(function () { //we watch and execute the next lines when any value from the dropdown#1 is selected
var id = $(this).val(); //we get the selected value on dropdown#1 and store it on id variable
var url = $('#application_url').val(); //we get the url from our hidden element that we used in first line of our view file, and store it on url variable
//here comes the ajax function part
$.ajax({
url: url + "/kitysoftware/sectors/subsectors/" + id, //we use the same url we used in our route file and we are adding the id variable which have the selected value in dropdown#1
dataType: "json", //we specify that we are going to use json type of data. That's where we sent our query result (from our controller)
success: function (data) { //*on my understanding using json datatype means that the variable "data" gets the value and that's why we use it to tell what to do since here.*
//and this final part is where we use the dropdown#1 value and we set the values for the dropdown#2 just adding the variables that we got from our query (in controllert) through "data" variable.
$('#subSectorSelect').empty();
$.each(data, function (key, value) {
$('#subSectorSelect').append('<option value="' + key.SectorID + '">' + value.SectorName + '</option>');
});
}
});
});
</script>
Hope it helps the solution and the explanations. I'm happy to get some feedback as well.
I hope it is your requirement:
<Select class="selectsector" onChange="getSelectorValue( this, '#selector2' )" id="selector1" name="sector">
#foreach($sectors10 as $sector)
<option>{{ $sector->SectorName }}</option>
#endforeach
</select>
<Select class="selectsubsector" onChange="getSelectorValue( this, '#selector1' )" name = "subsector" id="selector2" >
#foreach($sectors10 as $sector)
<option>{{ $sector->SectorName }}</option>
#endforeach
</select>
Add Script to make it work:
<script type="text/javascript">
function getSelectorValue( selectorObj, selector ){
document.querySelector( selector ).value = selectorObj.value;
}
</script>
Controller
public function selectsector()
{
$sectors = Sector::get();
return view('besttradesview', compact('sectors'));
}
public function selectsubsector($sectors)
{
$subsectors = Sectors::where('parentid', $sectors)->get();
if (empty($subsectors)) {
$html = '';
$html = '<option value="">There has no Value</option>';
} else {
$html = '';
foreach ($subsectors as $subsector) {
$html .= '<option value="'.$subsector->id.'">'.$subsector->subsector.'</option>';
}
}
return response()->json(['html' => $html]);
}
route
Route::get('/get-selector/{id}', 'Inventory\selectorController#selectsubsector')->name('get.selector');
ajax
$(document).on('change','.selectsector',function () {
var id= $(this).val();
var url = "{{ URL::to('/get-selector') }}"+ '/' + id;
$.ajax({
url: url,
type: 'get',
dataType:'JSON',
success: function (response) {
console.log(response);
if(response.html==''){
$('.selectsubsector').html('<option value="">There has no Value</option>');
}else{
$('.selectsubsector').html(response.html);
}
},error: function (exception) {
console.log(exception);
}
});
});

Getting data from database using vuejs and laravel

I have a select element and based on the the selection, data is to be retrieved based on the id selected.
blade template
<div id="pers_obj" class="form-group form-duration-div">
{{Form::label("personal_objective", "Personal Objective/KPA")}}
<select name="personal_objective" id="personal_objective" v-model="personal_objective">
<option value="0" class="form-control">--Select Objective--</option>
#foreach($personal_objectives as $personal_objective)
<option value="{{ $personal_objective->id }}" class="form-control">{{ $personal_objective->name}}</option>
#endforeach
</select>
<div v-cloak>#{{personal_objective}}</div>
</div>`
measure.js
var pers_objective = new Vue({
el: '#pers_obj',
data:{
personal_objective: null
},
});
How can I:
retrieve data from database using vuejs
display data from the database using vue js
Looks like you are mixing a bit the PHP and JavaScript code trying some luck. The best way is creating a service response to get the personal objectives like an API.
So lets supose that you create a controller, called at /personal-objectives for example, that returns an array of objects with the structure of { id: number, name: string }
Then your code for the HTML would look like:
<div id="pers_obj" class="form-group form-duration-div">
<select name="personal_objective" v-model="personal_objective">
<option value="0" class="form-control">--Select Objective--</option>
<option v-for="po in pos" value="#{{ po.id }}" class="form-control">#{{ po.name }}</option>
</select>
</div>
And your JavaScript (assuming you are ussing vue-resource library for ajax calls) like:
var pers_objective = new Vue({
el: '#pers_obj',
data: function() {
return {
personal_objective: null,
pos: [];
};
}
created: function() {
this.loadPersonalObjectives();
}
methods: {
loadPersonalObjectives: function() {
this.$http.get('personal-objectives').then((response) => {
this.pos = response.data.pos;
}, (response) => {
console.log(response);
});
}
}
});
The above code will make an ajax GET call when the component is created to /personal-objectives which will return a JSON (don't forget to return the array encoded this way and set the proper header) array of bjects that on error will be displayed in console, and on succed the array will be assigned to the pos javascript variable and updated in the HTML creating the corresponding options reactively!
You may need to update the URL adding the root / in case you are not configuring the vue-resource with the root option (Vue.http.options.root)

How to get value from select value in Laravel

i need to get the value from a select tag, but the problem is that i need to send the value to the route for example :
<select name="feeling">
<option value="0">Joyous</option>
<option value="1">Glad</option>
<option value="2">Ecstatic</option>
I neeed to send the value to a route like this:
retrieve_money/0/account
How can i get the value and send into another route
retrieve_money/{in this camp i need the value}/account
Thanks.
Try this:
You could accomplish this using JavaScript by making the following modifications
In View
<select onChange="newFunction(this)" name="feeling">
<option value="0">Joyous</option>
<option value="1">Glad</option>
<option value="2">Ecstatic</option>
In Script
function newFunction(newVal){
window.location.href = '/retrieve_money/'+newVal+'/account';
}
In Routes
Route::get('/retrieve_money/{selectVal}/account', ['uses' => 'DemoController#demoFunction');
Hope this would get you started.

Populate dropdown based on another dropdown selected value in laravel - edit form

I found how to accomplish this on another site and I got it working. My issue is though that I need to use it in my edit form (preferably in the same form as my create form, since my create and edit views use the same form). When I go to my edit page, the "Section" dropdown value is selected as it should be. But the "Subsection" is not, because ofcourse I did not click it. Probably it's a fix too easy for me to see, but I am not quite good with javascript. I basically need the second dropdown (the subsection one) to show the correct options based on which "section" (first dropdown) is selected, on my edit view.
Section Model:
public function subsections()
{
return $this->hasMany('App\Subsection');
}
Subsection Model:
public function section()
{
return $this->belongsTo('App\Section');
}
View:
{!! Form::select('section_id', [null=>'-- Select Section --'] + $sections, null, array('id' => 'section')) !!}
<select id="subsection" name="subsection_id" class="select">
<option>-- First Select Section --</option>
</select>
From my controller: $sections = Section::lists('section', 'id');
Script:
<script>
$(document).ready(function($){
$('#section').change(function(){
$.get("{{ url('api/dropdown')}}",
{ option: $(this).val() },
function(data) {
$('#subsection').empty();
$.each(data, function(key, element) {
$('#subsection').append("<option value='" + key +"'>" + element + "</option>");
});
});
});
});
</script>
Route:
Route::get('api/dropdown', function(){
$id = Input::get('option');
$subsections = Section::find($id)->subsections;
return $subsections->lists('subsection', 'id');
});
If you just want to select the first option in jquery , you can add :
$('#subsection option:eq(1)').prop('selected', true);
Or else if you want to select a particular value, you can do that by
$('#subsection option[value="value_to_be_selected"]').prop('selected', true);
Use this after you have appended all the values to the subsection
In my controller I added:
$subsections = Subsection::where('section_id', '=', $transaction->section_id)->orderBy('subsection', 'asc')->lists('subsection', 'id');
And in my view I did this:
#if(isset($transaction))
{!! Form::select('subsection_id', [null=>'-- Select Subsection --'] + $subsections, null, array('class' => 'select', 'id' => 'subsection')) !!}
#else
<select id="subsection" name="subsection_id" class="select">
<option>-- First Select Section --</option>
</select>
#endif
Problem solved :)
So, what we will do is initially we will send value to the dependent drop-down as "<option value="">Select Something</option>"
and when returning on error create complete drop-down with selected as below value and return, this will reduce lots of javascript calls.
Controller:
if($error){
//create get array of second drop-down, suppose $second_drop
// create complete second drop-down like
$selectbox="";
foreach($second_drop as $option){
$selectbox.="<option value='". $option->id."'";
if($request->option2==$ $option->id){
$selectbox.=" selected ";
}
$selectbox.=">".$option->value."</option>";
}
}
return view('routename', ['selectbox2' => $selectbox]);
View:
<select id="subsection" name="subsection_id" class="select">
{!! $selectbox !!}
</select>

Laravel update form - get correct selected state

Within my update profile form, I have a select list for title. Admittedly, the items should be derived from the database however for the moment, I would like this particular select list to do the following..
Show the selected item on initial page load. So, if the $user['title'] is a 'Mrs', this is displayed.
Should laravel validation bring up errors on other form fields, and the user has changed the title to 'Mr', the selected state should be on the item 'Mr'.
I have the following so far, but it isn't working correctly.
<select name="title" id="title">
<option value="Mr" #if(($user['title']) == 'Mr') selected #else #if((Input::old('title')) == 'Mr') selected #endif #endif>Mr</option>
<option value="Mrs" #if(($user['title']) == 'Mrs') selected #else #if((Input::old('title')) == 'Mrs') selected #endif #endif>Mrs</option>
....
</select>
You should pass the data for the select from your Controller and also uset the Form component to build the select in the View, for example:
In Controller method:
$users = User::lists('title', 'id');
return View::make('user')->with('users', $user);
In the View:
// By default, item with id 1 (the first item) will be selected
echo Form::select('title', $users, Input::old('title', 1), ['id'=>title]);
If you are using Blade then:
// By default, item with id 1 (the first item) will be selected
{{ Form::select('title', $users, Input::old('title', 1), ['id'=>title]) }}
Read the documentation properly. You are using Laravel with old school PHP coding.

Categories