May 19, 2011
by ashishdeshpande
I recently helped a customer create a simple Order form that calculates Subtotals for several line items and a Grand Total. The number of line items is variable since the user may order one or more items.
You can try an example form by clicking here.
It’s a common enough use case yet has some complexities that are easily handled by frevvo. First, you have to create a line item which repeats. In frevvo, simply create a Section for your Line Item, and layout the controls (in the example above, there’s a Drop down named Item for the items, a Money control named P for price, a Quantity control named Q for quantity, and a Money control named S for the subtotal) on a single line using panels. If you aren’t familiar with laying out controls, see this blog post. It contains a short video that shows you how.
Then, you have to create some rules. The first one auto-fills the Price based on the Item chosen. It looks like this:
for (var i = 0; i < Item.value.length; i++) {
if (Item[i].value == '1000')
P[i].value = 12.95;
else if (Item[i].value == '1001')
P[i].value = 13.65;
// etc. deleted for brevity
else
P[i].value = null;
}
The Items all have codes 1000, 1001 etc. and when a particular item is chosen, the corresponding price is filled in by the rule above. In practice, you may get Items and Prices dynamically from a database. There’s a whole Tutorial on just that topic if you’re interested.
Now that we have our Prices, we need to compute a Subtotal when the user enters a Quantity. That rule looks like this:
for (var i = 0; i < S.value.length; i++) {
if (Q[i].value > 0) {
S[i].value = Q[i].value * P[i].value;
} else {
S[i].value = 0;
}
Finally, we want to compute a Grand Total, which is the sum of all the Subtotals.
var tot = 0;
for (var i = 0; i < S.value.length; i++) {
tot = tot + S[i].value;
}
T.value = tot;
Finally, we want to recompute the Grand Total if a line item is removed by the user.
if (ORepeat.itemRemoved) {
var tot = 0;
for (var i = 0; i < S.value.length; i++) {
tot = tot + S[i].value;
}
T.value = tot;
}
That’s all there is to it. Try the example form and let us know what you think or if you want to see other examples.