Suitescript 2.0 Quickstart Examples

Suitescript 2.0 Quickstart Examples

Here I will be posting the most used scripts from Suitescript 2.0. These code examples are meant for beginners to be a quick start so they can quickly get a script started and add their code to them. I tried to keep them short. If you are a beginner I recommend you to check Netsuite’s Help section and navigate to Suitescript 2.0 API so you can learn more about each.

 


Client Script

Note: Check out how the helper functions in clientscript have to be nested inside the main runClientscript function. This is something particular to client scripts.


User Event Script


Scheduled Script


Suitelet


RESTlet

Leave a comment if you want to see other examples.

  • Dilip DiLee

    Thanks a lot Adolfo.

    This will b helpful for all beginers

  • Dilip DiLee

    i need to use this getId() in suitescript2.0 user event script after submit function.

    • Use context.newRecord.id

      • Dilip DiLee

        thank you

        • Dilip DiLee

          //trying to add days

          // getting start date value from task

          var stDate1 = sTask.getValue({
          fieldId: ‘startdate’
          });

          log.debug({
          title: ‘string date’,
          details: ‘Value: ‘ +stDate1 //Tue Jan 17 2017 00:00:00 GMT-0800 (PST)
          });

          //date Format
          var dtDate1 = format.format({
          value: stDate1,
          type: format.Type.DATE
          });

          log.debug({
          title: ‘dtDate1’,
          details: ‘dtDate1’ + dtDate1 // 11/17/2017
          });

          how can i add 30 days
          and get the added date in this format Tue Jan 17 2017 00:00:00 GMT-0800 (PST)

          because there is no api for suitescript 2.0 to addDays

          • You will probably need to parse the date with JS new Date(yourDate) and manipulate the date object to add the dates. Then you just turn the date object back into NS date format.

          • Dilip DiLee

            can u show me some sample code so that i can understand
            better

          • Dilip DiLee

            Thank you
            i got the output

            i tried it

          • Awesome. I am glad you figured it out!

  • Dilip DiLee

    any alternative for nlapiDisableField once i get check box value in suitescript 2.0??

    • nlapiDisableField doesnt have an equivalent function for SuiteScript 2.0.

      You could hack your way into achieving this in 2.0, but I would just keep using 1.0 for now.

  • Dilip DiLee

    nlapiResolveURL(type, identifier, id, displayMode)

    is their any equivalent to this in 2.0??

    or any hack / modules to do this in 2.0??

    i checked N/url module

    but i need to resolveURL in clientscript.

    is that possible??

    • Dilip DiLee

      i got the answer
      url.resolveScript({

      });

      • Yogesh Bhurley

        how can i trigger suitelet for me its not triggering i am using form suitelet here

        • You need to deploy it first and then go to the deployment URL. If set to released your user needs to be within the roles/users with permission to access the Suitelet. If you deployed the Suitelet code in this page then you should be greeted with a “Hello World” page.

  • Dilip DiLee

    Hi Adolfo

    Do u have any technical documents related to suiteGL enhancements using custom GL lines plug-in
    it will be helpful for me

  • Yamini Surender

    I have created custom button using user event script on the custom module VIEW mode. But the button is not triggering my function. Can you help me to resolve this issue ?

    I can able to see the button that I have created via user evetn script. When I click the button, nothing happened!

    • You need to attach your clientscript to the form. See the following post for code sample on how to do this: https://ursuscode.com/netsuite-tips/running-client-script-in-view-mode/

      • Yamini Surender

        Thanks for the reply!

        Please find the client script code :

        define([‘N/record’,’N/search’],
        function(record,search) {

        function create_amort_schedule() {
        var v_loan_pymt_mthd=currentRecord.getValue({
        fieldId:’custrecordpfg_adv_loan_pymt_type’
        });
        alert(v_loan_pymt_mthd);

        }
        });

        User Event Script Code :

        /**
        *@NApiVersion 2.x
        *@NScriptType UserEventScript
        */
        define([‘N/ui/serverWidget’],
        function(record) {

        function beforeLoad (scriptContext) {
        if (scriptContext.type == scriptContext.UserEventType.EDIT) {
        scriptContext.form.clientScriptFileId = 13553;
        scriptContext.form.addButton({
        id: ‘custpage_some_button’,
        label: ‘Schedule’,
        functionName: ‘create_amort_schedule();’
        });
        }
        }

        return {
        beforeLoad : beforeLoad
        };
        });

        Can you please tell me where i am making mistake ?

        Thanks!

        • Your situation is a bit tricky cause you need to pass the recordid, but I managed to do it.

          Formatted: http://pastebin.com/EyTV7zpi

          //########## CLIENTSCRIPT ##########
          var SEARCHMODULE, RECORDMODULE;
          define([‘N/search’, ‘N/record’], runClientscript);

          function runClientscript(search, record){
          SEARCHMODULE = search;
          RECORDMODULE = record;

          //*********** HELPER FUNCTIONS ***********
          function create_amort_schedule(recordid) {//Here you receive the record id. Alternatively you can use SS 1.0 nlapiGetRecordId() but its deprecated.
          var YOUR_RECORD_TYPE = ‘custrecord_XXXX’;
          var fieldLookUp = SEARCHMODULE.lookupFields({ type: YOUR_RECORD_TYPE, id: recordid, columns: [‘custrecordpfg_adv_loan_pymt_type’]});//Doing a lookup cause its faster than loading the record
          var v_loan_pymt_mthd = fieldLookUp.custrecordpfg_adv_loan_pymt_type;
          alert(v_loan_pymt_mthd);
          return;
          }

          var returnObj = {};
          returnObj.create_amort_schedule = create_amort_schedule;
          return returnObj;
          }

          //########## USEREVENT ##########
          var WIDGETMODULE;
          /**
          *@NApiVersion 2.x
          *@NModuleScope Public
          *@NScriptType UserEventScript
          */
          define([‘N/ui/serverWidget’], runUserEvent);

          function runUserEvent(widget) {
          WIDGETMODULE = widget;

          var returnObj = {};
          returnObj.beforeLoad = beforeLoad;
          return returnObj;
          }

          function beforeLoad(context) {
          if (context.type == context.UserEventType.VIEW) {
          context.form.clientScriptFileId = 13553;
          context.form.addButton({
          id : ‘custpage_some_button’,
          label : ‘Schedule’,
          functionName : ‘create_amort_schedule(‘ + context.newRecord.id + ‘)’ //Notice how you need to pass the id of the record as an argument. Your clientscript will receive it.
          });
          }
          return;
          }

          • Yamini Surender

            Thanks for the detailed explanation!
            However I couldn’t able to understand the below line :-

            functionName : ‘create_amort_schedule(‘ + context.newRecord.id + ‘)’ //Notice how you need to pass the id of the record as an argument. Your clientscript will receive it.

            what do you mean by ‘ + context.newRecord.id + ‘ ? I’m making mistake in this line only.

            I’m beginner to suitescript 2.0 version and so i’m raising many questions!

            Thanks for your help !

          • You were trying to get the value of one of the fields and tried getting that from the context on the clientscript, but that won’t work, so I passed the record id to the function by calling it like create_amort_schedule(12345)

          • Yamini Surender

            Thanks for your help and detailed explanation :

            I have modified the user event script as follows :

            /**
            * @NApiVersion 2.0
            * @NScriptType UserEventScript
            * @NModuleScope SameAccount
            */
            define([], function() {
            return {
            beforeLoad: function (params)
            {
            var form = params.form;

            form.clientScriptModulePath = ‘./calculateInterest.js’;
            form.addButton({
            id: ‘custpage_custombutton’,
            label: ‘Generate Schedule’,
            functionName: ‘create_amort_schedule’
            });

            }
            };
            });

            var CURRENTRECORDMODULE;
            /**
            * @NApiVersion 2.x
            * @NScriptType ClientScript
            * @NModuleScope SameAccount
            */

            define([‘N/currentRecord’],

            function saveRec(currentRecord){
            CURRENTRECORDMODULE = currentRecord;

            //*********** HELPER FUNCTIONS ***********
            function create_amort_schedule() {
            var currentRec = CURRENTRECORDMODULE.get();
            var v_loan_pymt_mthd = currentRec.getValue({
            fieldId:’custrecordpfg_adv_loan_pymt_type’
            });
            alert(v_loan_pymt_mthd);
            currentRec.setValue({
            fieldId: ‘custrecordpfg_adv_loan_amount’,
            value: ‘100’
            });
            return;
            }

            var returnObj = {};
            returnObj.saveRecord = saveRec;
            returnObj.create_amort_schedule = create_amort_schedule;
            return returnObj;
            });

            We need to mention the Client Script module path and then it is worked perfectly:)

            Thanks again!

          • I actually figured out an easier way. I wasn’t aware of the “n/currentRecord” module which simplifies things. Here’s how to do it:

            Formatted: http://pastebin.com/m8hYPSrw

            //########## CLIENTSCRIPT ##########

            var CURRENTRECORDMODULE;
            define([‘N/currentRecord’], runClientscript);

            function runClientscript(currentRecord){
            CURRENTRECORDMODULE = currentRecord;

            //*********** HELPER FUNCTIONS ***********
            function create_amort_schedule() {
            var currentRec = CURRENTRECORDMODULE.get();
            var v_loan_pymt_mthd = currentRec.getValue({
            fieldId:’custrecordpfg_adv_loan_pymt_type’
            });
            alert(v_loan_pymt_mthd);
            return;
            }

            var returnObj = {};
            returnObj.create_amort_schedule = create_amort_schedule;
            return returnObj;
            }

            //########## USEREVENT ##########
            var WIDGETMODULE;
            /**
            *@NApiVersion 2.x
            *@NModuleScope Public
            *@NScriptType UserEventScript
            */
            define([‘N/ui/serverWidget’], runUserEvent);

            function runUserEvent(widget) {
            WIDGETMODULE = widget;

            var returnObj = {};
            returnObj.beforeLoad = beforeLoad;
            return returnObj;
            }

            function beforeLoad(context) {
            if (context.type == context.UserEventType.VIEW) {
            context.form.addButton({
            id : ‘custpage_some_button’,
            label : ‘Schedule’,
            functionName : ‘create_amort_schedule’
            });
            }
            return;
            }

  • Dilip DiLee

    Can i get some Sample code on Restlet ? Example: Like creating Employee/customer

    • Sure, I will post it later in the week, I have been pretty busy lately.

      • Dilip DiLee

        ok Thankyou

      • Kumar Watson Agarwal

        Hi Adolfo, did you ever get the chance to post some RESTlet examples or tutorials? I can get a RESTlet in suitescript 2.0 to accept a GET, but I can’t get it to work on a POST.

        • Sorry about that, I just updated the post and included a RESTlet example now.

  • Hernan Orozco

    Hey! I need to use the recordType and the recordId in a Suitelet, I’m currently loading this suitelet in a iframe from a user event script 1.0, I’m passing the recordType and recordId as ur params from that script, but when I’m requesting the url params in the suitelet 2.0 (context.request.params) they are not comming.

    • In SS2.0 the correct way is using context.request.parameters .If that doesnt help then stringify the whole request and see if you can find anything that can help you.

  • Dilip DiLee

    Hi adolfo
    im trying add a line value in vendor record subsidiary sublist in edit mode ( Standard Mode). which has one line
    Line count i got it as Length : 1

    from Second line im trying to set line value.

    please find the below code

    var assigned_subsidiary_count = objRecord.getLineCount({
    sublistId : ‘submachine’
    });
    log.debug({
    title : “assigned_subsidiary length”,
    details : assigned_subsidiary_count
    });

    while (itemIndex < len) {

    objRecord.setSublistValue({
    sublistId : 'submachine',
    fieldId : 'subsidiary',
    line : lineIndex,
    value : res[itemIndex]
    });

    itemIndex++;
    lineIndex++;

    }

    This Code works properly when i open a vendor in create Mode.

    But in edit mode i'm facing problem its
    NOTE : vendor record is getting saved but its not setting the subsidiary value

  • Dilip DiLee

    Hi adolfo

    Can i know the actual difference between ScriptContext,newRecord and OldRecord When i use it userEvent scripts ( If scriptContext.type == create/edit )

    it would be great if i have simple example

    Thank you

    • Sure, so basically these are the gotchas:

      beforeLoad:
      oldRecord – Doesnt exist at all on beforeLoad

      beforeSubmit:
      oldRecord – Doesnt exist on CREATE

      afterSubmit:
      oldRecord – Doesnt exist on CREATE
      newRecord – Doesn’t exist on DELETE

      • Dilip DiLee

        Sorry Adolfo.
        can you be more specific or some example so that practically i can experience it and understand

        • Sorry, I can’t think of anything more specific. Try going over the scenarios above. For example: Try creating a user event beforeLoad and load the oldRecord and you’ll see what I am talking about.

          • Dilip DiLee

            thank u

    • To clarify, if you are creating a new record there would be no old record since the record hasn’t been committed to the database. As for when you are deleting a record, there is no newRecord on afterSubmit because the record has been deleted.

  • Dilip DiLee

    Hi adolfo,

    how can i find total number of records in JE or any records byCODE.
    Example : to know the counts of each and every record.

    • The easiest is by creating a saved search and summarize the column by COUNT. Then use the following chrome extension to export the saved search to code: https://goo.gl/hrsDfj

  • Ruby RK

    When i deploy CS (onSave) and UE (beforeSubmit) on the same record which will trigger first and why can u say?

    • CS on save will trigger first since this is happening on clientside. UE happens on serverside so that get’s triggered after the data has been sent by the client.

      • Ruby RK

        Thanks Adolfo Garza. Good work!

      • Ruby RK

        Does each method of CS and UE have individual governance unit? if yes can u please tell ?

        • Dang, I missed this question. Sorry about that. Yes, CS and UE have their own separate governance units.

  • Dilip DiLee

    Hi adolfo

    can i know how to make use of HTTPS module

    im thinking to make a call to suitelet from userevent script by passing some query string to it

    it would be great if i get some example on this

    • Sure, it works like this:

      var myrequest = {};
      myrequest.url = ‘https://XXXXX.com:’;
      myrequest.method = HTTPSMODULE.Method.GET;
      var myresponse = HTTPSMODULE.request(myrequest);
      log.debug(‘Body’, myresponse.body);

      • Dilip DiLee

        How can i send some parameters/Query String to that URL or

        • Dilip DiLee

          I’m able to figure it out now its working nice now

          • Can i make use of Http module in clientside script
            ?

          • Adolfo Garza

            Yes

          • Hi
            I’m not able to set createdfrom field by script.

            my script creates JE successfully but not setting the CreatedFrom, i have passed the proper value to it.

          • Hmmm… what’s the field id of that created from field? Is that a custom field? Some accounts use their own custom CreatedFrom field so double check the fieldid.

          • Its a standard field

          • Sorry, I never had that issue. Try asking that in the user community forums.

  • Charu Saklecha

    Hello all!
    I am very new to NetSuite, and it seems very confusing. I need to build Custom Forms or rather need to customize certain built-in NetSuite forms by embedding JavaScripts codes. In other words, I want to display a new HTML form on the change event of a field and I think I need to use fieldChanged and postSourcing methods (but don’t know how to use it), i.e. a new form should pop as soon as I change a field in a transaction form, say Status= “Won”. I get the whole idea on how to do things theoretically, but the problem is coming when I am actually coding it, since NetSuite has it owns tags for HTML and JavaScript elements & functions which I am having trouble with. I have seen Eric T. Grubaugh ‘s videos and read various articles but no luck. I am really stuck.
    Kindly help, I will be really grateful.

    • Something like this should work, just replace the url with the form url:

      Note: I didn’t test it so you may need to debug it.

      https://pastebin.com/myU4i1Bb

      /**
      *@NApiVersion 2.x
      *@NModuleScope Public
      *@NScriptType ClientScript
      */
      define([], runClientscript);

      function runClientscript(){
      //*********** HELPER FUNCTIONS ***********
      function fieldChanged(context) {
      if(context.fieldId == ‘status’){
      var status = context.currentRecord.getValue(‘status’);
      if(status == ‘Won’){
      window.open(“https://www.ursuscode.com”);
      }
      }

      alert(“fieldChanged Triggered!”);
      return;
      }

      var returnObj = {};
      returnObj.fieldChanged = fieldChanged;
      return returnObj;
      }

  • Pingback: Social shares tool()

  • Pingback: porn()

  • Pingback: juegos friv()

  • Pingback: law diyala()

  • Schuyler

    This is great! Thank you! Can you help with this one request I have? I need to set the field display type of a custom transaction column field based on the choice from two drop down menus. Like “If this AND this, then this” type of deal. However, Netsuite native workflows do not allow you to run workflows on transaction column fields, hence the need for suitescript. I have NO idea where to start, though!

    • You can hide the column fields by modifying the form on a User Event Before Load like this:

      var itemField = context.form.getSublist({id: ‘item’}).getField({id: ‘item’});
      itemField.updateDisplayType({
      displayType : SERVERWIDGET.FieldDisplayType.HIDDEN
      });

      The data must be saved already. I believe you can also modify it from clientscript if the field was added by a User Event script, you may want to try that.

  • Pingback: engineering()

  • Pingback: Look At This()

  • Umesh

    Hi Adolfo,
    First of all thanks for such a helpful and simple sample code.
    I am little with familer with SuiteSript 1.0, but not using SS 2.0. can you please suggest me if there is any way to get all the fields with their type of particular record using SS 2.0

  • Pingback: try this out()

  • Pingback: lose weight kg in lbs table()

  • Pingback: DMPK()

  • Pingback: how to make money with a iphone()

  • Pingback: Aws coehuman Diyala()

  • Pingback: GVK BIO()

  • Hi adolfo

    can i know import Gift Certificates if yes can i know how or any other options available.

  • Pingback: Aplikasi klinik()

  • Pingback: find a real estate agent()

  • Pingback: apoio informático()

  • Pingback: how to make money with a iphone()

  • Pingback: http://unbended.wiki/index.php/Direct_response_ppc_guaranteed()

  • Pingback: Mt ea()

  • Pingback: look at this website()

  • Pingback: 먹튀검증()

  • Pingback: SEO Agency()

  • Pingback: pendaftarancpns2018()

  • Bhushan Deshpande

    Hi adolfo,
    I am trying to create assistance page in 2.0 .
    when i am trying to click on next step not abel to show next steps fileds.
    Do have any sample code in 2.0 to create assistance page having at least 4 steps.

  • Pingback: 루비게임 엘리트게임 루비게임주소()

  • Pingback: deer valley real estate()

  • Kaul Shishir

    Can you help me with the code of Page Init:-
    On creation of new sales order record default the sales order page to a particular customer!

    • Something like this:
      function pageInit(context) {
      if (context.mode == ‘create’) {
      context.currentRecord.setValue({
      fieldId: ‘entity’,
      value: 123456789
      });
      return;
      }
      }

      • Kaul Shishir

        Thanks Adolfo.
        Can you help me with Line Init ?
        I want to default an item in the line items (say description or even tax or rate), once the customer is selected (Under entry ‘Orders’) .

        • You wouldn’t use Line Init for this. You would use field changed to listen to customer field changes and then loop through the items and set the description or whatever field you want to default.

          • Kaul Shishir

            Ohh! Okay! Thanks 🙂

  • Pingback: essayforme()

  • Pingback: More about Sunil()

  • Pingback: writeaessay()

  • Pingback: Array Questions()

  • Pingback: online class help()

  • Pingback: sciroxx trenadex enanthate 200()

  • Pingback: Online Reputation()

  • Pingback: Pe bile exercisespenis Enlargement Bible Review()

  • Pingback: Banja Luka()

  • Pingback: lowongan.cpns 2018()

  • Abhishek Pandey

    can some one explain what is wrong with this code,I am not able to redirect to the suitelet… I am getting the first alert but not redirecting to the suitelet.

    function print() {

    var parameters = “”;
    try {
    alert(‘suiteletURL Inside Try’);
    var suiteUrl = url.resolveScript({
    scriptId: ‘customscript_abc’,
    deploymentId: ‘customdeploy_abc’,
    returnExternalUrl: false,
    params: parameters
    });

    alert(‘suiteletURL outside Try’);
    var response = https.get({
    url: suiteUrl
    });

    }
    catch(e) {
    log.error(e.toString());
    }

    }

  • Pingback: latestvideo sirius289 abdu23na7426 abdu23na63()

  • Pingback: latestvideo sirius460 abdu23na1160 abdu23na8()