Summary:
Users should be choosing their desired products in a form environment. Every product has a core price and multiple additional options available which change the price when selected.
Products and options are shown in two SELECT fields which are getting populated like this:
$scope.products = [
{
name:'Product A',
cost:5,
options: [{name:"Option 1", value:10}]
},
{
name:'Product B',
cost:10,
options: [{name:"Option 1", value:10},{name:"Option 2", value:15}]
}
];
$scope.cart = {
items: [{
qty: 1,
}]
};
and
<tr ng:repeat="item in cart.items">
<td>
<div class="type-select">
<select ng-model="item.product" ng-options="p.name for p in products"></select>
</div>
</td>
<td>
<div class="type-select">
<select ng-model="item.option" ng-options="o for o in item.product.options.name" ng- disabled="!checked">
</div>
</td>
<td>
<input ng:model="item.qty" value="1" size="4" ng:required="" ng:validate="integer" class="ng-pristine ng-valid ng-valid-required input-mini">
</td>
<td>
{{calculate()}}
</td>
</tr>
The options select stays empty. Why?
How can i calculate this the angular way? (There will be multiple lines of product possible)
You might find my example app airquotes a good reference: https://github.com/JohnMunsch/airquotes
It's an AngularJS app I wrote for a t-shirt site and it demonstrates generating quotes on the fly given a set of different values the user may set that can affect the price (such as darker colors having a surcharge because more ink has to be used when screen printing them and xxl shirts have a price premium).
It sounds like it's a good match for the kind of thing you're trying to build here.
<select ng-model="item.product" ng-options="p as p.name for p in products">
</select>
...
<select ng-model="item.option" ng-options="o as o.name for o in
item.product.options" ng-disabled="!checked"></select>
...
<td>
{{calculate(item)}}
</td>
Controller:
$scope.calculate = function(item){
/* return the calculated cost */
}
Related
I am trying to make a form which shows all products from a group in a list. They can be given a quantity and added to a quote. Which is then stored in the database.
None of the automagical form options are working for me. So I've made each row showing information for a given product with the Quantity box and an add item button it's own form. But the loop which makes each form is doing something strange.
Controller:
products = db(db.product.group_id == productgroupnumber).select()
forms=[]
for product in products:
form = FORM(TABLE(TR(TD(product.productname),
TD((product.purchasecost or 0)),
TD((product.monthlycost or 0)),
TD(INPUT(_type='number', _name='quantity')),
TD(INPUT(_type='submit', _value=T('Add to Offer')))
)
)
)
forms.append(form)
session.quotedproducts = []
if form.accepts(request, session, keepvalues = True):
product = db(db.product.id == product_id).select().first()
offeritem = [product_id, request.vars.quantity, product.purchasecost, product.monthlycost]
session.quotedproducts.append(offeritem)
response.flash = T("Item added to offer")`
For 2 rows. The View has the below 2 forms, with only one hidden div with the formkey and formname. So I can't name the forms in order to process them properly:
<form action="#" enctype="multipart/form-data" method="post">
<table>
<tr>
<td>Block of 10 Phone Numbers</td>
<td>19.0</td>
<td>0</td>
<td><input name="quantity" type="number" /></td>
<td><input type="submit" value="Add to Offer" /></td>
</tr>
</table>
</form>
<form action="#" enctype="multipart/form-data" method="post">
<table>
<tr>
<td>100 Block of Phone Numbers</td>
<td>149.0</td>
<td>0</td>
<td><input name="quantity" type="number" /></td>
<td><input type="submit" value="Add to Offer" /></td>
</tr>
</table>
<!--Why is there only one of these??-->
<div style="display:none;">
<input name="_formkey" type="hidden" value="b99bea37-f107-47f0-9b1b-9033c15e1193" />
<input name="_formname" type="hidden" value="default" />
</div>
</form>
How do I give the forms individual names (preferably product.id)?
I tried adding the formname argument:
form.accepts(request, session, formname=product.id)
But this only names one form and the other is still named 'Default'.
In your code, you create multiple forms in the for loop, but after exiting the loop, you call form.accepts(). At that point, the value of form is the last form created in the loop, so only that form is processed.
Note, when a form is initially created, the form.accepts (or the preferred form.process) method adds the _formname and _formkey hidden fields to the form (these are used for CSRF protection). When that same method is called after form submission, it additionally handles form validation. So, given your workflow, you must process all the forms both at creation and submission. Maybe something like this:
products = db(db.product.group_id == productgroupnumber).select()
forms = []
for product in products:
quantity_name = 'quantity_%s' % product.id
form = FORM(TABLE(TR(TD(product.productname),
TD((product.purchasecost or 0)),
TD((product.monthlycost or 0)),
TD(INPUT(_type='number', _name=quantity_name)),
TD(INPUT(_type='submit', _value=T('Add to Offer')))
)
)
)
if form.process(formname=product.id, keepvalues=True).accepted:
offeritem = [product.id, form.vars[quantity_name],
product.purchasecost, product.monthlycost]
session.quotedproducts.append(offeritem)
response.flash = T("Item added to offer")
forms.append(form)
Basically I want to create a dynamic form with nested objects like the picture below:
Pay offs are in an array on the model
We should be able to add/remove pay offs as needed.
The form should sync underlying form controls and model
The number of pay offs is arbitrary and should be loaded into the form from the model
There are no working examples that I could find as how to do this in Angular 2, although this was really easy to do in Angular 1.
Below is my original question, I've since updated it for clarification (see above):
First I just wanted to point out that I'm aware that a new version of Angular 2 rc.2 has just been released a few days ago. So the code for creating a dynamic, nested form may have changed some but there's not enough documentation to figure this out.
In the latest version(s) of Angular 2 (I'm currently using rc.1 but planning to update to rc.2) I need to create a form like this (pseudo-code of view):
<form [ngFormModel]="form" (ngSubmit)="onSubmit()">
<input type="text" ngControl="name">
<div *ngFor="let expense for expenses; let i = index;" control-group="expenses">
<input type="text" ngControl="expense.amount" [(ngModel)]="myModel.expenses[i].amount">
<input type="checkbox" ngControl="expense.final" [(ngModel)]="myModel.expenses[i].final">
</div>
<a class="button" (click)="addExpenseControl()">Add</a>
<a class="button" (click)="deleteExpenseControl()">Delete</a>
</form>
So the pseudo-code above won't work but to be honest because of lack of documentation I can't figure out how to wire something like this up. There's a few tutorials about nested ControlGroup but this won't fit the case here since we need to be able to dynamically add and remove control groups, and also I need to be able to sync them with a model.
I found this plunkr here provided by Angular team which allows adding of Controls to a form--but this is not adding/removing a ControlGroup, rather it's using ControlArray and I'm not sure if that applies here?
I'm very familiar with using the newer model-based Angular 2 forms however I'm grasping for resources in order to properly nest them (dynamically!), and tie this nested data into the main form model. How would I refer to nested controls in the view? Is the pseudo-code above even close? I'd post code from my controller but honestly I wouldn't know where to start when it comes to the nested expenses (ControlGroup ??) above...
I had to figure this out on my own because it seems that forms are still changing in Angular 2 and I've not seen any other examples similar to this (although it seems like a very common use-case).
Here is a plunkr of working example using Angular2 RC3.
I am using updated Angular 2 form code from this document.
app.component.ts (contains the form):
import { Component } from '#angular/core';
import {REACTIVE_FORM_DIRECTIVES, FormControl, FormGroup, FormArray} from '#angular/forms';
#Component({
selector: 'my-app',
templateUrl: 'app/app.html',
directives: [REACTIVE_FORM_DIRECTIVES],
providers: []
})
export class AppComponent {
form: FormGroup;
myModel:any;
constructor() {
// initializing a model for the form to keep in sync with.
// usually you'd grab this from a backend API
this.myModel = {
name: "Joanna Jedrzejczyk",
payOffs: [
{amount: 111.11, date: "Jan 1, 2016", final: false},
{amount: 222.22, date: "Jan 2, 2016", final: true}
]
}
// initialize form with empty FormArray for payOffs
this.form = new FormGroup({
name: new FormControl(''),
payOffs: new FormArray([])
});
// now we manually use the model and push a FormGroup into the form's FormArray for each PayOff
this.myModel.payOffs.forEach(
(po) =>
this.form.controls.payOffs.push(this.createPayOffFormGroup(po))
);
}
createPayOffFormGroup(payOffObj) {
console.log("payOffObj", payOffObj);
return new FormGroup({
amount: new FormControl(payOffObj.amount),
date: new FormControl(payOffObj.date),
final: new FormControl(payOffObj.final)
});
}
addPayOff(event) {
event.preventDefault(); // ensure this button doesn't try to submit the form
var emptyPayOff = {amount: null, date: null, final: false};
// add pay off to both the model and to form controls because I don't think Angular has any way to do this automagically yet
this.myModel.payOffs.push(emptyPayOff);
this.form.controls.payOffs.push(this.createPayOffFormGroup(emptyPayOff));
console.log("Added New Pay Off", this.form.controls.payOffs)
}
deletePayOff(index:number) {
// delete payoff from both the model and the FormArray
this.myModel.payOffs.splice(index, 1);
this.form.controls.payOffs.removeAt(index);
}
}
Notice above that I manually push new FormGroup objects into the form.controls.payOffs array, which is a FormArray object.
app.html (contains form html):
<form (ngSubmit)="onSubmit()" [formGroup]="form">
<label>Name</label>
<input type="text" formControlName="name" [(ngModel)]="myModel.name" placeholder="Name">
<p>Pay Offs</p>
<table class="simple-table">
<tr>
<th>Amount</th>
<th>Date</th>
<th>Final?</th>
<th></th>
</tr>
<tbody>
<tr *ngFor="let po of form.find('payOffs').controls; let i = index">
<td>
<input type="text" size=10 [formControl]="po.controls.amount" [(ngModel)]="myModel.payOffs[i].amount">
</td>
<td>
<input type="text" [formControl]="po.controls.date" [(ngModel)]="myModel.payOffs[i].date">
</td>
<td>
<input type="checkbox" [formControl]="po.controls.final" [(ngModel)]="myModel.payOffs[i].final">
</td>
<td>
<button (click)="deletePayOff(i)" style="color: white; background: rgba(255, 0, 0, .5)">x</button>
</td>
</tr>
</tbody>
<tr>
<td colspan="4" style="text-align: center; padding: .5em;">
<button (click)="addPayOff($event)" style="color: white; background: rgba(0, 150, 0, 1)">Add Pay Off</button>
</td>
</tr>
</table>
</form>
In the html form I link the form to the model on the inputs with statements like so:
... [formControl]="po.controls.amount" [(ngModel)]="myModel.payOffs[i].amount" ...
When I open my dropdown list, the width of list is greater than drop down box.
List width should same as drop down box.
You can use the following:
select, option { width: __; }
Keep in mind this may not work on Google Chrome. If you want a cross-browser solution you will probably have to use PHP to clip the String with SubStr. You can probably also use jQuery to set the length of the option text.
jQuery('#dropdown option').each(function() {
var optionText = this.text;
console.log(optionText);
var newOption = optionText.substring(0,19);
console.log(newOption);
jQuery(this).text(newOption + '..');
});
select, option {
width:150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<table>
<tr>
<td>
<select id="dropdown" style="width:150px;">
<option value="test">123123123123123123123123123123</option>
<option value="test2">123123123123123123123123123123</option>
<option value="test3">123123123123123123123123123123</option>
</select>
</td>
<td>
<input type="text">
</td>
</tr>
</table>
JsFiddle
You will have to set the substring values of
var newOption = optionText.substring(0,19);
By yourself though.
Try to set width of options same as select box
#SelectBoxid {
width:150px;
}
#SelectBoxid option{
width:150px;
}
I have a dropdownlist control and it's populated with a list of peoples names from a database. I want to enable a CheckBox control if the user selects a person in the list and disable the checkbox if they select BLANK (also an option in the list).
Here is a portion of my code...
<tr>
<td> <asp:Label ID="lblAssignedTo1" runat="server" Text="Assigned To:"></asp:Label></td>
<td><asp:DropDownList ID="ddlAssignedTo1" runat="server" AppendDataBoundItems="True" DataSourceID="dsAssignedTo" DataTextField="StaffName" DataValueField="StaffID"><asp:ListItem Text="" /></asp:DropDownList></td>
</tr>
<tr>
<td> <asp:Label ID="LabelEmail1" runat="server" Text="Send Email:"></asp:Label>
</td>
<td><asp:CheckBox ID="cbEmail1" runat="server" Checked="true" /></td>
</tr>
The checkbox is a trigger to send an email to the person selected from the list. I want it to default the checkbox to "enabled" if a person is selected from the list to make sure the program I am using is going to send an email later on.
I had a look at http://api.jquery.com/change/ for an example of this, but it's not using a checkbox control, so not sure if it would work. Sorry I am new to jScript.
Thanks in advance
A pure HTML and JavaScript approach would look something like this:
<select id="people">
<option value="">Select One</option>
<option value="person1">Person 1</option>
<option value="person2">Person 2</option>
<option value="person3">Person 3</option>
</select>
<input type="checkbox" name="sendemail" id="sendemail" disabled="disabled" />
$(document).ready(function() {
$('#people').change(function() {
if($(this).val() == '') {
$('#sendemail').attr('disabled', 'disabled');
}
else {
$('#sendemail').removeAttr('disabled');
}
});
});
http://jsfiddle.net/AEXpG/
In terms of your code, just grab the select list and checkbox ClientId and then apply the above jQuery code to them.
Below is a working example of a form. I need to display additional text field if user selects "Other" in drop down menu.
Unfortunately, I can't use example below because it requires Mootools but I use Jquery. Don't want to force users to download one more file (Mootools) just for one form.
Is there any way how to do this without Mootools? Thanks.
<form action='user_friends_manage.php' method='POST'>
<table cellpadding='0' cellspacing='0'>
<select name='friend_type' onChange="if(this.options[this.selectedIndex].value == 'other_friendtype') { $('other').style.display = 'block'; } else { $('other').style.display = 'none'; }">
<option></option>
<option value='1'>Friend</option>
<option value='2'>Family</option>
<option value='other_friendtype'>Other</option></select>
</td>
<td class='form2' style='display: none;' id='other'> <input type='text' class='text' name='friend_type_other' maxlength='50' /></td>
</tr></table></form>
try this:
*if(this.value=='other_friendtype') {document.getElementById('other').style.display='block'}*
in onchage event of select control.