add an item to a sales order in Netsuite suitescript - javascript

I'm trying to figure out the code behind looking at a new Sales Order that has an item called "Repair" and add a second item called "Repair Cost" before User submit. I'm a bit lost and I welcome any help that can be given. I would like this script to be in Javascript and I will attach it to the Sales Order form in Netsuite to run.

Here is one sample solution:
We will still assume that the items internal ids are Repair = 100 and Repair Cost = 200
function recalc(type)
{
if(type == 'item')
{
var itemId = nlapiGetCurrentLineItemValue('item', 'item'); //Get the Item ID
if(itemId == 100) //Repair Cost
{
//Insert item
nlapiSelectNewLineItem('item');
nlapiSetCurrentLineItemValue('item', 'item', 200); //Repair Cost
nlapiSetCurrentLineItemValue('item', 'quantity', 1);
nlapiSetCurrentLineItemValue('item', 'amount', '0.00');
nlapiCommitLineItem('item');
}
}
return true;
}
Deploy this as client-side code and make sure that the function is Recalc.
To learn more about client side script: https://system.na1.netsuite.com/help/helpcenter/en_US/Output/Help/SuiteFlex/SuiteScript/SSScriptTypes_ClientScripts.html#1016773

First thing you need to do is to get the internal id of the item "Repair" and "Repair Cost".
In this example, let's assumed that the internal id of Repair = 100 and Repair Cost = 200
Here is th code:
function afterSubmit(type)
{
if(type == 'create' || type == 'edit')
{
var record = nlapiLoadRecord(nlapiGetRecordType(), nlapiGetRecordId()); //Load the record
//Loop to all sublist item
var count = record.getLineItemCount('item');
for(var i = 1; i <= count; i++)
{
var item = record.getLineItemValue('item', 'item', i); //This will return the internal id of the item
if(item == 100) //Item is equal to 100; insert one item
{
record.insertLineItem('item', i);
record.setLineItemValue('item', 'item', i, 200); //Repair Cost internal id
record.setLineItemValue('item', 'quantity', i, 1); //You should put some quantity; depending on your account setup all required fields should be set here.
}
}
//Submit the changes
nlapiSubmitRecord(record, true);
}
}
To understand the suitescript API and the fields exposed to sales order check on this Netsuite helpguide:
https://system.netsuite.com/help/helpcenter/en_US/RecordsBrowser/2012_2/Records/salesorder.html

Related

How to read a sublist data in netsuite?

I am new to suitescript. Openly telling I hardly wrote two scripts by seeing other scripts which are little bit easy.
My question is how can read a data from sublist and call other form.
Here is my requirement.
I want to read the item values data highlighted in yellow color
When I read that particular item in a variable I want to call the assemblyitem form in netsuite and get one value.
//Code
function userEventBeforeLoad(type, form, request)
{
nlapiLogExecution('DEBUG', 'This event is occured while ', type);
if(type == 'create' || type == 'copy' || type == 'edit')
{
var recType = nlapiGetRecordType(); //Gets the RecordType
nlapiLogExecution('DEBUG', 'recType', recType);
//
if(recType == 'itemreceipt')
{
nlapiLogExecution('DEBUG', 'The following form is called ',recType);
//var itemfield = nlapiGetFieldValue('item')
//nlapiLogExecution('DEBUG','This value is = ',itemfield);
var formname = nlapiLoadRecord('itemreceipt',itemfield);
nlapiLogExecution('DEBUG','This value is = ',formname);
}
}
}
How can I proceed further?
I want to read that checkbox field value in the following image when i get the item value from above
I recommend looking at the "Sublist APIs" page in NetSuite's Help; it should describe many of the methods you'll be working with.
In particular you'll want to look at nlobjRecord.getLineItemValue().
Here's a video copmaring how to work with sublists in 1.0 versus 2.0: https://www.youtube.com/watch?v=n05OiKYDxhI
I have tried for my end and got succeed. Here is the answer.
function userEventBeforeLoad(type, form, request){
if(type=='copy'|| type =='edit' || type=='create'){
var recType = nlapiGetRecordType(); //Gets the RecordType
nlapiLogExecution('DEBUG', 'recType', recType);
//
if(recType == 'itemreceipt')
{
nlapiLogExecution('DEBUG', 'The following form is called ',recType);
var itemcount = nlapiGetLineItemCount('item');
nlapiLogExecution('DEBUG','This value is = ',+itemcount);
for(var i=1;i<=itemcount;i++)
{
var itemvalue = nlapiGetLineItemValue('item','itemkey',i);
nlapiLogExecution('DEBUG','LineItemInternalID = ',itemvalue);
var itemrecord = nlapiLoadRecord('assemblyitem', itemvalue);
nlapiLogExecution('DEBUG','BOM= ',itemrecord);
if(itemrecord == null){
var itemrecord = nlapiLoadRecord('inventoryitem', itemvalue);
nlapiLogExecution('DEBUG','BOM= ',itemrecord);
}
var value = itemrecord.getFieldValue('custitem_mf_approved_for_dock_to_stock');
nlapiLogExecution('DEBUG',"Checkboxvalue = ",value);
if(value == 'F'){
nlapiSetLineItemValue('item','location',i,9);
nlapiSetLineItemDisabled ('item','location',false,i );
}
else{
nlapiSetLineItemValue('item','location',i,1);
nlapiSetLineItemDisabled ('item','location',true,i );
}
}
}
}
}

How validation works

I´m supporting API where I need to update validation into javascript method:
function AddCategory() {
var category = $("#category");
var subCategory = $("#subcategory");
if (category.val().length > 0 && subCategory.val().length > 0) {
var grid = $("#lstCategory").data("kendoGrid");
var listGrid = $("#lstCategory").data().kendoGrid.dataSource.data();
var dataS = grid.dataSource;
if (!FindObjectInList(listGrid, "idSubcategory", subCategory.val())) {
dataS.add({
idCategory: category.val(),
category: $("option:selected", category).text(),
idSubcategory: subCategory.val(),
subCategory: $("option:selected", subCategory).text()
});
dataS.sync();
}
else {
InfoMessage("Category", "Selected subcategory cannot add again");
}
} else {
WarningMessage("Warning", "Select category and subcategory...");
}
}
I need to remove this validation:
InfoMessage("Category", "Selected subcategory cannot add again");
But I don´t understand how this method works, anyone can explain me it? Regards
How it works:
First, pass listGrid, idSubcategory and the value returned from subCategory.val() into FindObjectInList. If null is returned (the category does not exist) - then add the new category information passed in. Else, if the function returns true (the category already exists) then serve up the notification to the user via the InfoMessage function.
if (!FindObjectInList(listGrid, "idSubcategory", subCategory.val())) {
dataS.add({
idCategory: category.val(),
category: $("option:selected", category).text(),
idSubcategory: subCategory.val(),
subCategory: $("option:selected", subCategory).text()
});
dataS.sync();
}
else {
InfoMessage("Category", "Selected subcategory cannot add again");

How do I add Mark all / Unmark all button in inlineeditor type sublist netsuite

I am trying to add a Mark all/Unmark all button in sub-list which is a type of inline-editor sub-list. below I have added a code for list type sub-list which will not work on inline-editor sub-list. Can anyone help to find this?
function button1Func(type) {
if (type=='edit' || 'view')
{
var record = nlapiLoadRecord(nlapiGetRecordType(), nlapiGetRecordId());
var intCount = record.getLineItemCount('item');
var headrow = document.getElementById("item_headerrow");
var head = headrow.insertCell(0);
head.innerHTML ="Select";
for (var rep = 1; rep <= intCount; rep++)
{
var row = document.getElementById("item_row_"+rep);
var x = row.insertCell(0);
var newCheckbox = document.createElement("INPUT");
newCheckbox.setAttribute("type", "checkbox");
newCheckbox.setAttribute("id", "select_CheckBox"+rep);
x.appendChild(newCheckbox);
}
}
}
function button2Func(type) {
if (type=='edit' || 'view')
{
var record = nlapiLoadRecord(nlapiGetRecordType(), nlapiGetRecordId());
var intCount = record.getLineItemCount('item');
for (var rep = 1; rep <= intCount; rep++)
{
var repId = record.getLineItemValue('item', 'item', rep);
if(document.getElementById("select_CheckBox"+rep).checked==true){
makecopyfun(repId);
}
else
{
continue;
}
}
alert("Success");
}
}
function makecopyfun(repId){
var record = nlapiLoadRecord(nlapiGetRecordType(), nlapiGetRecordId());
var intCount = record.getLineItemCount('item');
record.insertLineItem('item',intCount + 1);
alert (intCount);
record.setCurrentLineItemValue('item','item',repId);
record.commitLineItem('item');
var id = nlapiSubmitRecord(record, true);
}
Not sure through the API because there's no record object, you could try using jQuery.
First write following code & create userEvent script and apply function name(initnoload) in beforeLoad Event.
Then Deploy that script on Quote.
function initonload(type, form, request) {
if (type=='edit' || type=='view') {
var list = form.getSubList("item");
list.addButton('custpage_markmark','Mark all','markall();'); //markall(); is function name from the client script
list.addButton('custpage_unmarkmark','Unmark all','unmarkall();'); //unmarkall(); is function name from client script
form.setScript('customscript_mark_all_item_quote'); // 'customscript_mark_all_item_quote' is the ID of script
}
}
Above code will add two buttons to Sublist and their action get executed in client script whose ScriptId we have Defined.
Now write the following code & create client script.(Note: Just save the client script, Don't specify any event function name and do not deploy it).
function markall() {
var count=nlapiGetLineItemCount('item'); //gets the count of lines
for(var i=1;i<=count;i++) {
nlapiSelectLineItem('item',i);
nlapiSetCurrentLineItemValue('item','custcol_checkbox_field','T',true,true); //'custcol_checkbox_field' is checkbox's field ID.
}
nlapiCommitLineItem('item');
}
function unmarkall() {
var count=nlapiGetLineItemCount('item');
for(var i=1;i<=count;i++) {
nlapiSelectLineItem('item',i);
nlapiSetCurrentLineItemValue('item','custcol_checkbox_field','F',true,true); //'custcol_checkbox_field' is checkbox's field ID.
}
nlapiCommitLineItem('item');
}
After saving the client script please paste it's ID in user event's form.setScript('Client script ID'). function
i hope this will help you out.
Please let me know if u face any difficulty.
Thank you.
I do came up with other idea as you can use the field which'll help you to mark/unmark all lines under sublist..you can add subtab to the form and under subtab you can add field and sublist. later you can apply script on that field which will help you to mark/unmark all sublist lines.
Here is the code...
form.addSubTab('custpage_tab', 'Main Tab');
form.addField('custpage_chkmark','checkbox','Mark/Unmark All',null,'custpage_tab');
form.addSubList('custpage_sublst','inlineeditor','SampleSubList','custpage_tab');

Netsuite Saved Search to Suitelet Sublist

I am trying to populate a sublist in a suitelet with data from a custom saved search that I have already created. My problem is that the sublist is only populating data from fields that correspond to the "type" of saved search I am doing. For example, in this instance the saved search is a "transaction" type search. If, for example, I want to reference a customer field withing the saved search, say "Name" and "Billing Address", this data will not populate the sublist in the suitelet. All other fields that are being referenced in the Transaction record itself populate the sublist fine. I was just wondering if anyone has ever run into the same issue, anyways here's the code I'm trying to implement.
var form,
sublist;
//GET
if (request.getMethod() == 'GET')
{
//create form
form = nlapiCreateForm('Test Custom Suitelet Form', false);
//create sublist to show results
sublist = form.addSubList('custpage_sublist_id', 'list', 'Item List');
//form buttons
form.addSubmitButton('Submit');
form.addResetButton('Reset');
// run existing saved search
var searchResults = nlapiSearchRecord('transaction','customsearchID');
var columns = searchResults[0].getAllColumns();
// Add the search column names to the sublist field
for ( var i=0; i< columns.length; i++ )
{
sublist.addField(columns[i].getName() ,'text', columns[i].getLabel() );
nlapiLogExecution('DEBUG', 'Column Label',columns[i].getLabel());
}
//additional sublist fields
sublist.addMarkAllButtons();
sublist.addField('custfield_selected', 'checkbox', 'Selected');
sublist.setLineItemValues(searchResults)
response.writePage(form);
}
If you review the nlobjSublist docs you'll see that sublist.setLineItemValues can also take an array of hashes. What does work is:
function getJoinedName(col) {
var join = col.getJoin();
return join ? col.getName() + '__' + join : col.getName();
}
searchResults[0].getAllColumns().forEach(function(col) {
sublist.addField(getJoinedName(col), 'text', col.getLabel());
nlapiLogExecution('DEBUG', 'Column Label', col.getLabel());
});
var resolvedJoins = searchResults.map(function(sr) {
var ret = {
id: sr.getId()
};
sr.getAllColumns().forEach(function(col) {
ret[getJoinedName(col)] = sr.getText(col) || sr.getValue(col);
});
return ret;
});
sublist.setLineItemValues(resolvedJoins);

Calculating sum of order with changing price values in Javascript

I am trying to use Javascript to calculate sum of order in one big form. Each product has its own price, however, there are more prices tied with some products. Each product has it's own price, but if a customer orders bigger quantity of this product, the price will drop to a value that is specified in a database table.
To simplify, the shopping form for one item looks something like this.
<input name="id" value="'.$id.'" type="hidden">
<input name="price_'.$id.'" value="'.$price.'" type="hidden">
<input name="quantity_'.$id.'" type="text" onchange="calculateTotal()">
I have a table with the discounts: itemId, minimumQuantity, priceAfterDiscount. There can be more than one discounts connected with one item. The MySQL query works with LEFT JOIN of Items and Discounts tables.
calculateTotal() calculates the total of order after every input change.
What I would like to do, is to check if the quantity of certain product is greater than the value needed for the discounts and if so, I would like to change the value of the input with price from item's regular price to the discounted one. Then, calculateTotal() will use that price and update the total.
To do so, I think I can do something like adding more hidden inputs with values of all discounts. The function would check if there is a discount linked to every item and if so, it will check if the quantity is greater than requiredQuantity and if this condition is met, it will update the value of price hidden input. Please keep in mind that there can be multiple discounts connected to one item - the function should find the lowest price that meets requiredQuantity.
I am trying to do this - create the hidden inputs and somehow parse them in javascript, but I am just not able to figure this out. I tried my best to explain the problem, however, if my explanation is not sufficient, I will try to answer your questions regarding my issue.
I hope you are able and willing to help me. Thanks for help in advance.
Perhaps something like this example.
CSS
.itemLabel, .currentPrice, .subTotal {
display: inline-block;
width: 40px;
}
#myTotal {
border:2px solid red;
}
HTML
<fieldset id="myInputs"></fieldset>
<div id="myTotal"></div>
Javascript
var myInputs = document.getElementById('myInputs'),
myTotal = document.getElementById('myTotal'),
order = {
total: 0
},
items = {
foo: {
1: 0.5,
100: 0.25
},
bar: {
1: 1,
100: 0.5
}
},
totalNode;
function calculateTotal() {
var newTotalNode;
Object.keys(order).filter(function (key) {
return key !== 'total';
}).reduce(function (acc, key) {
order.total = acc + order[key].subTotal;
return order.total;
}, 0);
newTotalNode = document.createTextNode(order.total.toFixed(2));
if (totalNode) {
myTotal.replaceChild(newTotalNode, totalNode);
totalNode = newTotalNode;
} else {
totalNode = myTotal.appendChild(newTotalNode);
}
console.log(JSON.stringify(order));
}
calculateTotal();
Object.keys(items).forEach(function (key) {
var div = document.createElement('div'),
label = document.createElement('label'),
price = document.createElement('span'),
input = document.createElement('input'),
subtotal = document.createElement('span'),
priceNode,
subTotalNode;
order[key] = {
quantity: 0,
subTotal: 0,
price: items[key]['1']
};
priceNode = document.createTextNode(order[key].price.toFixed(2));
subTotalNode = document.createTextNode(order[key].subTotal.toFixed(2));
label.className = 'itemLabel';
label.setAttribute("for", key);
label.appendChild(document.createTextNode(key));
price.className = 'currentPrice';
price.id = key + 'CurrentPrice';
price.appendChild(priceNode);
input.id = key;
input.name = 'myFormGroup';
input.type = 'text';
input.addEventListener('change', (function (key, order, priceNode, subTotalNode) {
return function () {
var value = +(this.value),
newPriceNode,
newSubTotalNode;
Object.keys(items[key]).sort(function (a, b) {
return b - a;
}).some(function (quantity) {
if (value >= quantity) {
order.price = items[key][quantity];
newPriceNode = document.createTextNode(order.price.toFixed(2));
priceNode.parentNode.replaceChild(newPriceNode, priceNode);
priceNode = newPriceNode;
return true;
}
return false;
});
order.subTotal = order.price * value;
newSubTotalNode = document.createTextNode(order.subTotal.toFixed(2));
subTotalNode.parentNode.replaceChild(newSubTotalNode, subTotalNode);
subTotalNode = newSubTotalNode;
calculateTotal();
};
}(key, order[key], priceNode, subTotalNode)), false);
subtotal.className = 'subTotal';
subtotal.id = key + 'SubTotal';
subtotal.appendChild(subTotalNode);
div.appendChild(label);
div.appendChild(price);
div.appendChild(input);
div.appendChild(subtotal);
myInputs.appendChild(div);
});
On jsFiddle

Categories

Resources