Reputation: 319
My validate line function below appears to only work on the second time of clicking add. So if the amount is 500 and I set the discount to 100, on hitting the add button it should be 400. It doesn't work. If I click the line again, the it seems the discount applies twice - amount becomes 300. How do I resolve this?
function OnValidateLine(type, name) {
var count = nlapiGetLineItemCount('expense')
var total = nlapiGetFieldValue('usertotal')
for (var x = 1; x <= count; x++) {
var amount = nlapiGetCurrentLineItemValue('expense', 'amount');
var discount = nlapiGetCurrentLineItemValue('expense', 'custcolptc_discount');
if (discount) {
nlapiSetCurrentLineItemValue('expense', 'amount', amount - discount)
}
return true;
}
return true;
}
Upvotes: 0
Views: 716
Reputation: 15367
You are not actually doing anything with your loop.
Also the way you are going about this is fraught with issues.
You should probably do this in the recalc event rather than a line validation event.
If I were doing this I'd tend manage a 'synthetic' expense line that is the total of calculated discounts. The way you are currently doing this if someone changes the expense description you'll end up with the discount applied twice. If you use a discount line then you'll just total up the discounts and add or update the discount line.
Typically for a Client script you would need to advance the pointer for each line you are looking at. In the untested example below the 'id field?' would be memo or account columns (you'll have to set the account anyway):
var totalDiscount = 0;
var discountExpenseAt = 0;
for(var i = nlapiGetLineItemCount('expense'); i> 0; i--){
if(nlapiGetLineItemValue('expense', 'id field?', i) == 'discount identifier') {
discountExpenseAt = i;
continue;
}
totalDiscount += parseFloat(nlapiGetLineItemValue('expense', 'custcolptc_discount', i)) ||0;
}
if(totalDiscount) {
if(discountExpenseAt){
nlapiSelectCurrentLineItem('expense', discountExpenseAt);
nlapiSetCurrentLineItemValue('expense', 'amount', totalDiscount.toFixed(2));
nlapiSetCurrentLineItemValue('expense', 'id field?', 'discount identifier');
nlapiCommitCurrentLineItem('expense');
}
Upvotes: 2