I am trying to get nlapiGetOldRecord sublist values.
var record= nlapiGetOldRecord();
var testCount= record.getLineItemCount('recmachcustrecord_test');
The above linecount api is working and output the number of lines. But when i try to get its line item values it's giving following error "Cannot find function nlapiGetLineItemValue in object nlobjRecord.". My code.
for (var i = 1; i <= testCount; i++) {
var name= record.nlapiGetLineItemText('recmachcustrecord_test', 'custrecord_name', i);
var quantity = record.nlapiGetLineItemValue('recmachcustrecord_test', 'custrecord_qty', i);
nlapiLogExecution('DEBUG', 'Detail: ', name + ' and ' + quantity);
}
I have found the solution. Basically i was trying to get line item text/value using nlapiGetLineItemText api and which is not nlobjRecord api. so for sublist nlobjRecord getLineItemText api works.
var record= nlapiGetOldRecord();
var testCount= record.getLineItemCount('recmachcustrecord_test');
for (var i = 1; i <= testCount; i++) {
var name= record.getLineItemText('recmachcustrecord_test', 'custrecord_name', i);
var quantity = record.getLineItemValue('recmachcustrecord_test', 'custrecord_qty', i);
nlapiLogExecution('DEBUG', 'Detail: ', name + ' and ' + quantity);
}
Related
I am trying to set quantity field value in my sublist and quantity in my sublist subrecord(inventorydetail). When I try to .editLineItemSubrecord(), system throws an error:
"code\":\"CANNOT_EDIT_SUBRECORD\",\"details\":\"Cannot edit this subrecord, it is either in readonly state or dead state.\"
My code is as follows:
function updateRec(matRecArr, request, qtySetByUser, itemToFind) {
var tranOrderRec = nlapiLoadRecord('transferorder', matRecArr)
var count = tranOrderRec.getLineItemCount('item');
for (var i = 1; i < count + 1; i++) {
var indx = tranOrderRec.findLineItemValue('item', 'item', itemToFind);
if (indx > -1) {
tranOrderRec.selectLineItem('item', indx);
tranOrderRec.setCurrentLineItemValue('item', 'quantity', qtySetByUser);
var subrecord = tranOrderRec.editLineItemSubrecord('item', 'inventorydetail', 1);
subrecord.selectLineItem('inventoryassignment', 1);
subrecord.setCurrentLineItemValue('inventoryassignment', 'quantity', qtySetByUser);
subrecord.commitLineItem('inventoryassignment');
subrecord.commit();
}
tranOrderRec.commitLineItem('item');
tranOrderRec.commit();
}
nlapiSubmitRecord(tranOrderRec, true, true);
nlapiLogExecution('debug', 'MATERIAL REC. UPDATED!', tranOrderRec);
}
can anyone tell me the mistake I am doing?
Refer "Editing an Address Subrecord on an Existing Customer Record" in help or suite answers
I have a client script which is doing two things:
Calculate total weight of sales order on add of line
Copy tax code from custom field to native field
The script deploys correctly when adding lines in the UI from the sublist but when using the "add multiple" button and selecting and adding multiple lines at once, the script does not trigger. Here is the script as I have it written so far (I have 2 versions, one which is validateLine and one which is postSourcing).
Validate Line:
function calculateTotalWeight(type){
var lines = nlapiGetLineItemCount('item');
var totalWeight = 0 ;
for(var i=1; i< lines+1 ; i++){
var weight = nlapiGetLineItemValue('item', 'custcol_itemweight', i);
var quantity = nlapiGetLineItemValue('item', 'quantity', i);
var weightTimesQuantity = weight * quantity;
totalWeight = totalWeight + weightTimesQuantity ;
}
nlapiSetFieldValue('custbody_items_total_weight', totalWeight);
}
function validateLine(type){
var taxableCustomer = nlapiGetFieldValue('custbody_taxable');
if (taxableCustomer == 'T'){
var customTax = nlapiGetCurrentLineItemValue(type,'custcol_taxcode');
nlapiLogExecution('DEBUG', 'Custom Tax Value',customTax);
nlapiSetCurrentLineItemValue('item','taxcode',customTax,true,true);
}
return true;
}
postSourcing:
function calculateTotalWeight(type){
var lines = nlapiGetLineItemCount('item');
var totalWeight = 0 ;
for(var i=1; i< lines+1 ; i++){
var weight = nlapiGetLineItemValue('item', 'custcol_itemweight', i);
var quantity = nlapiGetLineItemValue('item', 'quantity', i);
var weightTimesQuantity = weight * quantity;
totalWeight = totalWeight + weightTimesQuantity ;
}
nlapiSetFieldValue('custbody_items_total_weight', totalWeight);
}
function postSourcing(type, name)
{
if(type === 'item' && name === 'item')
{
var custcol_taxcode = nlapiGetCurrentLineItemValue('item', 'custcol_taxcode');
var line = nlapiGetCurrentLineItemIndex(type);
{
nlapiSetCurrentLineItemValue('item', 'taxcode', custcol_taxcode);
}
}
}
How can I get this script to trigger with the add multiple button?
You’ll need to calculate the weight on the recalc event. The following is from a script that works as a scriptable cart/checkout script. It can be deployed in an eCommerce context or the UI context. (i.e. a deployed client script as opposed to a client script attached to a form)
Note:You should set up your tax codes so that they are assigned automatically. It is possible to script those but it's a fair pain to do.
the field custbody_sco_toggle is a checkbox field that keeps the script out of an infinite loop if your recalc scripts might change the order total.
var scriptableCart = (function(){
var cartScript = {};
var isUI = ('userinterface' == nlapiGetContext().getExecutionContext());
var isWeb = !isUI;
function tty(type, title, detail){
var haveWindow = typeof window != 'undefined';
if(isUI && haveWindow && window.console) window.console.log(title, detail);
else if(isWeb || !haveWindow) nlapiLogExecution(type, title, (detail || '') +' '+entranceId +' '+nlapiGetContext().getExecutionContext()); // this slows down the NS GUI
}
function calculateTotalWeight(type){...}
cartScript.recalc = function(type){
tty("DEBUG", "entered "+ type +" with toggle: "+ nlapiGetFieldValue('custbody_sco_toggle'));
if('F' == nlapiGetFieldValue('custbody_sco_toggle')){
try{
nlapiSetFieldValue('custbody_sco_toggle', 'T', false, true);
if(type == 'item'){
calculateTotalWeight(type);
}
}catch(e){
tty('ERROR', 'In recalc for '+ type, (e.message || e.toString()) + (e.getStackTrace ? (' \n \n' + e.getStackTrace().join(' \n')) : ''));
}finally{
nlapiSetFieldValue('custbody_sco_toggle', 'F');
}
}
};
return cartScript;
})();
I'm having some trouble getting the value of a column in a saved search via SuiteScript. Below is my code:
function KW_AutoCloseOldRA() {
var search = nlapiLoadSearch('transaction', 'customsearchopen_ras', null, null);
var columns = search.getColumns();
for (i = 0; i < columns.length; i++) {
nlapiLogExecution('DEBUG', 'Column #' + i + ' is ' + columns[i].getName());
}
var results = search.runSearch();
if (results) {
results.forEachResult(getResults);
}
}
function getResults(res) {
var message = res.getValue('tranid');
nlapiLogExecution('DEBUG', 'Result ' + message);
return true;
}
The search produces two columns, and the name of those columns output as expected in the DEBUG entry (internalid is column 0 and tranid is column 1). When looping through the results however, res.getValue('tranid') is always null. I can't seem to find what I'm doing wrong here.
Try getting the value using the columns object and its index like this:
function KW_AutoCloseOldRA() {
var search = nlapiLoadSearch('transaction', 'customsearchopen_ras', null, null);
var columns = search.getColumns();
for (i = 0; i < columns.length; i++) {
nlapiLogExecution('DEBUG', 'Column #' + i + ' is ' + columns[i].getName());
}
var results = search.runSearch();
if (results) {
results.forEachResult(getResults);
}
}
function getResults(res) {
var cols = res.getAllColumns();
var message = res.getValue(cols[1]);
nlapiLogExecution('DEBUG', 'Result ' + message);
return true;
}
I want to print out all number from 1 to 1,000,000 with 1,000 numbers per line. and return the response without having a long delay.
Thanks in advance for any type of help!!!
Well, first you can create a function to print numbers from 1 to 1000.
function getThousand(index) {
var result = '';
for (var i = index; i < index + 1000; i++) {
result += i + ' ';
}
return result;
}
Then, you need a function to call this for 1 to 1000000.
function getAll() {
var result = '';
for (var i = 0; i < 1000; i++) {
result = getThousand((i * 1000) + 1) + " \n";
fs.appendFileSync('foo.txt', result);
}
}
Then call it all:
getAll();
This will save your lines into a file. At the end of getAll() you can print what you need.
Below is code I came up with to run a Saved Search in NetSuite using SuiteScript, create a CSV with the Saved Search results and then email the CSV. The trouble is, the results are limited to 1000 records. I've researched this issue and it appears the solution is to run a loop that slices in increments of 1000. A sample of what I believe is used to slice searches is also below.
However, I cannot seem to be able to incorporate the slicing into my code. Can anyone help me combine the slicing code with my original search code?
var search = nlapiSearchRecord('item', 'customsearch219729');
// Creating some array's that will be populated from the saved search results
var content = new Array();
var cells = new Array();
var temp = new Array();
var x = 0;
// Looping through the search Results
for (var i = 0; i < search.length; i++) {
var resultSet = search[i];
// Returns an array of column internal Ids
var columns = resultSet.getAllColumns();
// Looping through each column and assign it to the temp array
for (var y = 0; y <= columns.length; y++) {
temp[y] = resultSet.getValue(columns[y]);
}
// Taking the content of the temp array and assigning it to the Content Array.
content[x] += temp;
// Incrementing the index of the content array
x++;
}
//Inserting headers
content.splice(0, 0, "sku,qty,");
// Creating a string variable that will be used as the CSV Content
var contents;
// Looping through the content array and assigning it to the contents string variable.
for (var z = 0; z < content.length; z++) {
contents += content[z].replace('undefined', '') + '\n';
}
// Creating a csv file and passing the contents string variable.
var file = nlapiCreateFile('InventoryUpdate.csv', 'CSV', contents.replace('undefined', ''));
// Emailing the script.
function SendSSEmail()
{
nlapiSendEmail(768, 5, 'Inventory Update', 'Sending saved search via scheduled script', 'cc#email.com', null, null, file, true, null, 'cc#email.com');
}
The following code is an example of what I found that is used to return more than a 1000 records. Again, as a novice, I can't seem to incorporate the slicing into my original, functioning SuiteScript. Any help is of course greatly appreciated.
var filters = [...];
var columns = [...];
var results = [];
var savedsearch = nlapiCreateSearch( 'customrecord_mybigfatlist', filters, columns );
var resultset = savedsearch.runSearch();
var searchid = 0;
do {
var resultslice = resultset.getResults( searchid, searchid+1000 );
for (var rs in resultslice) {
results.push( resultslice[rs] );
searchid++;
}
} while (resultslice.length >= 1000);
return results;
Try out this one :
function returnCSVFile(){
function escapeCSV(val){
if(!val) return '';
if(!(/[",\s]/).test(val)) return val;
val = val.replace(/"/g, '""');
return '"'+ val + '"';
}
function makeHeader(firstLine){
var cols = firstLine.getAllColumns();
var hdr = [];
cols.forEach(function(c){
var lbl = c.getLabel(); // column must have a custom label to be included.
if(lbl){
hdr.push(escapeCSV(lbl));
}
});
return hdr.join(",");
}
function makeLine(srchRow){
var cols = srchRow.getAllColumns();
var line = [];
cols.forEach(function(c){
if(c.getLabel()){
line.push(escapeCSV(srchRow.getText(c) || srchRow.getValue(c)));
}
});
return line.join(",");
}
function getDLFileName(prefix){
function pad(v){ if(v >= 10) return v; return "0"+v;}
var now = new Date();
return prefix + '-'+ now.getFullYear() + pad(now.getMonth()+1)+ pad(now.getDate()) + pad( now.getHours()) +pad(now.getMinutes()) + ".csv";
}
var srchRows = getItems('item', 'customsearch219729'); //function that returns your saved search results
if(!srchRows) throw nlapiCreateError("SRCH_RESULT", "No results from search");
var fileLines = [makeHeader(srchRows[0])];
srchRows.forEach(function(soLine){
fileLines.push(makeLine(soLine));
});
var file = nlapiCreateFile('InventoryUpdate.csv', 'CSV', fileLines.join('\r\n'));
nlapiSendEmail(768, 5, 'Test csv Mail','csv', null, null, null, file);
}
function getItems(recordType, searchId) {
var savedSearch = nlapiLoadSearch(recordType, searchId);
var resultset = savedSearch.runSearch();
var returnSearchResults = [];
var searchid = 0;
do {
var resultslice = resultset.getResults(searchid, searchid + 1000);
for ( var rs in resultslice) {
returnSearchResults.push(resultslice[rs]);
searchid++;
}
} while (resultslice.length >= 1000);
return returnSearchResults;
}
I looked into your code but it seems you're missing the label headers in the generated CSV file. If you are bound to use your existing code then just replace
var search = nlapiSearchRecord('item', 'customsearch219729');
with
var search = getItems('item', 'customsearch219729');
and just use the mentioned helper function to get rid off the 1000 result limit.
Cheers!
I appreciate it has been a while since this was posted and replied to but for others looking for a more generic response to the original question the following code should suffice:
var search = nlapiLoadSearch('record_type', 'savedsearch_id');
var searchresults = search.runSearch();
var resultIndex = 0;
var resultStep = 1000;
var resultSet;
do {
resultSet = searchresults.getResults(resultIndex, resultIndex + resultStep); // retrieves all possible results up to the 1000 max returned
resultIndex = resultIndex + resultStep; // increment the starting point for the next batch of records
for(var i = 0; !!resultSet && i < resultSet.length; i++){ // loop through the search results
// Your code goes here to work on a the current resultSet (upto 1000 records per pass)
}
} while (resultSet.length > 0)
Also worth mentioning, if your code is going to be updating fields / records / creating records you need to bear in mind script governance.
Moving your code to a scheduled script to process large volumes of records is more efficient and allows you to handle governance.
The following line:
var savedsearch = nlapiCreateSearch( 'customrecord_mybigfatlist', filters, columns );
can be adapted to your own saved search like this:
var savedsearch = nlapiLoadSearch('item', 'customsearch219729');
Hope this helps.