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;
}
Related
In here I am trying to make a checking where if the "STATUS" column is 'NEW FILE', then i would like to perform a file conversation from excel to spreadsheet.
For the "STATUS" column i created an IF-ELSE statement,
if (row[0] === "last week file") {
newValues.push(['OLD FILE'])
}
else{
newValues.push(['NEW FILE'])
ConvertFiles()
return
}
Therefore, I am making a check through the "STATUS", if the status column is empty it will be written as 'NEW FILE', and then it will perform an file conversion from excel to spreadsheet since i already called the method inside it.
Here is the EDITED version code of the file conversion:
function ConvertFiles() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var range = sheet.getRange(2, 1, sheet.getLastRow()-1, 5); // get A2:E6 range
var data = range.getValues(); // get A2:E6 data
for(var i = 0; i < data.length; i++){
if(data[i][2] == " "){
for( var r= 2;r < sheet.getLastRow()+1; r++){
var fileId = sheet.getRange(r,1).getValue();
var folderID = sheet.getRange(r,2).getValue(); //for destination folder
var files = DriveApp.getFileById(fileId);
var name = files.getName().split('.')[0];
var blob = files.getBlob();
var newFile = {
title: name.replace('_converted','') + '_converted',
parents: [{id: folderID}] };
var destinationFolderId = DriveApp.getFolderById(folderID);
var existingFiles = destinationFolderId.getFilesByName(newFile.title);
while(existingFiles.hasNext()) {
var oldConvertedFileWithSameNameID = existingFiles.next().getId();
Drive.Files.remove(oldConvertedFileWithSameNameID,{supportsAllDrives: true});
}
var newFileID = Drive.Files.insert(newFile, blob, { convert: true,supportsAllDrives: true }).id;
Logger.log(newFileID);
var Url = "https://drive.google.com/open?id=" + newFileID;
//sheet.getRange(r,4).setValue(newFileID);
//sheet.getRange(r,5).setValue(Url);
}
sheet.getRange(i+2,4).setValue(newFileID); //set value in column D
sheet.getRange(i+2,5).setValue(Url); //set value in column E
}
}
}
The error that i am facing is, when i call the method ConvertFiles() inside the if statement, the conversion happens from row 2 until 6 CONTINOUSLY without stopping as shown in sample in red circle.
I only wanted to make conversion on the "NEW FILES" only which will be on row 5 and 6.
How can i make a conversion on the selected/specified row?
It would be more efficient if you obtain all the values in your Sheet, loop the 2D array the getValues() method will return and add an if statement that will only process new files.
Example:
Here in my example below I created a script that will only process rows that have a blank value for the status column.
Code:
function ConvertFiles() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var range = sheet.getRange(2, 1, sheet.getLastRow()-1, 5); // get A2:E6 range
var data = range.getValues(); // get A2:E6 data
/*the content of data is 2D array,
each sub array represent rows in your table*/
for(var i = 0; i < data.length; i++){
if(data[i][2] == ""){ //the 2 in [i][2] represent the value of C column in sheet
//Add your file conversion code here
sheet.getRange(i+2,4).setValue("Test only"); //set value in column D
sheet.getRange(i+2,5).setValue("Test only"); //set value in column E
}
}
}
Data:
Output:
References:
Sheet.getRange(row, column, numRows, numColumns)
Range.getValues()
Range.setValue(value)
EDIT:
The value of data variable in the code below is a 2D array containing all the data in the range provided. In your example, it is the data of A2:E6.
Example output:
[
[fileId1,folderId1,Status1,,],
[fileId2,folderId2,Status2,,],
[fileId3,folderId3,Status3,,],
[fileId4,folderId4,,,],
[fileId5,folderId5,,,],
]
The for loop will access each sub array per iteration and since we already knew the position of our target data (fileID and folderID) we don't need to create another for loop to access it, instead we just specify the index on which the data is located. data[i][0] for file id and data[i][1] for folder id. The if(data[i][2] == "") is added to check if the column C of each row is empty and ignore the one with data.
Code:
function ConvertFiles() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var range = sheet.getRange(2, 1, sheet.getLastRow()-1, 5);
var data = range.getValues();
for(var i = 0; i < data.length; i++){
if(data[i][2] == ""){
var fileId = data[i][0];
var folderID = data[i][1];
var files = DriveApp.getFileById(fileId);
var name = files.getName().split('.')[0];
var blob = files.getBlob();
var newFile = {
title: name.replace('_converted','') + '_converted',
parents: [{id: folderID}] };
var destinationFolderId = DriveApp.getFolderById(folderID);
var existingFiles = destinationFolderId.getFilesByName(newFile.title);
while(existingFiles.hasNext()) {
var oldConvertedFileWithSameNameID = existingFiles.next().getId();
Drive.Files.remove(oldConvertedFileWithSameNameID,{supportsAllDrives: true});
}
var newFileID = Drive.Files.insert(newFile, blob, { convert: true,supportsAllDrives: true }).id;
var Url = "https://drive.google.com/open?id=" + newFileID;
sheet.getRange(i+2,4).setValue(newFileID);
sheet.getRange(i+2,5).setValue(Url);
}
}
}
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 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);
}
I have an xpage, where fields are created dynamically. By default, there are 3, but you can click a button to add as many as you like, naming convention "ObjectiveDetails1", "ObjectiveDetails2" and so on.
I am trying to handle blank fields... For example, there is content in fields 1 and 2, nothing in 3 and 4, but content in 5. What I want to do, is shift content from field 5 into the first available blank, in this case 3. Likewise, if there is content in fields 1, 2, 4, 5, I then need content in 4, to go into field 3, and content in 5 to go into field 4 etc. At the moment, I'm managing to shift content up 1 only.
So if fields 2, 3, 4 are blank but 5 has content, it only moves the content into 4, where-as I need it to move into field 2.
I hope I've explained this well enough..... Current code is a little messy....
for (var i = 1; i < viewScope.rows+1; i++) {
print("Starting Array.....");
if(applicationScope.get("BreakAllCode")==true){
break;
}
var objFieldName:string = "ObjectiveDetails" +i;
print ("Field Name: " + objFieldName);
var fieldValue = document1.getItemValueString(objFieldName);
print ("Field Value: " + fieldValue);
if (fieldValue =="" || fieldValue==null){
print("EMPTY");
// We now need to delete the 3 fields related to this objective
var updFieldName:string = "ObjectiveUpdates" +i;
var SAFieldName:string = "ObjectiveSelfAssessment" +i;
// Before we delete the fields, we need to check if the next field is blank
// and if not, copy its contents into this field.
for (var n =i+1; n < viewScope.rows+1; n++) {
if(applicationScope.get("BreakAllCode")==true){
break;
}
if(document1.hasItem("ObjectiveDetails" +n)){
print("Next field: " +"ObjectiveDetails" +n);
var nextFieldValue = document1.getItemValueString("ObjectiveDetails" +n);
if (!nextFieldValue =="" || !nextFieldValue==null){
// Now copy the content into the field
var nextFieldName:string = "ObjectiveDetails" +n;
var previousNo = n-1;
var previousFieldName:string = "ObjectiveDetails" +previousNo;
print ("Previous field: " + previousFieldName);
document1.replaceItemValue(previousFieldName,nextFieldValue);
// Now clear the content from next field
document1.replaceItemValue(nextFieldName,"");
}else{
// Do nothing
}
}else{
print("Last field");
}
}
// Remove items from the document
//document1.removeItem(objFieldName);
//document1.removeItem(updFieldName);
//document1.removeItem(SAFieldName);
// Remove fields from our arrays
//viewScope.fields.splice(i-1, 1);
//viewScope.fields2.splice(i-1, 1);
//viewScope.fields3.splice(i-1, 1);
// Update the row variable
//viewScope.rows--;
//document1.replaceItemValue("rows",viewScope.rows);
//document1.save();
// We now need to "re-index" the array so that the fields are numbered corectly
}else{
print("We have a value");
}
}
Update with beforePageLoad:
viewScope.rows = document1.getItemValueInteger("rows");
var rowCount:integer = viewScope.rows;
var newCount:integer = 0;
while(newCount<rowCount){
if (!viewScope.fields) {
viewScope.fields = [];
viewScope.fields2 = [];
viewScope.fields3 = [];
}
viewScope.fields.push("ObjectiveDetails" + (viewScope.fields.length + 1));
viewScope.fields2.push("ObjectiveUpdates" + (viewScope.fields2.length + 1));
viewScope.fields3.push("ObjectiveSelfAssessment" + (viewScope.fields3.length + 1));
newCount++;
}
This should be your core algorithm:
var writeIndex = 0;
for (var readIndex = 1; readIndex <= viewScope.rows; readIndex++) {
var value = document1.getItemValueString("ObjectiveDetails" + readIndex);
if (value) {
writeIndex++;
if (readIndex !== writeIndex) {
document1.removeItem("ObjectiveDetails" + readIndex);
document1.replaceItemValue("ObjectiveDetails" + writeIndex, value);
}
} else {
document1.removeItem("ObjectiveDetails" + readIndex);
}
}
viewScope.rows = writeIndex;
The code
deletes all empty fields,
renames fields to ObjectiveDetails1, ObjectiveDetails2, ObjectiveDetails3,... and
writes the resulting number of rows back to viewScope variable "rows".
If I understood your problem correctly, then this code should work (not tested):
// define variables
var i,j,nRows,values,value,allowContinue,fieldname;
// collect values from document fields
nRows=viewScope.rows;
values=[];
for (i=0;i<nRows;i++) {
values.push(document1.getItemValueString("ObjectiveDetails"+(i+1).toFixed(0)));
}
// fill empty values
for (i=0;i<nRows-1;i++) {
if (values[i]) continue;
allowContinue=false;
for (j=i+1;j<nRows;j++) {
if (value=values[j]) {
values[i]=value;
values[j]="";
allowContinue=true;
break;
}
}
if (!allowContinue) break;
}
// write back to document and remove empty fields on the end
for (i=0;i<nRows;i++) {
fieldname="ObjectiveDetails"+(i+1).toFixed(0);
if (value=values[i]) document1.replaceItemValue(fieldname,value);
else document1.removeItem(fieldname);
}
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.