How to Populate a Field with Random Numbers in NetSuite

Populating fields with random numbers in NetSuite is used for various scenarios such as assigning unique identifiers or performing random sampling. Here are two methods to achieve this: using “Field Defaults” and using a Script.

Method 1: Using Field Defaults

Navigate to Transaction Body Fields:

Go to Customization > Lists, Records, & Fields > Transaction Body Fields > New.

Create a New Field:

Type: Select “Integer Number”.

Set Display Properties:

Click on the Display tab.

Display Type: Select “Hidden”.

Set Validation and Defaulting:

Click on the Validation & Defaulting tab.

Formula: Enter DBMS_RANDOM.VALUE(1, 10000) to generate a random number between 1 and 10,000.

Save:

Click Save to create the field.

This method automatically populates the field with a random number whenever a transaction is created or edited.

Method 2: Using a Script

Create a User Event Script:

Create a new JavaScript file with the following content:

/**
 * @NApiVersion 2.x
 * @NScriptType UserEventScript
 */
define(['N/record', 'N/log'], function(record, log) {

  function afterSubmit(context) {
    var newRecord = context.newRecord;

    // Generate a random number between 0 and 9999
    var randomNum = Math.floor(Math.random() * 10000);

    // Update the record with the random number
    var updatedRecordId = record.submitFields({
      type: newRecord.type,
      id: newRecord.id,
      values: {
        custfield_random_number: randomNum // Replace with your actual custom field ID
      }
    });

    log.debug('Record Updated', 'Record ID: ' + updatedRecordId + ' with Random Number: ' + randomNum);
  }

  return {
    afterSubmit: afterSubmit
  };
});

Deploy the Script:

Go to Customization > Scripting > Scripts > New.

Upload the script file and define it as a User Event Script.

Associate the script with the desired record type(s) (e.g., Sales Order, Invoice).

This method runs the script after a record is submitted, generating and populating a random number in the specified field.

Leave a comment

Your email address will not be published. Required fields are marked *