Im trying to display a confirmation message when a record is correctly saved and an error message when its not.
But when I try to save the script I get
SuiteScript 2.x entry point scripts must implement one script type function
appears and i don't know why. Here is the script:
/**
* #NApiVersion 2.x
* #NScriptType ClientScript
*
*/
define('[N/ui/message]', function(message){
function saveRecord(context){
var currentRecord = context.currentRecord;
var pName = currentRecord.getValue('name');
var pAge = currentRecord.getValue('custrecord_p_age');
var pLastName = currentRecord.getValue('custrecord_plastname');
if(pName != null && pAge != null && pLastName != null ){
var confirmationMsg = message.create({
title: 'Enhorabuena',
message: 'La persona ah sido ingresada con exito',
Type: message.Type.CONFIRMATION
});
confirmationMsg.show({
duration: 5000
});
return true;
}else{
var errorMsg = message.create({
title: 'Enhorabuena',
message: 'La persona ah sido ingresada con exito',
Type: message.Type.ERROR
});
errorMsg.show({
duration: 5000
});
return false;
}
}
return{
saveRecord: saveRecord
}
});
Change
/** *#NApiVersion 2.x *#NScriptType ClientScript * */
to (remove the extra * towards the end of the tag)
/**
*#NApiVersion 2.x
*#NScriptType ClientScript
*/
Also change
define('[N/ui/message]', function(message){
to (move the single quotes to inside the brackets)
define(['N/ui/message'], function(message){
Try a stripped down version in the debugger with "Require." Your code seems fine. Also write it in Visual Code so you can see the formatting. Take out the functionality and see what is missing in structure for suitescript 2.0, example:
/**
* #NApiVersion 2.x
* #NScriptType Restlet
*/
define(["N/log"], function(log) {
function dostuff(context) {
//do stuff
}
return {
post: dostuff
};
});
Related
I have created a button on the work order records that opens a suitelet form with a fieldType.FILE to allow the user to choose a file locally. When the Suitlet is submitted I want the script to take the file, take the contents, and then pass two arrays to a scheduled script. So far I have no errors and none of my log.debugs are showing up in Netsuite.
Here is the suitelet code for reference:
/**
* #NApiVersion 2.x
* #NScriptType Suitelet
*
* #author MF
*/
define(['N/ui/serverWidget', 'N/file', 'N/search', 'N/email','N/ui/dialog'], function (serverWidget, file, search, email, dialog) {
function onRequest(context) {
//getWoData(context);
buildPage(context);
};
function buildPage(context) {
var woForm = serverWidget.createForm({
title: "Mass Update Work Order Due Dates",
})
woForm.addField({
id: 'custpage_wo_export',
label: "Work Order Update File",
type: serverWidget.FieldType.FILE
});
woForm.addSubmitButton({
id: 'custpage_submitwo',
label: 'Submit',
functionName: 'SubmitWorkOrders'
});
woForm.clientScriptModulePath = "SuiteScripts/WoSubmitClient.js"
context.response.writePage(woForm);
}
return {
onRequest: onRequest
};
});
The issue starts at the client as far as I know.
Here is the client script for the Suitelet above:
/**
* #NApiVersion 2.X
* #NScriptType ClientScript
* #NModuleScope SameAccount
* #author MF
*/
define(['N/url', 'N/https','N/currentRecord'], function (url, https, currentRecord) {
function pageInit(context) { };
function SubmitWorkOrders(context) {
var objRecord = currentRecord.get();
//Handle the save button
log.debug({
title: 'SubmitWorkOrders',
details: "This function was called"
})
var uploadedFile = objRecord.getValue({
fieldId: 'custpage_wo_export'
})
log.debug({
title: 'File',
details: uploadedFile.name
})
var taskCreate = url.resolveScript({
scriptId: 'customscript_scheduledscripttaskagent',
deploymentId: 'customdeploy_scheduledscripttaskagent',
returnExternalUrl: false,
params: {
input_file: uploadedFile
}
});
}
return {
pageInit: pageInit,
saveRecord: SubmitWorkOrders
};
});
This client script then calls another suitelet to create and run the task.
/**
* #NApiVersion 2.x
* #NScriptType Suitelet
*
* #author MF
*/
define([
'N/task',
'N/redirect',
'N/file'
], function (task, redirect, file) {
function scriptTask(context) {
//check file type
var input_file = context.request.params.input_file;
log.debug({
title: 'File Name',
details: input_file.name
})
var woUpdateScriptTask = task.create({
taskType: task.taskType.SCHEDULED_SCRIPT,
deploymentId: 'customscript_womassupdate',
params: { uploadedFile: uploadedFile },
scriptId: 715
}).submit();
}
return {
onRequest: scriptTask
};
});
Any advice would be appreciated, I have only been in the Netsuite realm for a few weeks and javascript in general only a bit longer than that. Note that there is some residual modules in some of these scripts from testing different approaches.
Currently the entire process looks something like this -> (1)UserEventScript on Work Orders -> (2)ClientScript on Work Orders -> (3)First attached Suitelet -> (4)ClientScript for Suitelet -> (5)Suitelet to create the task to run the scheduled script -> (6)ScheduledScript to update work orders. Looking to get some advice on getting the file contents from step 3 to step 5 so the data could get parsed before they are passed to the scheduled script.
Thanks in advance
I think this is how you can get the file contents from your first Suitelet to your Scheduled script:
First, you need to combine your 1st and 2nd Suitelet into one single Suitelet. This is required for getting selected file.
You can simply do it like this in your first Suitelet > function onRequest():
function onRequest(context) {
if (request.method == 'GET') { //This block will execute when you open your Suitelet form
buildPage(context);
}else{ //This block will execute when Submit button is clicked
scriptTask(context); // add scriptTask() function body in your 1st Suitelet from 2nd Suitelet
}
};
Second, if your client script is attached with a Suitelet you can view it's logs using console.log instead of log.debug in web browser's console (open with Ctrl+Shift+i). BUT getting value of 'custpage_wo_export' in your CS will only return a string like 'C:\fakepath\your_file_name.file_extension'. You might need to first save selected file in NetSuite's File Cabinet to access it's contents. This can be done in function scriptTask() now in your 1st Suitelet.
In Client Script > function SubmitWorkOrders(), use:
function SubmitWorkOrders(context) {
var objRecord = context.currentRecord;
var uploadedFile = objRecord.getValue({
fieldId: 'custpage_wo_export'
})
console.log('File', uploadedFile);
return true; //use return 'false' to view the log in console first
}
Now Third, in function scriptTask(), now in 1st Suitelet, use:
function scriptTask(context) {
if (context.request.files.custpage_wo_export) {
var fileObj = context.request.files.custpage_wo_export; //save this fileObj and then access it's contents.
log.debug('fileObj', fileObj);
fileObj.folder = 1630; //speficy the id of folder in File Cabinet
var fileId = fileObj.save();
log.debug("fileId", fileId);
//Now, load newly saved file and access it's contents. You can also access file contents in your Scheduled script depending on what you prefer/require.
if (fileId) {
var fileObj = file.load({
id: fileId
});
fileContents = fileObj.getContents();
log.debug("fileContents", fileContents);
/*
Now, you have fileId and/or fileContents. You can execute your Scheduled script here using task.create() etc.
*/
}
}
}
Note: Selecting and uploading/saving the same file in File Cabinet will simply overwrite the existing file keeping file id same.
I am using Suitescript 2.0. There I am trying to reschedule a script for a particular type of error.
I got the below code which can be used to rescheduled the script immediately.
var scriptTask = task.create({
taskType: task.TaskType.MAP_REDUCE
});
scriptTask.scriptId = 'customscript_id';
scriptTask.deploymentId = 'customdeploy_id';
var scriptTaskId = scriptTask.submit();
But I am mainly looking for some option to run it after a certain time like after an hour.
Is it possible to achieve by passing any kind of parameter to the above task?
Any other alternative approach would also helpful.
I had a similar issue, I needed to delay my schedule a certain time in your case a map/reduce script which should be the same.
I fixed it with this approach.
Here is sample code with the approach.
/**
#NApiVersion 2.x
#NScriptType ScheduledScript
#NModuleScope SameAccount
*/
define(['N/file', 'N/record', 'N/render', 'N/runtime', 'N/search', 'N/ui/serverWidget', 'N/format', 'N/task', 'N/log'],
function(file, record, render, runtime, search, serverWidget, format, task, log) {
/**
* Definition of the Scheduled script trigger point.
*
* #param {Object} scriptContext
* #param {string} scriptContext.type - The context in which the script is executed. It is one of the values from the scriptContext.InvocationType enum.
* #Since 2015.2
*/
function execute(scriptContext) {
wait(20000); // it waits 20 sec
//whatever you want to do
}
function wait(ms){
var start = new Date().getTime();
var end = start;
while(end < start + ms) {
end = new Date().getTime();
}
}
return {
execute: execute
};
});
I am running into the issue below when trying to edit a CUSTOMER record in NetSuite. The script I have created is very simple.
What could I possibly doing wrong with such a simplistic piece of code?
{"type":"error.SuiteScriptModuleLoaderError","name":"MODULE_DOES_NOT_EXIST","message":"Module does not exist: /SuiteScripts/BillingInfoUpdated.js","stack":[]}
SCRIPT:
define(['N/log'], function (log) {
/**
* User Event 2.0 example showing usage of the Submit events
*
* #NApiVersion 2.x
* #NModuleScope SameAccount
* #NScriptType UserEventScript
* #appliedtorecord customer
*/
var exports = {};
function afterSubmit(scriptContext) {
log.debug({
"title": "After Submit",
"details": "action=" + scriptContext.type
});
}
exports.afterSubmit = afterSubmit;
return exports;
});
Add .js to the end of the script file name
Nathan Sutherland answer worked for me and it's absolutely fine But I'm writing this answer so new user get that faster and not confused with other names.
You need to add .js where the blue arrow points.
On starting while creating script.
if you forget then edit here
Use this instead:
var LOGMODULE; //Log module is preloaded, so this is optional
/**
*#NApiVersion 2.x
*#NModuleScope Public
*#NScriptType UserEventScript
*/
define(['N/log'], runUserEvent);
function runUserEvent(log) {
LOGMODULE = log;
var returnObj = {};
returnObj.afterSubmit = afterSubmit;
return returnObj;
}
function afterSubmit(context) {
log.debug('After Submit', "action=" + context.type);
//LOGMODULE.debug('After Submit', "action=" + context.type); //Alternatively
//context.newRecord; //Just showing how to access the records
//context.oldRecord;
//context.type;
return;
}
For more 2.0 Quickstart Samples: ursuscode.com
So I know the method app.set() is that setting value for a name. therefore, app.get() could get the value by name. but accordingly, if I set 'view engine' to 'ejs',where is the app.get('view engine')? if not have, how dose the app.set('view engine','ejs') work?
thank you for responding this wizard question.
It works as You expect:
How it works?
Check this: https://github.com/expressjs/express/blob/master/lib/application.js#L336
From line: 336
/**
* Assign `setting` to `val`, or return `setting`'s value.
*
* app.set('foo', 'bar');
* app.get('foo');
* // => "bar"
*
* Mounted servers inherit their parent server's settings.
*
* #param {String} setting
* #param {*} [val]
* #return {Server} for chaining
* #public
*/
app.set = function set(setting, val) {
if (arguments.length === 1) {
// app.get(setting)
return this.settings[setting];
}
debug('set "%s" to %o', setting, val);
// set value
this.settings[setting] = val;
// trigger matched settings
switch (setting) {
case 'etag':
this.set('etag fn', compileETag(val));
break;
case 'query parser':
this.set('query parser fn', compileQueryParser(val));
break;
case 'trust proxy':
this.set('trust proxy fn', compileTrust(val));
// trust proxy inherit back-compat
Object.defineProperty(this.settings, trustProxyDefaultSymbol, {
configurable: true,
value: false
});
break;
}
return this;
};
I have a suitelet with a sublist button and I am trying to get the button to execute a function on a custom module. I can not get it to work. I get an error "Cannot call method "receive" of undefined"
Any Ideas?
Snippet of code to add button
define(['N/error', 'N/record', 'N/search', 'N/ui/serverWidget','./lib1'],
function(error, record, search, ui, lib1) {
//... some code here
searchSublist.addButton({
id: 'custpage_recievepayment',
label: 'Receive Payment',
functionName: "lib1.receive()"});
}
Snippet of custom Module
define(['N/redirect'],
function(redirect){
function receive(){
var deal = '497774';
var url = redirect.toSuitelet({
scriptId: 'customscript_deal_entry_2_0',
deploymentId: 'customdeploy1',
returnExternalUrl: false,
params: {
prevdeal: url
}
})
}
});
I was able to get this to work with out the client script or exporting it to the global object that was suggested. The key was to modify my custom module to return the function I wanted to use on the button and calling the custom module file with form.clientScriptFileId
//suitelet
define(['N/error', 'N/record', 'N/search', 'N/ui/serverWidget'],
function(error, record, search, ui) {
// other code here
form.clientScriptFileId = 78627;//this is the file cabinet internal id of my custom module
var searchSublist = form.addSublist({
id: 'custpage_deals',
type: ui.SublistType.LIST,
label: 'Deals'
})
searchSublist.addButton({
id: 'custpage_receivepayment',
label: 'Receive Payment',
functionName: "receive()"
});
//custom module
define(['N/url','N/error'],
function(url, error) {
return{
receive: function(){
//function code here
}
}
})
For suitescript 2.0, you'll need to define the file that actually contains your function.
/**
*#NApiVersion 2.x
*#NScriptType UserEventScript
*/
define([],
function() {
function beforeLoad(context) {
if(context.type == "view") {
context.form.clientScriptFileId = 19181;
context.form.addButton({
id: 'custpage_dropshippo',
label: 'Generate Dropship PO',
functionName: 'generateDropshipPurchaseOrder'
});
}
}
return {
beforeLoad: beforeLoad,
};
}
);
In that example, the value 19181 is the file cabinet ID of the following file (which doesn't need a deployment but does need a script record):
/**
*#NApiVersion 2.x
*#NScriptType ClientScript
*/
define([],
function() {
function pageInit() {
}
function generateDropshipPurchaseOrder() {
console.log("foo");
}
return {
pageInit: pageInit,
generateDropshipPurchaseOrder: generateDropshipPurchaseOrder
};
});
Thanks for sharing this information. I finally made it to work by using the "file cabinet internal id" not the "client script" internal id, as mentioned by someone in this thread.
Also i noticed through the chrom developer tool that "scriptContext" is not automatically passed over to the client script function as i had expected. So i had to manually pass in the data i need in the client script through the following way:
function beforeLoad(scriptContext) {
var form = scriptContext.form;
form.clientScriptFileId = 33595032;
form.addButton({
id: 'custpage_reprocessinvoice',
label: 'Reprocess Invoice',
functionName: 'reprocess(' + scriptContext.newRecord.id + ')'
});
}
Hope this may help someone and save him/her a bit of time.
Button click handlers is something of an issue (at least, in my opinion) in 2.0. You are getting this error because lib1 is not defined on the client side.
What I have had to do is create a Client Script that exports my click handlers to the global object to make them accessible. Something like:
// Client script
define(['my/custom/module'], function (myModule) {
window.receive = myModule.receive;
});
// Suitelet
define(...
// some code...
searchSublist.addButton({
id: 'custpage_recievepayment',
label: 'Receive Payment',
functionName: "receive"
});
// other code...
It's not ideal, and certainly not good practice in general to export to the global space, but I do not know any other way to reference a function within a module on a button click.
After not getting this to work after multiple tries I filed a defect with Netsuite (Defect 390444) and they have just told me that this has now been fixed and tested and will be in the next major release.