Netsuite: Is it possible to pass array in custparam? - netsuite

var stAccNum = '1013320075';
var stAccName = 'ABC SINGAPORE PTE LTD';
var arrRecItem = new Array();
for (var x = 0; x < 3; x++) {
arrRecItem[x] = [];
}
;
arrRecItem[0][0] = '2';
arrRecItem[0][1] = 'DBSSSGSGXXX';
arrRecItem[0][2] = '301234567';
var arrParams = {
custparam_jason_my_acc_num : stAccNum,
custparam_jason_my_acc_name : stAccName,
***custparam_jason_rec_item_arr : arrRecItem*** };
nlapiSetRedirectURL('SUITELET', 'customscript_jason_ss_bulk_payment_file',
'customdeploy_jason_ss_bulk_payment_file', null, arrParams);
As shown in code above, I failed to pass the array arrRecItem in arrParams. Is there any ways to pass this array as custparam and pass to suitelet?
Thank you.

Sure, just use JSON.stringify(arrRecItem) and then parse it on the suitelet with JSON.parse(arrRecItem)

Related

If Else statement inside the nlapiSearchRecord

Badly need help..
I am trying to add a condition inside my nlapiSearchRecord API but the condition is not being followed. Though it is running fine with no errors, the suitelet is looking at the first parameter even if it should follow the else statement.
Please refer at the line: var arrSearchResults = nlapiSearchRecord(searchRecordType, null, arrSearchFilters, (searchRecordType = 'transaction') ? arrSearchColumnsTrans : arrSearchColumnsCustomers) || [];
Even though the searchRecordType is 'customers', it still follows the arrSearchColumnsTrans, not the arrSearchColumnsCustomers
var searchRecordType = request.getParameter ('custpage_rectype');
var searchLookupText = request.getParameter ('custpage_lookuptext');
var searchLookupField = request.getParameter ('custpage_lookupfield');
var searchParameter = request.getParameter ('custpage_searchparam');
var arrSearchFilters = [new nlobjSearchFilter(searchLookupField, null, searchParameter, searchLookupText)];
var arrSearchColumnsTrans = [new nlobjSearchColumn('internalid'),
new nlobjSearchColumn('type'),
new nlobjSearchColumn('entity')];
var arrSearchColumnsCustomers = [new nlobjSearchColumn('internalid'),
new nlobjSearchColumn('entityid'),
new nlobjSearchColumn('companyname')];
var arrSearchResults = nlapiSearchRecord(searchRecordType, null, arrSearchFilters,
(searchRecordType = 'transaction') ? arrSearchColumnsTrans : arrSearchColumnsCustomers) || [];
var objVal = {};
for (var i = 0, ii = arrSearchResults.length; i < ii; i++)
{
var val = arrSearchResults[i];
objVal[val.getId()] = {};
objVal[val.getId()].tranid = val.getValue('tranid');
objVal[val.getId()].internalid = val.getValue('internalid');
objVal[val.getId()].type = val.getValue('type');
objVal[val.getId()].entityid = val.getValue('entityid');
objVal[val.getId()].entity = val.getText('entity');
}
Your ternary statement doesn't actually have a conditional:
(searchRecordType = 'transaction') ? ...
Because you're using =, you're just assigning the value of 'transaction' to searchRecordType. If you want to compare the two values instead, you'll want to use == or ===.
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality
Thank you!
All good now..
var arrSearchResults = (searchRecordType === 'transaction') ? nlapiSearchRecord(searchRecordType, null, arrSearchFilters, arrSearchColumnsTrans) : (searchRecordType === 'item') ? nlapiSearchRecord(searchRecordType, null, arrSearchFilters, arrSearchColumnsItems) : nlapiSearchRecord(searchRecordType, null, arrSearchFilters, arrSearchColumns) || [];

How to get over 1000 records from a SuiteScript Saved Search?

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.

Node JS for loop does not work

In node js, after running the for loop, descrip does not contain anything, no field written into the descrip array, why?
data = data['data'];
var course = data['course'];
data = data['sections'];
var descrip = new Array();
console.log(data.length);
for (var i = data.size - 1; i >= 0; i--) {
var data = data[i];
var section = data['section'];
var day = data['day'];
var date = data['date'];
var start = data['start_time'];
var end = data['end_time'];
var location = data['location'];
var res = 'Section: '+section+'\nDate: '+date+' '+day+'\nLocation: '+location+'\nStart: '+start+'\tEnd: '+end;
descrip.push(res);
};
Assuming you expect data to be an array, data.size - 1 will be -1 since data.size is null. So it will exit the loop immediately. You probably want data.length.
The length of an array in JavaScript is returned by the length property:
for (var i = data.length - 1; i >= 0; i--) {
// no block scope in JS, using data as a variable name here overwrites array
// var data = data[i];
var _data = data[i];
var section = _data['section'];
var day = _data['day'];
var date = _data['date'];
var start = _data['start_time'];
var end = _data['end_time'];
var location = _data['location'];
var res = 'Section: '+section+'\nDate: '+date+' '+day+'\nLocation: '+location+'\nStart: '+start+'\tEnd: '+end;
descrip.push(res);
};
Also, as pointed out in the comments by #Red Alert, you're overwriting your data variable in the for loop (JavaScript has no concept of block scope). I've renamed it _data, but you could probably come up with a more meaningful name to distinguish between the array and the element of the current iteration.

How can I create a new document out of a subset of another document's pages (in InDesign (CS6) using ExtendScript)?

I need to offer a feature which allows InDesign users to select a page range in an InDesign document and create a new document out of those pages. This sounds simple, but it isn't...
I have tried many different ways of doing this but they have all failed to some degree. Some methods put all pages in a single spread (which sometimes makes InDesign crash). The best I've been able to do (see code below) still has problems at the beginning and the end (see screenshots below):
The original document:
The new document:
The question: How can I create a new document out of a subset of another document's pages (in InDesign using ExtendScript) without having the problems shown in the screenshots?
note: The behavior of the script is quite different in CS5.5 and CS6. My question concerns CS6.
The second screenshot was obtained by applying the following code to the document shown in the first screenshot:
CODE
var firstPageName = { editContents: "117" }; // This page number is actually entered by the user in an integerEditbox
var lastPageName = { editContents: "136" }; // This page number is actually entered by the user in an integerEditbox
var sourceDocument = app.activeDocument;
var destDocument = app.documents.add();
destDocument.importStyles(ImportFormat.paragraphStylesFormat, new File(sourceDocument.filePath + "/" + sourceDocument.name), GlobalClashResolutionStrategy.LOAD_ALL_WITH_OVERWRITE);
destDocument.importStyles(ImportFormat.characterStylesFormat, new File(sourceDocument.filePath + "/" + sourceDocument.name), GlobalClashResolutionStrategy.LOAD_ALL_WITH_OVERWRITE);
destDocument.viewPreferences.horizontalMeasurementUnits = sourceDocument.viewPreferences.horizontalMeasurementUnits;
destDocument.viewPreferences.verticalMeasurementUnits = sourceDocument.viewPreferences.verticalMeasurementUnits;
destDocument.documentPreferences.facingPages = sourceDocument.documentPreferences.facingPages;
destDocument.documentPreferences.pageHeight = sourceDocument.documentPreferences.pageHeight;
destDocument.documentPreferences.pageWidth = sourceDocument.documentPreferences.pageWidth;
destDocument.documentPreferences.pageSize = sourceDocument.documentPreferences.pageSize;
var sourceSpreads = sourceDocument.spreads;
var nbSourceSpreads = sourceSpreads.length;
var firstPageFound = false;
var lastPageFound = false;
var i;
var newSpreadNeeded;
var currentDestSpread;
for (i = 0; !lastPageFound, i < nbSourceSpreads; ++i) {
newSpreadNeeded = true;
var sourcePages = sourceSpreads[i].pages;
var nbSourcePages = sourcePages.length;
var j;
for (j = 0; !lastPageFound, j < nbSourcePages; ++j) {
if (sourcePages[j].name === firstPageName.editContents) {
firstPageFound = true;
destDocument.documentPreferences.startPageNumber = parseInt(firstPageName.editContents); // We want to preserve page numbers
}
if (firstPageFound) {
// Copy this page over to the new document.
var firstInNewSpread = false;
if (newSpreadNeeded) {
currentDestSpread = destDocument.spreads.add();
newSpreadNeeded = false;
firstInNewSpread = true;
}
var newPage = sourcePages[j].duplicate(LocationOptions.AT_END, currentDestSpread);
var k;
for (k = 0; k < newPage.index; ++k) {
currentDestSpread.pages[k].remove();
}
}
if (sourcePages[j].name === lastPageName.editContents) {
lastPageFound = true;
}
}
}
destDocument.spreads[0].remove();
I was hacking around and came up with this little script. Although it approaches the problem from the opposite direction, it seems to work fine here. Also, I'm still running in InDesign CS5, but maybe it will work for you. Hopefully I got the gist of your question?
This will extract pages 3 through 5 into a separate document:
var doc = app.activeDocument;
var newFilePath = doc.filePath + "/subset_" + doc.name;
var newFile = File(newFilePath); // Create a new file path
doc.saveACopy(newFile); // Save a copy of the doc
var newDoc = app.open(newFile); // Open the copy
var firstPageNum = 3; // First page number in the range
var lastPageNum = 5; // Last page number in the range
var firstPage = newDoc.pages[firstPageNum-1];
var lastPage = newDoc.pages[lastPageNum-1];
// Remove all text from the last page in the range to the end of the document
var lastPageFrames = lastPage.textFrames.everyItem().getElements();
for (var i=0; i < lastPageFrames.length; i++) {
var frame = lastPageFrames[i];
var parentStory = frame.parentStory;
var lastFrameInsert = frame.insertionPoints.lastItem();
var lastStoryInsert = parentStory.insertionPoints.lastItem();
var textAfter = parentStory.insertionPoints.itemByRange(lastFrameInsert,lastStoryInsert);
textAfter.remove();
};
// Remove all text from the beginning of the document to the first page in the range
var firstPageFrames = firstPage.textFrames.everyItem().getElements();
for (var i=0; i < firstPageFrames.length; i++) {
var frame = firstPageFrames[i];
var parentStory = frame.parentStory;
var firstFrameInsert = frame.insertionPoints.firstItem();
var textBefore = parentStory.insertionPoints.itemByRange(0,firstFrameInsert.index);
textBefore.remove();
};
// Remove the pages that aren't in the range
var allPages = newDoc.pages.everyItem().getElements();
for (var i=0; i < allPages.length; i++) {
var page = allPages[i];
if (i < firstPageNum || i > lastPageNum) {
page.remove();
}
};

Help required to form Json string in Javascript

Hi i have to create a json sting in javascript like this
{widget_list:[{widget_id:1,new_position:2},{widget_id:2,new_position:3}, . . .]}
using json.org library. Function i am using of this library is
var json_text =
JSON.stringify(uploaded, "", "");
Which creates a perfect json string i am able to generate when there is a no array
function uploaded()
{
}
var uploaded = new Uploaded();
uploaded.widget_id = 1;
uploaded.new_position = 2;
var json_text = JSON.stringify(uploaded, "", "");
when u alert json_text u will get {"widget_id":1,"new_position":2} requirment is just download a file json2.js from json.org for javascript and include it.
so please help some logic issue i am unable to create....
thanks in advance....
uploaded = {};
var a = [];
uploaded.widget_id = 1;
uploaded.new_position = 2;
a[0] = uploaded;
uploaded.widget_id = 2;
uploaded.new_position = 3;
a[1] = uploaded;
uploaded_new = {}
uploaded_new.widget_list = a
alert( JSON.stringify(uploaded_new, "", ""));
alert will give
{"widget_list":[{"widget_id":2,"new_position":3},{"widget_id":2,"new_position":3}]}
I came across this looking for a similar solution, in that it helped. But you need to re-initialize the "uploaded" object, otherwise it over-writes the existing values.
So, with that slight modification, it would be
uploaded = {};
var a = [];
uploaded.widget_id = 1;
uploaded.new_position = 2;
a[0] = uploaded;
**uploaded = {};**
uploaded.widget_id = 2;
uploaded.new_position = 3;
a[1] = uploaded;
uploaded_new = {}
uploaded_new.widget_list = a
alert( JSON.stringify(uploaded_new, "", ""));

Resources