Client SuiteScript
Developer’s Guide
Copyright NetSuite, Inc. 2005 All rights reserved.
Client SuiteScript Developer’s Guide
January 18, 2007
This document is the property of NetSuite, Inc., and may not be reproduced in whole or in part without
prior written approval of NetSuite, Inc.
Trademarks
NetSuite, NetERP and NetCRM are provided by NetSuite, Inc, and NetSuite is a trademark of NetSuite, Inc.
Oracle is a registered trademark of Oracle Corporation.
Other product names mentioned in this document may be trademarks, servicemarks, or tradenames of
their respective companies and are hereby acknowledged.
Contents
Chapter 1
Welcome
In This Guide . . . 1
Roles & Permissions . . . 1
Chapter 2
Using Client SuiteScript
General Guidelines. . . 3Getting Started . . . 4
Enabling the Client SuiteScript Feature and Preferences . . . 4
Field Names (IDs) . . . 5
Attaching Client SuiteScripts to Forms . . . 5
Functions. . . 6 PageInit . . . 7 SaveRecord . . . 8 PostSourcing . . . 9 ValidateField . . . 9 FieldChanged . . . 10
Client SuiteScript API . . . 10
Using the Fire Field Changed Parameter . . . 13
Working with Line Items . . . 14
Chapter 3
Client SuiteScript Tutorial
Customizing the Page Load . . . 16Setup . . . 16
Create the Code . . . 16
Test the Code. . . 17
Validating Field Values . . . 18
Setup . . . 18
Create the Code . . . 19
Test the Code. . . 20
More Validation . . . 21
Triggering Events when a Field is Changed . . . 21
Setup . . . 21
Create the Code . . . 22
Test the Code. . . 22
Validating a Line Item. . . 23
Setup . . . 23
Create the Code . . . 23
Recalculating Field Totals. . . 24
Setup . . . 24
Create the Code . . . 25
Test the Code. . . 25
Prompting before Save . . . 26
Create the Code . . . 26
Test the Code. . . 26
Chapter 4
Code Names
Code Names by Record Type . . . 28Case Record . . . 28 Contact Record. . . 29 Customer Record . . . 30 Employee Record . . . 31 Event Record . . . 34 Partner Record . . . 34 Task Record . . . 35 Vendor Record . . . 35 Opportunity Record . . . 36
Code Names by Field Type . . . 38
Entity Fields . . . 38
CRM Fields . . . 42
Item Fields . . . 44
Transaction Fields . . . 48
Chapter 1 Welcome
Welcome to NetSuite’s Client SuiteScript feature. With Client SuiteScript you can write custom
JavaScript code that performs validations and calculations on forms. You can use custom code
in combination with custom fields, forms and records to completely tailor your business
management system to your individual business needs.
The purpose of this guide is to introduce you to NetSuite Client SuiteScript tools. It provides
step-by-step instructions on how to create and implement Client SuiteScript for your forms as
well as real-world examples for how companies use custom code to customize NetSuite
accounts for their businesses. Client SuiteScript requires an understanding of JavaScript code
and is intended to be used by customers with some advanced programming knowledge only.
Note: When using Client SuiteScript, you will need to create custom fields, forms and records. For more information on the complete customization features available in your NetSuite account, refer to the Customization Guide.In This Guide
This guide contains the following chapters:
Chapter 1 "Welcome"
: provides an overview of this guide. Describes which roles in your
company can access Client SuiteScript.
Chapter 2 "Using Client SuiteScript"
: introduces Client SuiteScript and its uses. Provides
instructions for turning the feature on. Describes each function and possible API call that can
be invoked.
Chapter 3 "Client SuiteScript Tutorial"
: provides a detailed example of how to use Client
SuiteScript to control the behavior of item discounts in a custom Cash Sale Transaction Form.
Chapter 4 "Code Names"
: provides tables that detail standard field names that can be used in
Client SuiteScript.
"Appendix: Tutorial Code"
: provides the complete code for the example use case created in
Chapter 3 "Client SuiteScript Tutorial"
.
Roles & Permissions
NetSuite provides many standard roles with predefined permissions. A role is a set of
permissions that lets customers, vendors, partners and employees access specific areas of your
data. Each role grants access at a certain level for each permission.
Access to the Client SuiteScript feature is also controlled using roles and permissions. There are
seven standard roles that have access to custom code as outlined in the following table. Refer to
this table when assigning employees and vendors the task of implementing Client SuiteScript
for the part of NetSuite they or their teams work with.
Welcome
Roles & Permissions
2
Note: Depending on the product you subscribe to, all of these roles may NOT be available for you to use. Also, in addition to the following standard roles there may be custom roles created with
Client
SuiteScript
permissions assigned to them. To create a custom role, an administrator must go to Setup > Users/Roles > Manage Roles. When customizing a role to addClient SuiteScript
capabilities, you must also add permission for customizing entry forms and transaction forms.Roles Access Level
Administrator FULL
Full Access FULL
Marketing Manager FULL Marketing Administrator FULL
Sales Manager FULL
Sales Administrator FULL Support Administrator FULL
Chapter 2 Using Client SuiteScript
This section describes the event functions that can be modified and the API calls that can be
used in Client SuiteScripts. These scripts are supported across NetSuite versions as long as the
procedures and guidelines provided in this guide are adhered to.
Note: NetSuite Client SuiteScript does NOT support JavaScript code using the Document Object
Model (DOM) to interact with the objects on the web page.
Currently, you can provide custom JavaScript functions to handle the following events:
•
Initializing forms
•
Entering or changing a value in a field (before and after it is entered)
•
Entering or changing a value in a field that sources another field
•
Selecting a line item
•
Adding a line item (before and after it is entered)
•
Saving a form
•
Searching for another record
•
Loading, saving or deleting a record
•
Sending an email
If desired, functions that save or validate events can abort the action.
General Guidelines
Following are some general guidelines to follow when working with NetSuite Client
SuiteScript.
Important: During testing of Client SuiteScript, use Ctrl-Refresh to clear your cache and ensure that the latest scripts are being executed.
•
Always thoroughly test your code before using on your live NetSuite data.
•
If the same code is being used across multiple forms, ensure that you test any changes
in the code for each form that the code is associated with.
•
Ensure that you test your code for the roles that will be using the forms that the code is
associated with. Keep in mind that form definitions may change for different roles
such that certain fields may become available or unavailable for certain roles.
•
Wherever data may be inconsistent, not available, or invalid for certain functions,
ensure that you include proper error handling sequences in your script. For example, if
your script requires a field value in order to validate another, ensure that the field value
is available.
Using Client SuiteScript
Getting Started
4
•
Organize your code into reusable chunks. Many functions can be used in a variety of
forms. Any reusable functions should be stored in a common library file and then
called into specific event functions for the required forms as needed.
•
Since name values can be changed, ensure that you use
static
ID values in your API
calls where applicable.
•
Although you can use any desired naming conventions for functions within your code,
it is recommended that the top level functions include an indication of the
corresponding NetSuite function. For example, if you are creating a Page Init function,
you could name the function pageInit or formAPageInit. If your code is already
established, you could simply wrap it with a top level function that has the appropriate
naming convention.
•
As with any script, ensure that you thoroughly comment your code. This will not only
help with debugging and development but will assist NetSuite support in locating
problems if necessary.
Getting Started
Before describing the nuances of creating javascript files for use with your NetSuite forms,
review the information provided in this section so that you understand how the code will be
implemented.
Enabling the Client SuiteScript Feature and Preferences
Before beginning with Client SuiteScript, you should enable the Client SuiteScript feature and
enable the preference that causes NetSuite to display internal IDs.
•
Enabling the Client SuiteScript Feature
: Go to Setup > Company > Enable Features
and check Client SuiteScript on the General tab. Once enabled, the Client SuiteScript
feature provides a new folder in the file cabinet at Documents > Files > SuiteScripts. A
custom code tab is also available in custom entry and transaction forms. Here you can
define which scripts to associated with the current form.
•
Displaying Internal IDs (nsKeys)
: Go to Home > Set Preferences and check Show
Internal IDs. When Show Internal IDs is checked, the
internalId
values for records are
displayed in the Internal ID column of record lists.
When referencing records in your custom code, always use the internal ID values since
the internal IDs are constant but the records themselves may be renamed. For example,
to determine if a selection in a drop down is specific value, without worrying if that
value has been renamed, refer to the internal ID of the record — not the text name.
Note: The internal ID of a record and a field ID are two different things. Field IDs must be used when calling a field from any custom code API. Field IDs are displayed in the ID column of any lists of fields such as at Setup > Customization > CRM Fields. Record internal IDs are unique IDs associated with a record at creation time. Internal ID values should be used when referencing a specific field value.Using Client SuiteScript
Getting Started
5
Field Names (IDs)
Field names (or IDs) must be used when calling a field from any SuiteScript API. Standard field
names are provide in
Chapter 4 "Code Names"
. Custom Field IDs are displayed in the ID
column of any lists of fields. For example, to obtain the field ID for a specific custom CRM
field, go to Setup > Customization > CRM Fields.
Note: When creating custom fields, the custom field ID can be specified or you can accept the default ID assigned by NetSuite. To ensure that the field IDs make sense in the context of your business environment, it is recommended that you always define your own custom field IDs. This will also help to make your custom code more readable. For detailed information on creating custom fields and assigning custom field IDs refer to the Customization User Guide.
Attaching Client SuiteScripts to Forms
After you have created your Client SuiteScript scripts, you need to make the scripts available
for custom forms and define which forms will use which functions.
Important: SuiteScripts must have a .js extension.
To attach your script files to a custom form:
1.
Upload your scripts to your NetSuite file cabinet.
Click Documents > Files > SuiteScripts, navigate to your script file, and click attach.
Note:
The SuiteScripts folder is provided for convenience; you can store the script files
in any location.
2.
Go to the desired custom form.
Client SuiteScript can only be attached to custom Entry or Transaction forms. Click
Setup > Customization >
[Form]
. Then click edit next to the desire custom form or
click Customize next to an existing standard form in order to create a new custom
form based on it.
Note:
For detailed information on creating custom forms, refer to the
Customization
User Guide
.
Using Client SuiteScript
Functions
6
3.
In the custom code tab, select the script file and library script file to associate to the
current form.
The library script file should contain any commonly used functions whereas the script
file should contain functions specific to the current form.
4.
Enter the
exact
name of your function that correlates to each NetSuite function.
When a Client SuiteScript script is called for a form function, the actions defined
within the SuiteScript file, as well as any NetSuite actions, are performed for the given
function. For example, if your form calls a custom PageInit function, the actions
defined by that script, as well as any predefined NetSuite actions, are performed prior
to the page loading.
Functions
NetSuite provides several standard functions that are automatically triggered with certain
events as outlined in the following table.
Function Parameters Returns Description
PageInit Called when the page is first loaded.
SaveRecord Boolean Called when the user requests the form to be saved. Returns false to reject the operation.
ValidateField* line item type: String; field name: String
Boolean Called when the user changes the value of a field. Returns false to reject the value. This script does NOT apply to dropdown select or check box fields.
FieldChanged* line item type: String; field name: String
Called when a new value for a field is accepted.
PostSourcing type: String field name: String
Called on the FieldChanged event after all slaved fields source.
Line Init line item type: String Called when an existing line is selected in the item machine. The string value returned is always item.
Using Client SuiteScript
Functions
7
PageInit
The PageInit function is called when the form is first loaded. Some functions that can be
performed on PageInit include the following:
•
Populate field defaults
•
Disable or enable fields
•
Change field availability or values depending on the data available for the record
•
Add flags to set initial values of fields
•
Provide alerts where the data being loaded is inconsistent or corrupt
•
Retrieve user login information and change field availability or values accordingly
•
Validate that fields required for your custom code (but not necessarily required for the
form) exist
Examples
Set Default Field Values for a Field
function pageInit() {
// is fieldA is either NULL or equal to "valueA"
if ((nlapiGetFieldValue('fieldA').length == 0) || (nlapiGetFieldText('fieldA') == "valueA"))
{
// then set fieldA to valueB
nlapiSetFieldText('fieldA', nlapiGetFieldText('valueB')); } }
Disable a Field
function pageInit() {// On init, disable two optional Other fields: fieldA and fieldB. nlapiDisableField('custrecord_other_fieldA', true);
nlapiDisableField('custrecord_other_fieldB', true); }
Display User Profile Information
function pageInit() {
// On page init display the currently logged in User's profile information. // Set variables
var userName = nlapiGetUser(); // entity id of the current user var userRole = nlapiGetRole(); // id of the current user's role var userDept = nlapiGetDepartment(); // id of the current user's department var userLoc = nlapiGetLocation(); // id of the current user's location
Validate Line line item type: String Boolean Called when a user requests the addition or edit of a line item. Returns false to reject the operation. Recalc line item type: String Called when a new or edited line has been accepted. *The ValidateField and FieldChanged scripts require a null line item for body form fields.
Using Client SuiteScript
Functions
8
// Display information
alert("Current User Information" + "\n\n" + "Name: " + userName + "\n" + "Role: " + userRole + "\n" + "Dept: " + userDept + "\n" + "Loc: " + userLoc ); }
SaveRecord
The SaveRecord function is called when the user requests the form to be saved. Returns false to
reject the operation. Use the Save function to provide alerts to the user before committing the
data. If it is necessary for the user to make changes before comitting the data, return false —
otherwise display the alert, return true and allow the user to commit the data.
You can also use the SaveRecord function to:
•
Enable fields that were disabled with other functions
•
Redirect the user to a specified url
Examples
Requesting Additional Information
function SaveRecord() {
// Check to see that fieldA is populated. If not, block the save and warn with a popup.
if (String(nlapiGetFieldValue('fieldA')).length == 0) {
alert("Please provide a value for fieldA"); return false;
}
alert("Are you sure you want to Save the record?"); return true;
} }
Redirect the User to Another Location
function saveRecord(type,name) {
window.open('https://system.netsuite.com/[url string]');void(0) return true;
Using Client SuiteScript
Functions
9
PostSourcing
(Transaction Forms Only)
The PostSourcing function is called when a field is modified that sources information from
another field. Event handlers for this function behave similar to event handlers for the Change
Field function except that the function is called only after all sourcing is completed — it waits
for any slaved or cascaded field changes to complete before calling the user defined function.
Therefore, the event handler is not triggered by field changes for a field that does not have any
slaved fields.
If there is at least one field sourced from a drop down (either a built-in sourcing or one created
through customization) the post sourcing event is fired. Therefore, if you need to do
something based on sourced values, you should do it in PostSourcing rather than from Field
Changed.
ValidateField
The ValidateField function is called whenever the user
changes
the value of a field. This
function returns false to reject the value.
Note: This script does NOT apply to dropdown select or check box fields.
Use the ValidateField function to validate field lengths, restrict field entries to a predefined
format, restrict submitted values to a specified range, validate the submission against entries
made in an associated field,
Examples
Validate Field Lengths
function ValidateField(type, name) {
// if fieldA is not greater than 5 characters, fail validation if (name == 'fieldA')
{
var fieldALength = String(nlapiGetFieldValue('fieldA')).length; if (fieldALength <= 6)
{
alert("FieldA must be at least 6 characters."); return false;
} }
// Always return true at this level, to continue validating other fields return true;
Using Client SuiteScript
Client SuiteScript API
10
FieldChanged
The FieldChanged function is called when a new value for a field is
accepted
. Use the
FieldChanged function to provide the user with additional information based on user input,
disable or enable fields based on user input.
Examples
Requesting Additional Information
function FieldChanged(type, name) {
// Prompt for additional information, based on values already selected. if (name == 'fieldA') && (nlapiGetFieldText('fieldA') == "Other")
{
alert("Please provide additional information about fieldA in the text field below.");
} }
Client SuiteScript API
This section describes the API calls that your Client SuiteScript can invoke to retrieve and
modify information on forms. These API calls can only be invoked when an event triggers the
custom code functions that have been assigned to the current form. Each call acts on standard
or custom fields defined for the current form.
For a complete list of standard fields available on standard NetSuite forms, see
“Code Names”
on page 27
. NetSuite is committed to maintaining these field names across versions. In rare
cases where field names must be changed, the name changes will be documented in the release
notes for that version of the software.
Important: You can NOT modify the values of the following standard fields with Client SuiteScript.
•
Amount
•
Applied
•
Unapplied
•
Total
•
Exchange Rate
•
Shipping Cost
•
Last Modified Date
•
Creation Date
•
Return on Investment
Using Client SuiteScript
Client SuiteScript API
11
Function Parameters Description
nlapiGetFieldValue field name: String Retrieves the value of the given field. nlapiSetFieldValue field name: String;
value: String;
firefieldchanged: Boolean
Sets the value of the given field. See also
“Using the Fire Field Changed Parameter” on page 13
nlapiGetCurrentLineItemValue line item type: String; field name: String
Retrieves the value of the given line-item field before it has been added to the form. Typically used in validate line functions. nlapiSetCurrentLineItemValue line item type: String;
field name: String; value: String
firefieldchanged: Boolean
Sets the value of the given line-item field before it has been added to the form. Typically used in validate line functions. See also “Using the Fire Field Changed
Parameter” on page 13
nlapiGetLineItemValue line item type: String; field name: String; line index: Integer
Retrieves the value of the given field on the line item at the given index.
Note: You cannot set default line item values when the line is not in edit mode.
nlapiSetLineItemValue line item type: String; field name: String; line index: Integer; value: String
Sets the value of the given field on the line item at the given index. Currently, you can use this only to write to description or custom fields. To write to other fields, use the method described at “Example: Adding Line Items to a Transaction” on page 14.
nlapiGetCurrentLineItemIndex line item type: String Retrieves the current index of the line being added or edited. If adding, the function should nlapiGetLineItemCount(type)+1. nlapiGetLineItemCount line item type: String Retrieves the total number of line items for
the given type.
nlapiFormatCurrency amount: Float Formats a floating point value according to the prevailing currency conventions. nlapiStringToDate string: Date Converts a JavaScript string to a Date
according to date formatting conventions. nlapiDateToString date: Date Converts a JavaScript Date to a string
according to date formatting conventions. nlapiAddDays date: Date; days: Integer Adds a set number of days to a JavaScript
date, returning the modified object. nlapiAddMonths date: Date;
months: Integer
Adds a set number of months to a JavaScript date, returning the modified object.
nlapiGetFieldText field name: String Gets the text value of the given selection field.
Important: nlapiGetFieldText can NOT be used on hidden fields.
Using Client SuiteScript
Client SuiteScript API
12
nlapiGetCurrentLineItemText line item type: String; field name: String firefieldchanged: Boolean
Gets the text value of the given line-item selection field in the form before it has been added. Typically used in validate line functions. See also “Using the Fire Field Changed Parameter” on page 13
nlapiGetLineItemText line item type: String; field name: String; line index: Integer
Gets the text value of the given selection field on the line item at the given index.
nlapiSetFieldText field name: String; text value: String firefieldchanged: Boolean
Sets the value of the given selection field to the value with the given text. See also “Using the Fire Field Changed Parameter” on page 13
nlapiSetCurrentLineItemText line item type: String; field name: String; text value: String
Sets the value of the given line-item selection field to the value with the given text.
nlapiDisableField field name: String; value: Boolean
Sets the given field to disabled or enabled based on the value (true or false).
nlapiDisableLineItemField line item type: String; field name: String; value: Boolean
Sets the given line item field of the given type to disabled or enabled based on the value (true or false).
nlapiEncrypt Clear Text: String Returns an encrypted string for the given input string.
nlapiGetUser N/A Returns the entity ID of the current user. nlapiGetRole N/A Returns the ID of the current user’s role. nlapiGetDepartment N/A Returns the ID of the current user’s
department.
nlapiGetLocation N/A Returns the ID of the current user’s location. nlapiSelectLineItem line item type: String
line item number: String
Selects an existing line number of a machine. Line number must be between 1 and nlapiGetLineItemCount.
nlapiCommitLineItem line item type: String Commits the current line of a machine type. This is the equivalent of clicking Done for a line item in the UI.
nlapiInsertLineItem line item type: String Inserts a line above the current line of machine.
nlapiRemoveLineItem line item type: String Removes the current line of a machine. nlapiCancelLineItem line item type: String Cancels any edits to the current line of a
machine and reselects the line. nlapiSelectNewLineItem line item type: String Synonym for nlapiCancelLineItem.
nlapiIsLineItemChanged line item type: String Returns true if the currently selected line of machine has been edited.
nlapiLoadRecord type: record type id: internalID
Loads an existing record.
Using Client SuiteScript
Client SuiteScript API
13
Using the Fire Field Changed Parameter
When creating scripts that provide the ability to watch a field for a change, and then write back
to the field that just changed, a risk of creating a unending loop exists as follows:
1.
The Client SuiteScript code watches for fieldA to change.
2.fieldA changes.
3.
The Client SuiteScript writes to fieldA, causing the Field Changed event to fire,
returning the code to step
2
, and this loop repeats indefinitely.
To prevent this looping behavior, you can set the optional
firefieldchanged
parameter in your
custom code.
The firefieldchanged parameter is available for all write functions. If set to True, the parameter
causes any field changed events to fire as normal. This is the default setting. If set to False, field
changed events are NOT fired.
Using the new parameter, we can modify the above example to:
1.Custom code watches for fieldA to change.
2.
fieldA changes.
3.
Client SuiteScript writes to fieldA using firefieldchanged = false, so the Field Changed
event does not fire.
The following API calls can set the fireFieldChanged parameter.
nlapiSaveRecord type: record type id: internalID
Saves the current record.
nlapiCreateRecord type: record type Creates a new record instance. nlapiSearchRecord type: record type
searchId: saved search ID
Allows you to search for other records in the system.
nlapiDeleteRecord type: record type id: internalID
Permanently deletes a record from the database.
nlapiSendEmail author: author internalID (must be an employee record)
recipient: recipient internalID
subject: email subject body: email body copy[ ] : array of e-mails to copy
blindcopy[ ]: array of emails to blind copy
Generates and sends an email.
Using Client SuiteScript
Client SuiteScript API
14
Note: The set line item text and value functions are NOT affected, as these do not currently call field changed after firing.
•
nlapiSetFieldValue(field, value, firefieldchanged)
•
nlapiSetFieldText(field, text, firefieldchanged)
•
nlapiSetCurrentLineItemValue(type, field, value, firefieldchanged)
•
nlapiSetCurrentLineItemText(type, field, text, firefieldchanged)
Note: The fireFieldChanged parameter is provided for convenience. To prevent this loop, you could also include code that either checks to ensure that you are not writing the same value to the field or that tracks whether you just wrote to the field.
Working with Line Items
NetSuite provides several functions that can be used to manipulate line items in a machine. You
can use these functions to update multiple line items in a machine when a body field is changed
or to automate the population of item machine fields when certain conditions exit in the form.
Line item functions include:
•
nlapiSelectLineItem
•
nlapiCommitLineItem
•
nlapiInsertLineItem
•
nlapiRemoveLineItem
•
nlapiCancelLineItem
•
nlapiSelectNewLineItem
•
nlapiIsLineItemChanged
Important: Once the code associated with a line item function is initiated, mouse events will NOT be responded to until the code is complete. This includes extended delays such as when an alert or prompt is thrown while the line is being manipulated by the code.
Example: Adding Line Items to a Transaction
In order to add a line item to a transaction using custom code, you need to insert the line item
and then commit the item in the same script. If you set the item field via
nlapiSetCurrentLineItemValue, you can't call nlapiCommitLineItem until the server call for
the item information has completed. The only way to know that the server call is complete is to
create a postsourcing function that sets a flag.
For example, suppose that you want to insert a shipping line when a user clicks a button. You
could attach a function such as insertShippingRate() to that button, which adds an item named
“Shipping”, sets its rate, and then commits the line.
function insertShippingRate() {
nlapiSelectNewLineItem('item');
/* important so that we know that we were called from insertShippingRate(). */ nlapiSetCurrentLineItemValue('item', 'custcolinsertshippingrate', 'T');
Using Client SuiteScript
Client SuiteScript API
15
function doPostSourcing(type, fldname) {
if ( type == 'item' && fldname == 'item' && nlapiGetCurrentLineItemValue ('item', 'custcolinsertshippingrate') == 'T' ) { nlapiSetCurrentLineItemValue('item', 'custcolinsertshippingrate', 'F'); nlapiSetCurrentLineItemValue('item', 'rate', '7.50'); nlapiCommitLineItem('item'); } }
Chapter 3 Client SuiteScript Tutorial
This tutorial provides a detailed example of how to use Client SuiteScript to control the
behavior of item discounts in a custom Cash Sale Transaction Form. It is intended for use with
NetSuite’s sample company, Wolfe Electronics. You can access Wolfe Electronics by signing up
for a Test Drive on the NetSuite Web Site. However, instructions are included to implement the
example in an account without Wolfe Electronics data if you wish.
We will start by describing the code to be used when the page first loads, then move on to field
changed, validation and page save code. For each section, you may need to create custom
elements as described in the Setup sections. If you are familiar with creating custom items, lists
and fields, simply refer to the table provided for the required parameters for each element.
Otherwise, refer to the
Customization User Guide
or the online help for detailed instructions.
These fields must exist in your NetSuite account prior to using this example. If the items and
fields do not exist, you will receive an error when attempting to use your custom cash sale.
Note: Before beginning this tutorial, ensure that you have enabled the Client SuiteScript feature as described in “Enabling the Client SuiteScript Feature and Preferences” on page 4.Customizing the Page Load
In the Page Init example, we will cause a 5% transaction discount to be automatically applied to
the cash sale price of an item whenever our custom Cash Sale Transaction form is loaded.
Setup
Before creating a script that applies a discount, we must first create a discount item in NetSuite
and then use this discount item in our custom code.
Create the Code
Next we will create a javascript file called
customCashSales.js
and enter the following code.
This code sets the discount item field to the value created in
Setup
.
function samplePageInit() {
nlapiSetFieldValue('discountitem', 144); }
Element Parameters Purpose
Discount Item Item Name/Number: In-store Discount
Income Account: 4000 Sales Rate: 5%
Apply Before Sales Tax: No
Defines the discount item that you will refer to in your custom code.
To create, go to Lists > Accounting > Items > New > Discount.
Client SuiteScript Tutorial
Customizing the Page Load
17
144
refers to the nsKey value of In-Store Discount item created in the preceeding section. You
can determine the discount item ID by navigating to the item, and inspecting the id=
parameter of the URL or, if you have enabled the display of Internal IDs, the value is displayed
in the nsKey column.
Test the Code
Next we will upload the javascript file to NetSuite and apply the code to our custom Cash Sale
Transaction form.
To upload the javascript file to NetSuite:
1.
Go to Documents > Files > File Cabinet.
2.Select the folder you want to add your file to.
3.
At the bottom of the page, select Computer in the Attach From field.
4.
Click Browse next to the File field and select the
customCashSale.js
file you just
created.
5.
Click Add This File.
To apply the custom code to a transaction form:
1.
Go to Setup > Customization > Transaction Forms.
2.Click Customize next to Standard Cash Sale.
3.In the Name field, enter
Custom Code Sample
.
Leave all standard settings the same.
4.Click the Custom Code subtab.
5.
In the Script File field, browse to the
customCashSale.js
file you uploaded to your file
cabinet.
Client SuiteScript Tutorial
Validating Field Values
18
6.
In the Page Init Function field, enter
samplePageInit
.
7.
Click Save.
You can now go to Transactions > Sales > Enter Cash Sales to test your custom code. Select the
Custom Code Sample
form in the Custom Form field on the Cash Sale page.
Notice that the Discount is automatically set to
In-Store Discount
with the rate at -5%. This
cash sale will have the 5% discount applied to it.
Validating Field Values
Of course, in some cases, there may be customer discounts already assigned for certain
customers, in which case we wouldn’t want to automatically assign the lower 5% discount — we
will want to consider the customer discount instead. In this section we will create a validation
script to ensure that this is the behavior.
Setup
Before creating our code, we will need to setup several customers with custom discounts. The
following table lists all of the elements you will need to create in order to do this.
Client SuiteScript Tutorial
Validating Field Values
19
Create the Code
In this section we will add the validation code to the customCashSales.js file created for the
Page Init function.
Note: When applying custom code, you can select up to two javascript files to associate with a given custom form. One file should contain all of the code specific to the current form. The other, library file, should contain any code that may be used across multiple forms. For the purposes of this tutorial, we will include all of the custom code in a single file — customCashSales.js.
Retrieving the Customer Discount
First, we’ll need to create a function that determines whether a customer discount rate has been
set. The following code uses nlapiGetFieldText to retrieve the value of the custom transaction
body field we created — custbody_cust_discount. If it exists, we convert the value to a negative
number to ensure that the total is decreased by the specified amount and the value is then
returned.
Element Parameters Purpose
5 Discount Items Item Name/Number: 10%* Income Account: 4000 Sales Rate: 10%*
Apply Before Sales Tax: No
And four additional discount items with the Item Name/Number and Rate fields to 15%, 20%, 25% and 30% respectively
Defines the discount items that you will be able to set for any customers. To create, go to Lists > Accounting > Items > New > Discount.
Custom List Name: Customer Discounts Values: 10%, 15%, 20%, 25%, 30%
Defines the selection list of discount items.
To create, go to Setup > Customization > Lists > New.
Entity Field Description: Customer Discount ID: _customer_discount Type: List/Record
List/Record: Customer Discounts Applies To: Customer:Job Subtab: General
Sources the list just created.
To create, go to Setup > Customization > Entity Fields > New.
Transaction Body Field
Description: Cust. Discount ID: _cust_discount Type: List/Record
List/Record: Customer Discounts Applies To: Sale
Subtab: Main
Display Type: Disabled Source LIst: Entity
Source From: Customer Discount
To create, go to Setup > Customization > Transaction Body Fields > New.
Customer Records
Set a discount to various customers.
Client SuiteScript Tutorial
Validating Field Values
20
function calcCustomerDiscountRate() { if( !isNaN(parseFloat(nlapiGetFieldText('custbody_cust_discount'))) ) return ((parseFloat(nlapiGetFieldText('custbody_cust_discount'))) * -1); else return 0; }Determining Which Discount to Use
Next, we’ll want to make sure that the Page Init function does not cause the discount to be set
to 5% if a customer already has a pre-defined higher discount rate.
1.
Create a new function.
function sampleValidateField(type, name) {
2.
Set the variables
var useCustomerDiscount = true; var instore_discount = -5;
var cust_discount = calcCustomerDiscountRate();
3.
Determine if In-Store discount is higher than the customer discount and return an
alert that allows you to choose whether to accept the higher value.
if ( instore_discount <= cust_discount ) { useCustomerDiscount = false; } if( useCustomerDiscount ) { alert("custbody_cust_discount: '" + nlapiGetFieldText('custbody_cust_discount') + "'"); nlapiSetFieldText('discountitem', nlapiGetFieldText('custbody_cust_discount')); } else {
nlapiSetFieldText('discountitem', "In-store Discount"); }
4.
Close the function.
}Test the Code
Now upload the modified customCashSale.js file to the file cabinet and then assign the
sampleValidateField function for the Validate Field function on the Custom Code Sample
form.
Client SuiteScript Tutorial
Triggering Events when a Field is Changed
21
Now when we enter a cash sale using the Custom Code Sample form, if a customer is selected
that has a pre-defined discount higher than the In-store discount set by the Page Init function,
then the In-store discount is NOT used.
More Validation
This is a very simple case. In reality, we’d need to add some further validation to ensure that the
field types are in the correct format and we may want to check for other discount restrictions,
etc. The complete code included in the appendix,
Appendix: Tutorial Code
includes javascript
validation for the following:
•
If the transaction discount is changed to a rate greater than $50 or 30%, a box pops up
asking for confirmation of manager approval for the discount.
The user can choose to keep the current discount or abort the discount. If the discount
is aborted, a message is displayed to notify the user that the discount level is not
approved and it will be reset.
•
If more than 20 of any one item is added to the transactions, a box pops up asking if
you are sure you want to add the item. The user can choose to add the items or return
to the item list without adding the items.
Triggering Events when a Field is Changed
In the Field Changed example, we will cause a popup box display that indicates if a customer
has had order problems in the past and reminds the user to verify all items before submitting
the order.
Setup
Client SuiteScript Tutorial
Triggering Events when a Field is Changed
22
Create the Code
In this section we will add the field changed code to the customCashSales.js file.
1.
First, we will set this code to fire on any change to the transaction body field created
during Setup.
function sampleFieldChanged(type, name) {
if (name == 'custbody_had_order_problems') {
Remember, the custbody_had_order_problems is sourced from the entity field
selected. Therefore, this code will be executed each time a new customer is selected in
the form. Since the custbody_had_order_problems field is locked, it can NOT be
edited directly.
2.
Next, we’ll check the value of the checkbox field and if set to T, display an alert.
if ( (nlapiGetFieldValue('custbody_had_order_problems') == 'T') &&(nlapiGetFieldText('entity')) ) {
alert("This customer has had order problems previously. Be sure to verify all items with the customer before submitting the order.");
return true; }
3.
Finally, we will close the function without causing any additional change.
}return true; }
Test the Code
Upload the modified customCashSale.js file to the file cabinet and then assign the
sampleFieldChanged function for the Field Change Validation function on the Custom Code
Sample form.
Element Parameters Purpose
Entity Field Description: Past Order Problems Subtab: General
ID: _had_order_problems Applies To: Customer:Job
To create, go to Setup > Customization > Entity Field > New.
Transaction Body Field
Description: Past Order Problems Type: Check Box
Source List: Entity Subtab: Main Display Type: Locked ID: _had_order_problems Applies To: Sale
To create, go to Setup > Customization > Transaction Body Field > New.
Client SuiteScript Tutorial
Validating a Line Item
23
Now when we enter a cash sale using the Custom Code Sample form, if a customer is selected
where Past Order Problems checkbox is enabled, an alert is displayed.
Validating a Line Item
In the Validate Line example, we will include validation that prevents the addition of a service
line item without a service employee being chosen for that line.
Setup
This script requires the creation of a custom entity and custom transaction column field.
Create the Code
Again, we will modify the customCashSale.js file to add the following code. The code simply
checks the value of the custcol_service_rep custom field whenever a custcol_service_item item
is selected. If the value is
T
, then an alert is displayed and the event is aborted. The user is
forced to first select a service rep before entering any line items.
function sampleValidateLine(type) {
Element Parameters Purpose
Entity Field Description: Service Rep Type: Check Box
Subtab: Human Resources Applies To: Employee
Provides a checkbox on employee records where you can define an employee as a service rep.
To create, go to Setup > Customization >Entity Field > New.
Transaction Column Field
Description: Service Rep Type: List/Record List/Record: Employee ID: _service_rep Applies To: Sale Item Filter Using: Service Rep Is Checked: True
To create, go to Setup > Customization > Transaction Column Field > New.
Employee Records
Assign various employees as service reps.
Client SuiteScript Tutorial
Recalculating Field Totals
24
if ( (nlapiGetCurrentLineItemValue('item', 'custcol_service_item') == 'T') && (!nlapiGetCurrentLineItemText('item', 'custcol_service_rep')) )
{
alert("You must choose a Service Rep for this service item."); return false;
}
return true; }
Test the Code
Upload the modified customCashSale.js file to the file cabinet and then assign the
sampleValidateLine function for the Validate Line function on the Custom Code Sample form.
Now when we enter a cash sale using the Custom Code Sample form, if a service line item is
selected when a sales rep has not been assigned, the user is forced to return and select a sales
rep for the customer before selecting any service items.
Recalculating Field Totals
In the Recalc example, we will determine if items added to the cash sale are service items. If the
item is a service, the sales price is added to the service bookings field.
Setup
This script requires the creation of a custom item field, transaction column field and
transaction body field.
Client SuiteScript Tutorial
Recalculating Field Totals
25
Create the Code
Again, we will modify the customCashSale.js file to add the following code.
function sampleRecalc(type){
var total = 0;
for ( i = 1; i <= nlapiGetLineItemCount('item'); i++) {
var item_amount = parseFloat(nlapiGetLineItemValue('item', 'amount', i)); if (nlapiGetLineItemValue('item', 'custcol_service_item', i) == 'T') { total += item_amount; } } nlapiSetFieldValue('custbody_service_bookings', nlapiFormatCurrency(total)); }
Test the Code
Upload the modified customCashSale.js file to the file cabinet and then assign the
sampleRecalc function for the Validate Line function on the Custom Code Sample form.
Element Parameters Purpose
Item Field Description: Service Item Type: Check Box Subtab: Basic ID: _service_item Applies To: Service Default Checked: True
To create, go to Setup > Customization > Item Field > New.
Transaction Body Field
Description: Service Bookings Type: Currency
Subtab: Main Display Type: Locked ID: _service_bookings Applies To: Sale
To create, go to Setup > Customization > Transaction Body Field > New.
Item Records Designate various existing items as service items.
Any new service items created are automatically marked as service items..
Client SuiteScript Tutorial
Prompting before Save
26
Now when we save a cash sale using the Custom Code Sample form, any service items amounts
are added to the service bookings field.
Prompting before Save
In the Save example, we will cause a pop-up box to display when a record is saved that prompts
the user with “Are you sure you want to save this record?” The code will execute the save if the
user clicks OK and abort the save if the user clicks Cancel.
Note: No record customization (setup) is required for this script to work properly.
Create the Code
Again, we will modify the customCashSale.js file to add the following code. This simple script
returns a dialog box prompting the user to confirm the save.
function sampleSaveRecord() {
return confirm("Are you sure you want to save this record?"); }
Test the Code
Upload the modified customCashSale.js file to the file cabinet and then assign the
sampleSaveRecord function for the Save Record function on the Custom Code Sample form.
Now when we save a cash sale using the Custom Code Sample form, a confirmation prompt is
returned.
Chapter 4 Code Names
The tables in this chapter detail standard field names that can be used in custom code. You can
reference the table with names listed by record type or by field type.
Note: When referenced in Client SuiteScript, field names are case sensitive. Also, the Field Name column in the following tables refers the standard field name NetSuite uses to define the given field. This name may differ in your account if the name has been customized.
Code Names by Record Type:
•
Case Record
•
Contact Record
•
Customer Record
•
Employee Record
•
Event Record
•
Partner Record
•
Task Record
•
Vendor Record
•
Opportunity Record
Code Names by Field Type:
•
Entity Fields
•
CRM Fields
•
Item Fields
•
Transaction Fields
You can also find the Custom Code ID for any standard or custom field in NetSuite by viewing
the page source of any form that displays the desired field.
To find any Client SuiteScript ID for a Field in NetSuite:
1.
Display the form that contains the standard or custom field ID you need in edit mode.
You can display a form in edit mode by editing an existing record or creating a new
record. For example, to find the Client SuiteScript ID for a field on an Opportunity
form, display the list of Opportunities and click Edit next to an Opportunity record.
2.Copy the Field name.
Highlight the field text and press CTRL + C .
Code Names
Code Names by Record Type
28
4.
Find the Field name in the source.
Press CTRL + F (Find) and then CTRL + V (Paste) and hit Return.
5.
Examine the Anchor tag for that Field. The anchor tag contains the Custom Code ID
for the field.
For example:
To find the Custom Code ID for the Win/Loss Reason field in an Opportunity form, navigate
to the opportunity form (in edit mode), and find the Win/Loss Reason field in the page source.
The anchor tag is as follows:
<A class='smalltextnolink' tabindex=-1 title="What's this?" href='javascript:void("help")'
style='cursor:help'onclick="return
nlFieldHelp(19,'TRAN_OPPRTNTY','winlossreason', this)" onkeypress="event.cancelBubble = true; return true;" onmouseover="this.className='smalltextul'; return
true;" onmouseout="this.className='smalltextnolink'; ">Win/Loss Reason</A>
Therefore, the Custom Code ID for the Win/Loss Reason field is
winlossreason
.
Code Names by Record Type
Case Record
Code Name Field Name Location
assigned Assigned main
casenumber Case Number main
category Category main
company Company main
contact Contact main
createddate Creation Date main customform Custom Form main
email E-mail main
emailemployees E-Mail Employees main emailform E-mail reply main escalationmessage Escalation Message escalation
helpdesk Help Desk main
inboundemail Inbound E-mail main incomingmessage Incoming Message main internalonly Internal Only main
isinactive Inactive main
issue Issue main
Code Names
Code Names by Record Type
29
Contact Record
lastmessagedate Last Message Date main lastmodifieddate Last Modified Date main
origin Origin main
outgoingmessage Outgoing Message main
phone Phone main
priority Priority main
serialnumber Serial Number main startdate Start Date main starttime Start Time main
status Status main
title Title main
Code Name Field Name Location
altemail Alt. E-mail general assistant Assistant general assistantphone Assistant Phone general availableoffline Always Available Offline main
category Category main
comments Comments general
company Company main
customform Custom Form main
email E-Mail general
entityid Name/ID main
fax Fax general
firstname First Name general homephone Home Phone general
image Image general
isinactive Inactive main
isprivate Private main
lastname Last Name general middlename Middle Name general mobilephone Mobile Phone general officephone Office Phone general
phone Phone general
Code Names
Code Names by Record Type
30
Customer Record
salutation Mr./Ms... general supervisor Supervisor general supervisorphone Supervisor Phone general
title Job Title general
unsubscribe Unsubscribe general
Code Name Field Name Location
accessrole Role access
accountnumber Account financial
aging Aging financial
altphone Alt. Phone general availableoffline Always Available Offline main
balance Balance financial
category Category general clickstream Click-Stream (1st Visit) web comments Comments general companyname Company Name general creditlimit Credit Limit financial currency Currency financial customform Custom Form main datecreated Date Created general
email E-Mail general
enddate End Date financial
entityid Name/ID main
entitystatus Status main
fax Fax general
firstvisit Date of First Visit web giveaccess Has Access access
image Image general
isinactive Inactive main
keywords Search Engine Keywords (1st Visit)
web
language Language general
Code Names
Code Names by Record Type
31
Employee Record
lastvisit Date of Last Visit web leadsource Lead Source general openingbalance Opening Balance financial
parent Parent main
partner Partner general
password Password access
phone Phone general
prefccprocessor Pref. CC Processor financial pricelevel Price Level financial printoncheckas Print On Check As general probability Probability main referrer Referrer (1st Visit) web reminderdays Reminder Days financial resalenumber Resale Number financial salesrep Sales Rep general sendemail Send Notification E-mail access shippingitem Shipping Item financial startdate Start Date financial
taxable Taxable financial
taxitem Tax Item financial
terms Terms financial
territory Territory general unsubscribe Unsubscribe general
url Web Address general
vatregnumber VAT Registration Nº financial visits Number of Visits web
weblead Web Lead general
Code Name Field Name Location
accountnumber Account general
aeic AEIC payfed
aliennumber Alien Number hrworkstatus allowance Allowance payfed approvallimit Approval Limit hr
Code Names
Code Names by Record Type
32
approver Approver hr
authworkdate Authorized to work until hrworkstatus billingclass Billing Class general birthdate Birth Date hr
class Class general
comments Comments general customform Custom Form main
degree Degree hreducation
degreedate Date Conferred hreducation department Department general directdeposit Use Direct Deposit dd
education Level of Education hreducation
email E-Mail general
employeestatus Employee Status hr
employeetype Type hr
entityid Name/ID main
ethnicity Ethnicity hrpersonal extra Extra Withholding payfed
fax Fax general
fedstatus Filing Status payfed fedunemp Federal Unemployment payfed fedwith Federal Withholding payfed firstname First Name general
gender Gender hrpersonal
giveaccess Has Access access hasofflineaccess Offline Client Access access
hiredate Hire Date hr
homephone Home Phone general i9verified I-9 Verified hrworkstatus
image Image general
inheritiprules Inherit IP Rules from Company
access
initials Initials general ipaddressrule IP Address Restriction access isinactive Inactive main
Code Names
Code Names by Record Type
33
issueusertype Issue User Type hr issupportrep Support Rep hr jobdescription Job Description hr lastname Last Name general lastpaiddate Last Paid date payroll lastreviewdate Last Review Date hr location Location general maritalstatus Marital Status hrpersonal
medicare Medicare payfed
middlename Middle Name general mobilephone Mobile Phone general nextreviewdate Next Review Date hr officephone Office Phone general
password Password access
payfrequency Pay Frequency payroll
phone Phone general
releasedate Release Date hr
residentstatus Resident Status hrworkstatus salutation Mr./Ms... general sendemail Send Notification E-mail access socialsecurity Social Security payfed socialsecuritynumber Social Security hr supervisor Supervisor hr
template Template main
terminationbydeath Termination Due To Death hr
title Job Title hr
unsubscribe Unsubscribe general usetimedata Use Time Data payroll visaexpdate Visa Expiration Date hrworkstatus visatype Visa Type hrworkstatus w4completed W4 Completed payfed
Code Names
Code Names by Record Type
34
Event Record
Partner Record
Code Name Field Name Location
accesslevel Access Level main customform Custom Form main
endtime End Time main
location Location main
message Message main
organizer Organizer main reminderminutes Minutes main remindertype Reminder Type main startdate Start Date main starttime Start Time main
status Status main
title Title main
transaction Opportunity main
Code Name Field Name Location
accessrole Role
category Category general comments Comments general companyname Company Name general customform Custom Form main
email E-Mail general
entityid Name/ID main
fax Fax general
giveaccess Has Access access
image Image general
isinactive Inactive main partnercode Partner Code
password Password access
phone Phone general
printoncheckas Print On Check As general sendemail Send Notification E-mail access subpartnerlogin Can give login access To
Code Names
Code Names by Record Type
35
Task Record
Vendor Record
taxidnum Tax ID financial
unsubscribe Unsubscribe general
url Web Address general
Code Name Field Name Location
accesslevel Access Level main
assigned Assigned main
completeddate Date Completed main customform Custom Form main
enddate End Date main
message Message main
order Order main
owner Owner main
priority Priority main
sendemail Send E-mail main startdate Start Date main
status Status main
title Title main
transaction Opportunity main
Code Name Field Name Location
accountnumber Account financial altphone Alt. Phone general
balance Balance financial
category Category general comments Comments general companyname Company Name general creditlimit Credit Limit financial currency Currency financial customform Custom Form main
email E-Mail general
entityid Name/ID main
expenseaccount Default Expense Account financial
Code Names
Code Names by Record Type
36
Opportunity Record
fax Fax general
giveaccess Has Access access
image Image general
is1099eligible 1099 Eligible financial isaccountant Make this my FREE
accountant
access
isinactive Inactive main legalname Legal Name financial openingbalance Opening Balance financial
password Password access
phone Phone general
prefccprocessor Pref. CC Processor financial printoncheckas Print On Check As general sendemail Send Notification E-mail access
taxidnum Tax ID financial
terms Terms financial
unsubscribe Unsubscribe general
url Web Address general
vatregnumber VAT Registration Nº financial
Code Name Field Name Location Available For
actionitem Action Item main screen
altsalesamt Alt.Sales screen
amount Amount screen
availableoffline Always Available Offline main screen
balance Balance main off
billaddress Bill To address both
class Class off
class Class main screen
currencyname Currency items screen customform Custom Form main screen
department Department off
department Department main screen
description Description screen
Code Names
Code Names by Record Type
37
entitystatus Entity Status main screen exchangerate Exchange Rate items screen expectedclosedate Exp. Close Date main screen forecasttype Forecast Type main screen
grossamt Gross Amt both
item Item screen
job Job off
leadsource Lead Source main screen
location Location off
location Location main screen
memo Memo main screen
pagenumber Page Number print
partner Partner main screen
probability Probability main screen projaltsalesamt Alt.Sales Amount main screen projectedtotal Projected Total main screen
quantity Quantity screen
quantityavailable Available off
quantityonhand On Hand off
rate Rate screen
salesrep Sales Rep main screen
serialnumbers Serial Numbers screen shipaddress Ship To address both
tax1amt Tax Amt both
taxcode Tax Code screen
taxrate1 Tax Rate both
terminmonths Revenue Recognition Term in Months
off
title Title main screen
trandate Date main screen
tranid Doc. No. main screen
units Units screen
vatregnum Tax Id main both
weightedtotal Weighted Total main screen winlossreason Win/Loss Reason main screen
Code Names
Code Names by Field Type
38
Code Names by Field Type
Entity Fields
Code Name Field Name Customer Job Vendor Partner Employee Contact
accessrole Role access access
accountnumber Account financial financial general
aeic AEIC payfed
aging Aging financial
aliennumber Alien Number hrwork
status
allowance Allowance payfed
altcontact Alt. Contact
altemail Alt. E-mail general
altphone Alt. Phone general general general
approvallimit Approval Limit hr
approver Approver hr
assistant Assistant general
assistantphone Assistant Phone general authworkdate Authorized to work until hrwork status availableoffline Always Available Offline main main
balance Balance financial financial
billingclass Billing Class general
birthdate Birth Date hr
category Category general general general general main
class Class general
clickstream Click-Stream (1st Visit)
web
comments Comments general general general general general general
company Company main
companyname Company Name
general general general general
creditlimit Credit Limit financial financial currency Currency financial financial