VueJs and Laravel - multiple select fields - laravel

Using Laravel 5.4 and Vuejs 2.1
In code I have a select field with two input fields (quantity and stock) in tr (Table Row). Table Row with the fields can be dynamically added as much as user is needed, this is the code:
<tbody id="loads-content">
<tr v-for="(item, index) in items">
<td>
<select v-model="item.load_id" name="load_id[]" class="loads" v-on:change="getLoadStock()">
<option v-for="load in loads" :value="load.id" :id="load.id">{{load.name}}</option>
</select>
</td>
<td><input type="text" v-model="item.quantity" name="quantity[]" class="input is-hovered qty"></td>
<td><input type="text" v-model="item.stock" class="input is-hovered stock" disabled readonly="true"></td>
<td>
<button type="button" class="button is-danger remove" #click="items.splice(index, 1)"><i class="fa fa-minus-square-o" aria-hidden="true"></i></button>
</td>
</tr>
<a #click="addLine" class="button is-success"><i class="fa fa-plus-square-o" aria-hidden="true"></i></a>
</tbody>
When you choose some value from select field I need to populate the STOCK input field with stock data from the database. For that I used an API call. I made something like this:
methods: {
addLine() {
this.items.push({
load_id: '',
quantity: '',
stock: ''
})
},
getLoadStock(){
var loadsContent = $('#loads-content');
var tr = loadsContent.parent().parent();
var id = tr.find('.loads').val();
axios.get('/api/load/' + id)
.then(function(response) {
tr.find('.stock').val(response.data.stock);
})
.catch(function(error) {
console.log(error)
});
},
This code is not working as expected.
The goal is to fetch actual stock for current choosen load, to see how much quantity can you enter in the input field for quantity.
I am open for any suggestions, if anyone has a better approach and solution please help.
Thanks in advance! :)

You are mixing two different and incompatible ways of building a web app: Vue.js and jQuery.
When using Vue, you should not be manipulating the DOM directly. You should instead be binding the DOM elements to Vue model attributes. Then, if you need a DOM element to reflect a change, you change the model – not the DOM.
So for instance, you would want something like this (note adding index as an argument to getLoadStock):
<select v-model="item.load_id" name="load_id[]" class="loads" v-on:change="getLoadStock(index)">
<option v-for="load in loads" :value="load.id" :id="load.id">{{load.name}}</option>
</select>
and
getLoadStock(index){
axios.get('/api/load/' + this.items[index].load_id)
.then(function(response) {
this.items[index].stock = response.data.stock;
})
.catch(function(error) {
console.log(error)
});
},

Related

How do I compare and verify user input field to stored data BEFORE to sending form in ColdFusion

I’m updating a site for my brother who teaches training courses. He has a registration form on the site that collects name, age, address, etc. That information is sent to him through cfmail with a copy sent to the registrant. The registrants then mails in a check via snail-mail to complete the registration. (My brother does NOT want to use an online payment method.)
Included in the form is the course name, location and fee. He asked if it was possible to implement some sort of “Promo Code” to offer discounts to select users. I’ve added PromoCode and PromoCode_Fee columns in SQL and am able to make it all work throughout the process.
My problem is on the user end. If the user mistypes the PromoCode in the form, the app will obviously not register the discount, send the registration emails out with the standard fee, and store the registration info in the DB. The only way for the user to fix the PromoCode would be to re-register, which would re-send the emails and add a new registration to the DB.
What I’d like to do is verify that the user entered a valid PromoCode in the input field PRIOR to submitting the form by comparing what they typed to the PromoCode stored in the DB. If the PromoCode doesn’t match, add “Promo Code is invalid” under the input field.
I do this as a hobby, am self-taught and am not sure if it’s even possible (or good idea.) I imagine it’s not possible to do with ColdFusion and would most likely need some sort of JS or jQuery - both of which I’m pretty illiterate in.
I’ve been searching for hours to see if anyone had any similar questions, but have come up short. Any help or pointing me in the right direction would be greatly appreciated.
Here's the code I'm putting together:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="/scripts/jquery.validate.js"></script>
<script>
$(document).ready(function() {
var validator = $("#signupform").validate({
rules: {
firstname: "required",
lastname: "required",
username: {
required: true,
minlength: 2,
remote: "/components/promocodecomponent.cfc?method=validateUserName"
}
}
});
});
</script>
<div class="row justify-content-center">
<div class="col-10">
<form id="signupform" autocomplete="off" method="get" action="">
<table>
<tr>
<td class="label">
<label id="lfirstname" for="firstname">First Name</label>
</td>
<td class="field">
<input id="firstname" name="firstname" type="text" value="" maxlength="100">
</td>
<td class="status"></td>
</tr>
<tr>
<td class="label">
<label id="llastname" for="lastname">Last Name</label>
</td>
<td class="field">
<input id="lastname" name="lastname" type="text" value="" maxlength="100">
</td>
<td class="status"></td>
</tr>
<tr>
<td class="label">
<label id="lusername" for="username">Username</label>
</td>
<td class="field">
<input id="username" name="username" type="text" value="" maxlength="50">
</td>
<td class="status"></td>
</tr>
<tr>
<td class="field" colspan="2">
<input id="signupsubmit" name="signup" type="submit" value="Signup">
</td>
</tr>
</table>
</form>
</div>
</div>
Here's the component code:
component {
remote boolean function validateUserName(string username) returnFormat="json"{
if (arguments.username == "john") {
return true;
}
return "Username already in use";
}
}
Usually, you'd need to post some code that you've tried and isn't working. But you've outlined what you want and are just not sure where to start.
You can test just the value of the discount code before allowing the whole form to be submitted. You don't say how you're doing client-side form validation. I'd suggest using jQuery Validate to handle that, it's very easy to implement.
https://jqueryvalidation.org/documentation/
Go to the demo "The Remember The Milk sign-up form". This form checks the username field via Ajax before the rest of the form can be submitted.
var validator = $("#signupform").validate({
rules: {
firstname: "required",
lastname: "required",
username: {
required: true,
minlength: 2,
remote: "users.action"
}
}
});
If not using this framework, then just make an Ajax request when change is triggered on the discount code field and make sure there's a positive response from that before you allow the form to be submitted.
Also, you need to do server-side validation of the discount code when someone submits the form. If they've entered a discount code that is invalid, then don't allow the form to be processed until they enter a valid code or they clear the value from that field.
I do this as a hobby, am self-taught ... I imagine ... would most likely need some sort of JS or jQuery - both of which I’m pretty illiterate in.
The plugin is easy to use but there may be a slight learning curve depending on your jQuery and javascript skills. Bigger tasks are easier to tackle if you you break them into smaller ones and solve those one at a time. Start with the code snippet #AdrianJMoreno posted and delve into the documentation to understand what the code is doing and how:
validate() - a function that initializes the plugin for a specific form
rules - options that tells the plugin which form fields should be validated and how
remote - remote url to be called via ajax to validate a field's value. The remote endpoint should either return true/false or true/"some custom error message";
1. Build Sample Form
Once you have a sense of how the plugin works, move on to building a scaled down version of the Milk demo form using the code snippet.
JQuery and Validate libraries
<!-- modify js paths as needed -->
<script src="scripts/jquery-3.1.1.js"></script>
<script src="scripts/jquery.validate.min.js"></script>
Javascript initialization (so plugin validates the form)
<script>
$(document).ready(function() {
var validator = $("#signupform").validate({
rules: {
firstname: "required",
lastname: "required",
username: {
required: true,
minlength: 2,
remote: "users.action"
}
}
});
});
</script>
HTML form (only the fields in code snippet)
<form id="signupform" autocomplete="off" method="get" action="">
<table>
<tr>
<td class="label">
<label id="lfirstname" for="firstname">First Name</label>
</td>
<td class="field">
<input id="firstname" name="firstname" type="text" value="" maxlength="100">
</td>
<td class="status"></td>
</tr>
<tr>
<td class="label">
<label id="llastname" for="lastname">Last Name</label>
</td>
<td class="field">
<input id="lastname" name="lastname" type="text" value="" maxlength="100">
</td>
<td class="status"></td>
</tr>
<tr>
<td class="label">
<label id="lusername" for="username">Username</label>
</td>
<td class="field">
<input id="username" name="username" type="text" value="" maxlength="50">
</td>
<td class="status"></td>
</tr>
<tr>
<td class="label">
<label id="lsignupsubmit" for="signupsubmit">Signup</label>
</td>
<td class="field" colspan="2">
<input id="signupsubmit" name="signup" type="submit" value="Signup">
</td>
</tr>
</table>
</form>
2. Test (Sample Form)
Test out the form in a browser. Since all fields are required, leaving the fields blank and submitting should trigger error messages on submit
3. Create Remote URL
The live demo form uses a mocking library to simulate a remote ajax call. The mock url "users.action" must be replaced with a real url on your server. That url will point to a new component (or "CFC") you create. The component should contain a remote accessible method that validates a given username.
Keep things simple for the initial test. Have the method return true if the input equals a test value like "John" and false for everything else. Ultimately you'll replace that with real business logic, like a database lookup, but one step at a time.
YourComponentName.cfc
component {
remote boolean function validateUserName(string username) returnFormat="json"{
if (arguments.username == "john") {
return true;
}
return false;
}
}
4. Test (Remote URL)
To test a remote method in a browser, specify the path, name of the method to invoke, and any parameters that method expects. Verify the component returns the expected results. The result should be true for username=John and false for any other value.
Example url:
https://localhost/path/YourComponentName.cfc?method=validateUsername&username=john
Valid: UserName=John:
InValid: UserName=Bob:
5. Fix Remote URL
With the component working, update the javascript code to point to the new cfc. Omit the username parameter because the plugin will pass it to the ajax call automatically.
For example, if the component location on disk is:
c:\path\webroot\path\YourComponentName.cfc
Use the url:
/path/YourComponentName.cfc
JS Snippet:
...,
username: {
...,
remote: "/path/YourComponentName.cfc?method=validateUserName"
}
6. Test Form (.. are you sensing a theme?)
Test the final form again with both a valid and invalid usernames to confirm it works as expected.
Invalid usernames "Mike" or "Bob" should trigger an error
Valid username "John" should not trigger an error
Next Steps ...
Continue to expand the working example and learn more about the plugin features by adding some customization. The next steps are left as an exercise for the reader ...
Replace hard coded test logic in the cfc with a database lookup
Replace default error message "Please fix this field" with a more user friendly message
Change the appearance of valid and invalid fields using CSS

Delete multiple rows using Laravel and Vue Js

Am having a problem deleting multiple rows in Laravel and Vue Js. I am able to get the values of id as an array. When I click on delete button I get a status 200 but no record is deleted from the database. Here is my code:
In my table
<tr v-for="user in users.data" :key="user.id">
<td>{{user.id}}</td>
<td>{{user.userName}}</td>
<td><input type="checkbox" :value="user.id" v-model="checkedNames"></td>
<button class="btn btn-warning" #click=" deleteAllUser()">Delete
Selected</button>
</td>
</tr>
Vue Js
<script>
export default {
data(){
return{
checkedNames:[],
Function
deleteAllUser(){
this.form.post('api/deletehotspotusers/',{id:this.checkedNames}).then(()=>{
self.loadHotspotUsers();
}).catch(()=> {
Swal.fire("Failed!", "There was something wrong.", "warning");
});
}
}
In my controller
public function deleteAll(Request $request){
if($request->id){
foreach($request->id as $id){
HotspotUsers::destroy($id);
}
}
My route
Route::post('/deletehotspotusers', 'HotspotUsersController#deleteAll');
To delete a model record you need to call the delete method. You can try the below in the controller method
//import use statement at the top of the class
//use Illuminate\Support\Arr;
public function deleteAll(Request $request){
if($request->id){
HotspotUsers::whereIn('id', Arr::wrap($request->id))->delete();
}
}
In Vue, input type checkbox, v-model uses checked property and change event, so v-model will record either true or false based on the checked state. In order to populate the id with user.id, you need to make use of change event
<tr v-for="user in users.data" :key="user.id">
<td>{{user.id}}</td>
<td>{{user.userName}}</td>
<td>
<input type="checkbox" :value="user.id" #change="onChecked(user.id)">
</td>
<td>
<button class="btn btn-warning" #click=" deleteAllUser()">
Delete Selected
</button>
</td>
</tr>
And in the script section in methods
onChecked(id){
if(!this.names.includes(id)){
this.names.push(id)
} else {
this.names.splice(this.names.indexOf(id),1)
}
}
I am not into vue.js.
If your front-end works good, then here is the laravel code.
Make sure that $request->id is receiving the value you expected.
You can use like
Model::destroy([array of primary keys])
If your Model's primary key is id, then you can specify array of ids like [1,2,3,4].
But before make sure the input values by using logger($request->id).
Thank you

when hit enter go to next element vuejs2

i have function on click vuejs2
this is the function
#change='units(chosed_item.id,$event)'
and this is the code for this function to send the id and put result inside array
units:function(item_id,$event){
var unit_id = event.target.value;
$.ajax({
type:'POST',
url: path+'unit_search',
data: {unit_id,item_id},
success:(data) => {
this.voucher_items.push({
id:data['id'],
item_desc_ar:data['item_desc_ar'],
item_unit_name:data['item_unit_name'],
item_smallest_unit_cost:data['item_smallest_unit_cost'],
item_smallest_unit:data['item_smallest_unit'],
item_smallest_unit_selling_price:data['item_smallest_unit_selling_price'],
item_discount_value:data['item_discount_value'],
item_tax_value:data['item_tax_value'],
});
this.chosed_items = [];
}
});
},
and i loop the voucher_items in loop
like this
<tr v-for="voucher_item , key in voucher_items">
<td>
<input name='items_quantity_coast[]' type='text' class='form-control' />
</td>
<td>
<input type='number' name='items_quantity_quantity[]' min='1' class='form-control' v-model='voucher_item.quantity' required />
</td>
<td>
<input type='number' name='items_quantity_discount[]' min='1' class='form-control' v-model='voucher_item.item_discount_value_input' min='1' max=''/>
</td>
</tr>
how can i make the input focus go to last input in voucher_items like when i click unit function do the code above and focus the input in
<input type='number' name='items_quantity_discount[]' min='1' class='form-control' v-model='voucher_item.item_discount_value_input' min='1' max=''/>
thanks
You can use a custom directive ..
In your component, add a directives option ..
directives: {
focus: {
inserted(el) {
el.focus()
}
}
}
Use your new v-focusdirective to focus on the desired element ..
This will focus on the last input on your last row. If you want finer control on which element to focus you can create a custom directive and use it on an upper level element (the table element for example), then use normal DOM traversing techniques(firtElementChild, lastElementChild et al.) to target specific elements. The process will be the same.

Angular 2 doesn't update my view after I add or edit item

I've finally made my app in angular 2. Everything is solved, except one thing. When I add item into my table or edited it, I can't see the change until I refresh page or click for example next page button (I have implemented pagination). I included:
<script src="node_modules/systemjs/dist/system-polyfills.js"></script>
<script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
in this order. My method for adding item is very simple:
addDepartment(item){
this._departmentService.addDepartment(item)
.subscribe(departments => this.department = departments.json());
this.getAll();}
Whhen I add item, and put breakpoint on get method, It is called correctly and I get right information from my DB, but I don't know why view isn't refreshed then. Do you have any idea why is it happened? Thanks for suggestions!
EDIT: department is just department: Department, where Department is interface with properties (departmentNo, departmentName, departmentLocation). The view for adding item looks like:
<form [ngFormModel]="myForm"
(ngSubmit)="addDepartment(newItem); showAddView=false" [hidden]="!showAddView" align="center">
<div>
<label for="editAbrv">Department name:</label><br>
<input type="text" [(ngModel)]="newItem.departmentName" [ngFormControl]="myForm.controls['departmentName']" >
<div *ngIf="myForm.controls['departmentName'].hasError('required')" class="ui error message"><b style="color:red;">Name is required</b></div>
</div>
<br/>
<div>
<label for="editAbrv">Department Location:</label><br>
<input type="text" [(ngModel)]="newItem.departmentLocation" [ngFormControl]="myForm.controls['departmentLocation']" >
<div *ngIf="myForm.controls['departmentLocation'].hasError('required')" class="ui error message"><b style="color:red;">Location is required</b></div>
</div>
<br/>
<div>
<button type="submit" [disabled]="!myForm.valid" class="ui button">Add item</button>
<button><a href="javascript:void(0);" (click)="showHide($event)" >
Cancel
</a></button>
</div>
</form>
and my department table is:
<table align="center">
<thead>
<tr>
<td>#</td>
<td><strong>Department</strong></td>
<td><strong>Department Location</strong></td>
<td><strong>Edit</strong></td>
<td><strong>Delete</strong></td>
</tr>
</thead>
<tbody>
<tr *ngFor="#department of departments | searchString:filter.value ; #i = index">
<td>{{i + 1}}.</td>
<td> {{department.departmentName}}</td>
<td>{{department.departmentLocation}}</td>
<td>
<button class="btnEdit" (click)="showEdit(department)">Edit</button>
</td>
<td>
<button class="btnDelete" (click)="deleteDepartment(department)" >Delete</button>
</td>
</tr>
</tbody>
</table>
With this code, you don't wait for the response of the addDepartment request and execute the getAll request directly.
addDepartment(item){
this._departmentService.addDepartment(item)
.subscribe(departments => this.department = departments.json());
this.getAll();
}
You should move the call to getAll within the callback registered in subscribe. At this moment, the addDepartment is actually done and you can reload the list...
The code could be refactored like this (it's a guess since I haven't the content of addDepartment and getAll methods):
addDepartment(item){
this._departmentService.addDepartment(item)
.subscribe(addedDepartment => {
this.department = this.getAll();
});
}
This issue occurs because of the way you're using departmant and how change detection works. When you use *ngFor="#department of departments", angular change detection looks for a object reference on departments array. When you update/change one of the items in this array object reference to the array itself doesn't change, so angular doesn't run change detection.
You have few options:
1) change reference of the array by replacing it with new array with updated values
2) tell angular explicitly to run change detection (which I think is easier in your case):
constructor(private _cdRef: ChangeDetectorRef) {...}
addDepartment(item){
this._departmentService.addDepartment(item)
.subscribe(departments => this.department = departments.json());
this.getAll();
this._cdRef.markForCheck();
}

Can I access the same controller multiple times in one view without changing the view?

I am using Spring MVC. I have a view that dynamically populates 2 dropdown lists based on queries called from the controller. I want to dynamically run a query based on the first dropdown selection to change the second dropdown, which means access the controller again (I think). Can I access the controller multiple times from the same view without changing the view? So for example, say starting out the first dropdown was a list of US States and the second started out as a list of all US cities, if I selected NC from the first list I would want to change the second list to include only NC cities.
Here is an example of the first dropdown:
<select name = "states" onChange = "populateCityList(this.options[this.selectedIndex].value)">
<option value ="*">All States</option>
<c:forEach items="${states}" var ="state">
<option value ="${state}">${state}</option>
Pretty straightforward, but I don't really know where to go from there. I have it calling a Javascript function within the current view right now, but I don't know if that is correct or what to even do within that function.
The magic word is AJAX.
Your JavaScript function needs to make an AJAX request to your controller, which should ideally return a JSON data structure containing the values for the second drop down. Your JS function should then have a callback that catches the JSON from your controller and populates the drop down HTML by manipulating the DOM. JQuery is the way to go. There are lots of examples on the web, just search for it.
Hi #user2033734 you can do something like this:
JQuery code
$(document).ready(function() {
$("#id1").change(function () {
position = $(this).attr("name");
val = $(this).val()
if((position == 'id1') && (val == 0)) {
$("#id2").html('<option value="0" selected="selected">Select...</option>')
} else {
$("#id2").html('<option selected="selected" value="0">Loading...</option>')
var id = $("#id1").find(':selected').val()
$("#id2").load('controllerMethod?yourVariable=' + id, function(response, status, xhr) {
if(status == "error") {
alert("No can getting Data. \nPlease, Try to late");
}
})
}
})
})
And JSP within
<table style="width: 100%;">
<tr>
<td width="40%"><form:label path="">Data 1: </form:label></td>
<td width="60%">
<form:select path="" cssClass="" id="id1">
<form:option value="" label="Select..." />
<form:options items="${yourList1FromController}" itemValue="id1" itemLabel="nameLabel1" />
</form:select>
</td>
</tr>
<tr>
<td width="40%"><form:label path="">Data 2: </form:label></td>
<td width="60%">
<form:select path="" cssClass="" id="id2">
<form:option value="" label="Select..." />
<form:options items="${yourList2FromController}" itemValue="id2" itemLabel="nameLabel2" />
</form:select>
</td>
</tr>
</table>
I hope help you :)
One solution would be to move some of the data gathering out into a service, so your main controller could use the service to gather the data before sending to the view.

Resources