Sie sind auf Seite 1von 80

Client SuiteScript Developers Guide

Copyright NetSuite, Inc. 2005 All rights reserved. Client SuiteScript Developers 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. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 Getting 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 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 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 Test the Code. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

Client SuiteScript Developers Guide

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 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Case 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

Appendix: Tutorial Code

Client SuiteScript Developers Guide

Chapter 1 Welcome
Welcome to NetSuites 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.

Client SuiteScript Developers Guide

Welcome Roles & Permissions

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 add Client SuiteScript capabilities, you must also add permission for customizing entry forms and transaction forms.
Roles Administrator Full Access Marketing Manager Marketing Administrator Sales Manager Sales Administrator Support Administrator Access Level FULL FULL FULL FULL FULL FULL FULL

Client SuiteScript Developers Guide

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.

Client SuiteScript Developers Guide

Using Client SuiteScript Getting Started

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.

Client SuiteScript Developers Guide

Using Client SuiteScript Getting Started

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. 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.

2.

Client SuiteScript Developers Guide

Using Client SuiteScript Functions

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. 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.

4.

Functions
NetSuite provides several standard functions that are automatically triggered with certain events as outlined in the following table.
Function PageInit SaveRecord ValidateField* line item type: String; field name: String line item type: String; field name: String type: String field name: String line item type: String Boolean Boolean Parameters Returns Description Called when the page is first loaded. Called when the user requests the form to be saved. Returns false to reject the operation. 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. Called when a new value for a field is accepted. Called on the FieldChanged event after all slaved fields source. Called when an existing line is selected in the item machine. The string value returned is always item.

FieldChanged* PostSourcing Line Init

Client SuiteScript Developers Guide

Using Client SuiteScript Functions

Function Validate Line Recalc

Parameters line item type: String line item type: String

Returns Boolean

Description Called when a user requests the addition or edit of a line item. Returns false to reject the operation. Called when a new or edited line has been accepted.

*The ValidateField and FieldChanged scripts require a null line item for body form fields.

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(); var userRole = nlapiGetRole(); var userDept = nlapiGetDepartment(); var userLoc = nlapiGetLocation(); // // // // entity id id of the id of the id of the of the current current user's current user's current user's user role department location

Client SuiteScript Developers Guide

Using Client SuiteScript Functions

// 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; }

Client SuiteScript Developers Guide

Using Client SuiteScript Functions

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; }

Client SuiteScript Developers Guide

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 Opening Balance

Client SuiteScript Developers Guide

Using Client SuiteScript Client SuiteScript API

11

Function nlapiGetFieldValue nlapiSetFieldValue

Parameters field name: String field name: String; value: String; firefieldchanged: Boolean line item type: String; field name: String line item type: String; field name: String; value: String firefieldchanged: Boolean line item type: String; field name: String; line index: Integer line item type: String; field name: String; line index: Integer; value: String

Description Retrieves the value of the given field. Sets the value of the given field. See also Using the Fire Field Changed Parameter on page 13 Retrieves the value of the given line-item field before it has been added to the form. Typically used in validate line functions. 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 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. 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. Retrieves the current index of the line being added or edited. If adding, the function should nlapiGetLineItemCount(type)+1. Retrieves the total number of line items for the given type. Formats a floating point value according to the prevailing currency conventions. Converts a JavaScript string to a Date according to date formatting conventions. Converts a JavaScript Date to a string according to date formatting conventions. Adds a set number of days to a JavaScript date, returning the modified object. Adds a set number of months to a JavaScript date, returning the modified object. Gets the text value of the given selection field. Important: nlapiGetFieldText can NOT be used on hidden fields.

nlapiGetCurrentLineItemValue

nlapiSetCurrentLineItemValue

nlapiGetLineItemValue

nlapiSetLineItemValue

nlapiGetCurrentLineItemIndex

line item type: String

nlapiGetLineItemCount nlapiFormatCurrency nlapiStringToDate nlapiDateToString nlapiAddDays nlapiAddMonths nlapiGetFieldText

line item type: String amount: Float string: Date date: Date date: Date; days: Integer date: Date; months: Integer field name: String

Client SuiteScript Developers Guide

Using Client SuiteScript Client SuiteScript API

12

Function nlapiGetCurrentLineItemText

Parameters line item type: String; field name: String firefieldchanged: Boolean

Description 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 Gets the text value of the given selection field on the line item at the given index. 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 Sets the value of the given line-item selection field to the value with the given text. Sets the given field to disabled or enabled based on the value (true or false). Sets the given line item field of the given type to disabled or enabled based on the value (true or false). Returns an encrypted string for the given input string. Returns the entity ID of the current user. Returns the ID of the current users role. Returns the ID of the current users department. Returns the ID of the current users location. Selects an existing line number of a machine. Line number must be between 1 and nlapiGetLineItemCount. Commits the current line of a machine type. This is the equivalent of clicking Done for a line item in the UI. Inserts a line above the current line of machine. Removes the current line of a machine. Cancels any edits to the current line of a machine and reselects the line. Synonym for nlapiCancelLineItem. Returns true if the currently selected line of machine has been edited. Loads an existing record.

nlapiGetLineItemText

line item type: String; field name: String; line index: Integer field name: String; text value: String firefieldchanged: Boolean line item type: String; field name: String; text value: String field name: String; value: Boolean line item type: String; field name: String; value: Boolean Clear Text: String N/A N/A N/A N/A line item type: String line item number: String line item type: String

nlapiSetFieldText

nlapiSetCurrentLineItemText

nlapiDisableField nlapiDisableLineItemField

nlapiEncrypt nlapiGetUser nlapiGetRole nlapiGetDepartment nlapiGetLocation nlapiSelectLineItem

nlapiCommitLineItem

nlapiInsertLineItem nlapiRemoveLineItem nlapiCancelLineItem nlapiSelectNewLineItem nlapiIsLineItemChanged nlapiLoadRecord

line item type: String line item type: String line item type: String line item type: String line item type: String type: record type id: internalID

Client SuiteScript Developers Guide

Using Client SuiteScript Client SuiteScript API

13

Function nlapiSaveRecord nlapiCreateRecord nlapiSearchRecord nlapiDeleteRecord nlapiSendEmail

Parameters type: record type id: internalID type: record type type: record type searchId: saved search ID type: record type id: internalID 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

Description Saves the current record. Creates a new record instance. Allows you to search for other records in the system. Permanently deletes a record from the database. Generates and sends an email.

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. 2. 3.

The Client SuiteScript code watches for fieldA to change. fieldA changes. 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. 2. 3.

Custom code watches for fieldA to change. fieldA changes. 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.

Client SuiteScript Developers Guide

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'); nlapiSetCurrentLineItemText('item', 'item', 'Shipping'); }

Client SuiteScript Developers Guide

Using Client SuiteScript Client SuiteScript API


function doPostSourcing(type, fldname) { if ( type == 'item' && fldname == 'item' && nlapiGetCurrentLineItemValue ('item', 'custcolinsertshippingrate') == 'T' ) { nlapiSetCurrentLineItemValue('item', 'custcolinsertshippingrate', 'F'); nlapiSetCurrentLineItemValue('item', 'rate', '7.50'); nlapiCommitLineItem('item'); } }

15

Client SuiteScript Developers Guide

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 NetSuites 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.
Element Discount Item Parameters Item Name/Number: In-store Discount Income Account: 4000 Sales Rate: 5% Apply Before Sales Tax: No Purpose Defines the discount item that you will refer to in your custom code. To create, go to Lists > Accounting > Items > New > Discount.

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); }

Client SuiteScript Developers Guide

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. 2. 3. 4.

Go to Documents > Files > File Cabinet. Select the folder you want to add your file to. At the bottom of the page, select Computer in the Attach From field. Click Browse next to the File field and select the customCashSale.js file you just created. Click Add This File.

5.

To apply the custom code to a transaction form:


1. 2. 3.

Go to Setup > Customization > Transaction Forms. Click Customize next to Standard Cash Sale. In the Name field, enter Custom Code Sample. Leave all standard settings the same. Click the Custom Code subtab. In the Script File field, browse to the customCashSale.js file you uploaded to your file cabinet.

4. 5.

Client SuiteScript Developers Guide

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 wouldnt 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 Developers Guide

Client SuiteScript Tutorial Validating Field Values

19

Element

Parameters

Purpose Defines the discount items that you will be able to set for any customers. To create, go to Lists > Accounting > Items > New > Discount.

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 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 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 Set a discount to various customers.

Sources the list just created. To create, go to Setup > Customization > Entity Fields > New.

Transaction Body Field

To create, go to Setup > Customization > Transaction Body Fields > New.

Customer Records

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, well 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.

Client SuiteScript Developers Guide

Client SuiteScript Tutorial Validating Field Values


function calcCustomerDiscountRate() { if( !isNaN(parseFloat(nlapiGetFieldText('custbody_cust_discount'))) ) return ((parseFloat(nlapiGetFieldText('custbody_cust_discount'))) * -1); else return 0; }

20

Determining Which Discount to Use


Next, well 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 Developers Guide

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, wed 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
This script requires the creation of custom entity and transaction body fields.

Client SuiteScript Developers Guide

Client SuiteScript Tutorial Triggering Events when a Field is Changed

22

Element Entity Field

Parameters Description: Past Order Problems Subtab: General ID: _had_order_problems Applies To: Customer:Job Description: Past Order Problems Type: Check Box Source List: Entity Subtab: Main Display Type: Locked ID: _had_order_problems Applies To: Sale

Purpose To create, go to Setup > Customization > Entity Field > New.

Transaction Body Field

To create, go to Setup > Customization > Transaction Body Field > New.

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, well 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.

Client SuiteScript Developers Guide

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.
Element Entity Field Parameters Description: Service Rep Type: Check Box Subtab: Human Resources Applies To: Employee Purpose 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. To create, go to Setup > Customization > Transaction Column 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 Assign various employees as service reps.

Employee Records

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) {

Client SuiteScript Developers Guide

Client SuiteScript Tutorial Recalculating Field Totals


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; }

24

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 Developers Guide

Client SuiteScript Tutorial Recalculating Field Totals

25

Element Item Field

Parameters Description: Service Item Type: Check Box Subtab: Basic ID: _service_item Applies To: Service Default Checked: True Description: Service Bookings Type: Currency Subtab: Main Display Type: Locked ID: _service_bookings Applies To: Sale Designate various existing items as service items.

Purpose To create, go to Setup > Customization > Item Field > New.

Transaction Body Field

To create, go to Setup > Customization > Transaction Body Field > New.

Item Records

Any new service items created are automatically marked as service items..

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.

Client SuiteScript Developers Guide

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.

Client SuiteScript Developers Guide

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 Entity Fields CRM Fields Item Fields Transaction Fields

Code Names by Field Type:

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. Copy the Field name. Highlight the field text and press CTRL + C . Right click in the form and select View Source (or View Page Source).

2.

3.

Client SuiteScript Developers Guide

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. Examine the Anchor tag for that Field. The anchor tag contains the Custom Code ID for the field.

5.

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 assigned casenumber category company contact createddate customform email emailemployees emailform escalationmessage helpdesk inboundemail incomingmessage internalonly isinactive issue item Field Name Assigned Case Number Category Company Contact Creation Date Custom Form E-mail E-Mail Employees E-mail reply Escalation Message Help Desk Inbound E-mail Incoming Message Internal Only Inactive Issue Item Location main main main main main main main main main main escalation main main main main main main main

Client SuiteScript Developers Guide

Code Names Code Names by Record Type

29

Code Name lastmessagedate lastmodifieddate origin outgoingmessage phone priority serialnumber startdate starttime status title

Field Name Last Message Date Last Modified Date Origin Outgoing Message Phone Priority Serial Number Start Date Start Time Status Title

Location main main main main main main main main main main main

Contact Record
Code Name altemail assistant assistantphone availableoffline category comments company customform email entityid fax firstname homephone image isinactive isprivate lastname middlename mobilephone officephone phone Field Name Alt. E-mail Assistant Assistant Phone Always Available Offline Category Comments Company Custom Form E-Mail Name/ID Fax First Name Home Phone Image Inactive Private Last Name Middle Name Mobile Phone Office Phone Phone Location general general general main main general main main general main general general general general main main general general general general general

Client SuiteScript Developers Guide

Code Names Code Names by Record Type

30

Code Name salutation supervisor supervisorphone title unsubscribe

Field Name Mr./Ms... Supervisor Supervisor Phone Job Title Unsubscribe

Location general general general general general

Customer Record
Code Name accessrole accountnumber aging altphone availableoffline balance category clickstream comments companyname creditlimit currency customform datecreated email enddate entityid entitystatus fax firstvisit giveaccess image isinactive keywords language lastpagevisited Field Name Role Account Aging Alt. Phone Always Available Offline Balance Category Click-Stream (1st Visit) Comments Company Name Credit Limit Currency Custom Form Date Created E-Mail End Date Name/ID Status Fax Date of First Visit Has Access Image Inactive Search Engine Keywords (1st Visit) Language Last Page Visited Location access financial financial general main financial general web general general financial financial main general general financial main main general web access general main web general web

Client SuiteScript Developers Guide

Code Names Code Names by Record Type

31

Code Name lastvisit leadsource openingbalance parent partner password phone prefccprocessor pricelevel printoncheckas probability referrer reminderdays resalenumber salesrep sendemail shippingitem startdate taxable taxitem terms territory unsubscribe url vatregnumber visits weblead

Field Name Date of Last Visit Lead Source Opening Balance Parent Partner Password Phone Pref. CC Processor Price Level Print On Check As Probability Referrer (1st Visit) Reminder Days Resale Number Sales Rep Send Notification E-mail Shipping Item Start Date Taxable Tax Item Terms Territory Unsubscribe Web Address VAT Registration N Number of Visits Web Lead

Location web general financial main general access general financial financial general main web financial financial general access financial financial financial financial financial general general general financial web general

Employee Record
Code Name accountnumber aeic aliennumber allowance approvallimit Field Name Account AEIC Alien Number Allowance Approval Limit Location general payfed hrworkstatus payfed hr

Client SuiteScript Developers Guide

Code Names Code Names by Record Type

32

Code Name approver authworkdate billingclass birthdate class comments customform degree degreedate department directdeposit education email employeestatus employeetype entityid ethnicity extra fax fedstatus fedunemp fedwith firstname gender giveaccess hasofflineaccess hiredate homephone i9verified image inheritiprules initials ipaddressrule isinactive issalesrep

Field Name Approver Authorized to work until Billing Class Birth Date Class Comments Custom Form Degree Date Conferred Department Use Direct Deposit Level of Education E-Mail Employee Status Type Name/ID Ethnicity Extra Withholding Fax Filing Status Federal Unemployment Federal Withholding First Name Gender Has Access Offline Client Access Hire Date Home Phone I-9 Verified Image Inherit IP Rules from Company Initials IP Address Restriction Inactive Sales Rep

Location hr hrworkstatus general hr general general main hreducation hreducation general dd hreducation general hr hr main hrpersonal payfed general payfed payfed payfed general hrpersonal access access hr general hrworkstatus general access general access main hr

Client SuiteScript Developers Guide

Code Names Code Names by Record Type

33

Code Name issueusertype issupportrep jobdescription lastname lastpaiddate lastreviewdate location maritalstatus medicare middlename mobilephone nextreviewdate officephone password payfrequency phone releasedate residentstatus salutation sendemail socialsecurity socialsecuritynumber supervisor template terminationbydeath title unsubscribe usetimedata visaexpdate visatype w4completed

Field Name Issue User Type Support Rep Job Description Last Name Last Paid date Last Review Date Location Marital Status Medicare Middle Name Mobile Phone Next Review Date Office Phone Password Pay Frequency Phone Release Date Resident Status Mr./Ms... Send Notification E-mail Social Security Social Security Supervisor Template Termination Due To Death Job Title Unsubscribe Use Time Data Visa Expiration Date Visa Type W4 Completed

Location hr hr hr general payroll hr general hrpersonal payfed general general hr general access payroll general hr hrworkstatus general access payfed hr hr main hr hr general payroll hrworkstatus hrworkstatus payfed

Client SuiteScript Developers Guide

Code Names Code Names by Record Type

34

Event Record
Code Name accesslevel customform endtime location message organizer reminderminutes remindertype startdate starttime status title transaction Field Name Access Level Custom Form End Time Location Message Organizer Minutes Reminder Type Start Date Start Time Status Title Opportunity Location main main main main main main main main main main main main main

Partner Record
Code Name accessrole category comments companyname customform email entityid fax giveaccess image isinactive partnercode password phone printoncheckas sendemail subpartnerlogin Field Name Role Category Comments Company Name Custom Form E-Mail Name/ID Fax Has Access Image Inactive Partner Code Password Phone Print On Check As Send Notification E-mail Can give login access To Subpartners access general general access general general general main general main general access general main Location

Client SuiteScript Developers Guide

Code Names Code Names by Record Type

35

Code Name taxidnum unsubscribe url

Field Name Tax ID Unsubscribe Web Address

Location financial general general

Task Record
Code Name accesslevel assigned completeddate customform enddate message order owner priority sendemail startdate status title transaction Field Name Access Level Assigned Date Completed Custom Form End Date Message Order Owner Priority Send E-mail Start Date Status Title Opportunity Location main main main main main main main main main main main main main main

Vendor Record
Code Name accountnumber altphone balance category comments companyname creditlimit currency customform email entityid expenseaccount Field Name Account Alt. Phone Balance Category Comments Company Name Credit Limit Currency Custom Form E-Mail Name/ID Default Expense Account Location financial general financial general general general financial financial main general main financial

Client SuiteScript Developers Guide

Code Names Code Names by Record Type

36

Code Name fax giveaccess image is1099eligible isaccountant isinactive legalname openingbalance password phone prefccprocessor printoncheckas sendemail taxidnum terms unsubscribe url vatregnumber

Field Name Fax Has Access Image 1099 Eligible Make this my FREE accountant Inactive Legal Name Opening Balance Password Phone Pref. CC Processor Print On Check As Send Notification E-mail Tax ID Terms Unsubscribe Web Address VAT Registration N

Location general access general financial access main financial financial access general financial general access financial financial general general financial

Opportunity Record
Code Name actionitem altsalesamt amount availableoffline balance billaddress class class currencyname customform department department description entity Field Name Action Item Alt.Sales Amount Always Available Offline Balance Bill To Class Class Currency Custom Form Department Department Description Entity main main main items main main main address Location main Available For screen screen screen screen off both off screen screen screen off screen screen screen

Client SuiteScript Developers Guide

Code Names Code Names by Record Type

37

Code Name entitystatus exchangerate expectedclosedate forecasttype grossamt item job leadsource location location memo pagenumber partner probability projaltsalesamt projectedtotal quantity quantityavailable quantityonhand rate salesrep serialnumbers shipaddress tax1amt taxcode taxrate1 terminmonths title trandate tranid units vatregnum weightedtotal winlossreason

Field Name Entity Status Exchange Rate Exp. Close Date Forecast Type Gross Amt Item Job Lead Source Location Location Memo Page Number Partner Probability Alt.Sales Amount Projected Total Quantity Available On Hand Rate Sales Rep Serial Numbers Ship To Tax Amt Tax Code Tax Rate Revenue Recognition Term in Months Title Date Doc. No. Units Tax Id Weighted Total Win/Loss Reason

Location main items main main

Available For screen screen screen screen both screen off

main

screen off

main main

screen screen print

main main main main

screen screen screen screen screen off off screen

main

screen screen

address

both both screen both off

main main main

screen screen screen screen

main main main

both screen screen

Client SuiteScript Developers Guide

Code Names Code Names by Field Type

38

Code Names by Field Type


Entity Fields
Code Name accessrole accountnumber aeic aging aliennumber allowance altcontact altemail altphone approvallimit approver assistant assistantphone authworkdate availableoffline Field Name Role Account AEIC Aging Alien Number Allowance Alt. Contact Alt. E-mail Alt. Phone Approval Limit Approver Assistant Assistant Phone Authorized to work until Always Available Offline Balance Billing Class Birth Date Category Class Click-Stream (1st Visit) Comments Company Company Name Credit Limit Currency Custom Form Date Created general financial financial main general main general general general financial financial main main main main general web general general general general general general main general general general general general main hrwork status main general general general hr hr general general general financial hrwork status payfed Customer access financial financial Job Vendor Partner access general payfed Employee Contact

balance billingclass birthdate category class clickstream comments company companyname creditlimit currency customform datecreated

financial

financial general hr main

Client SuiteScript Developers Guide

Code Names Code Names by Field Type

39

Code Name degree degreedate department directdeposit education email employeestatus employeetype enddate entityid entitystatus estimatedcost estimatedrevenue ethnicity expenseaccount

Field Name Degree Date Conferred Department Use Direct Deposit Level of Education E-Mail Employee Status Type End Date Name/ID Status Estimated Cost Estimated Revenue Ethnicity Default Expense Account Extra Withholding Fax Filing Status Federal Unemploymen t Federal Withholding First Name Date of First Visit Gender Has Access Offline Client Access Hire Date Home Phone

Customer

Job

Vendor

Partner

Employee hreducation hreducation general dd hreducation

Contact

general

general

general

general

general hr hr

general

financial main main

financial main main financial financial hrpersonal financial main main main main

extra fax fedstatus fedunemp

payfed general general general general general payfed payfed general

fedwith firstname firstvisit gender giveaccess hasofflineaccess hiredate homephone

payfed general web hrpersonal access access access access access hr general general general

Client SuiteScript Developers Guide

Code Names Code Names by Field Type

40

Code Name i9verified image inheritiprules initials ipaddressrule is1099eligible isaccountant

Field Name I-9 Verified Image Inherit IP Rules from Company Initials IP Address Restriction 1099 Eligible Make this my FREE accountant Inactive Private Sales Rep Issue User Type Support Rep Job Description Job Type Search Engine Keywords (1st Visit) Language Last Name Last Page Visited Last Paid date Last Review Date Date of Last Visit Lead Source Legal Name Location Marital Status Medicare Middle Name Mobile Phone

Customer

Job

Vendor

Partner

Employee hrwork status

Contact

general

general

general

general

general access general access

general

financial access

isinactive isprivate issalesrep issueusertype issupportrep jobdescription jobtype keywords

main

main

main

main

main

main main

hr hr hr hr general web

language lastname lastpagevisited lastpaiddate lastreviewdate lastvisit leadsource legalname location maritalstatus medicare middlename mobilephone

general

general general general

web payroll hr web general financial general hrpersonal payfed general general general general

Client SuiteScript Developers Guide

Code Names Code Names by Field Type

41

Code Name nextreviewdate officephone openingbalance parent partner partnercode password payfrequency percentcomplete phone prefccprocessor pricelevel printoncheckas probability projectedenddate referrer releasedate reminderdays resalenumber residentstatus salesrep salutation sendemail

Field Name Next Review Date Office Phone Opening Balance Parent Partner Partner Code Password Pay Frequency Percent Complete Phone Pref. CC Processor Price Level Print On Check As Probability Projected End Date Referrer (1st Visit) Release Date Reminder Days

Customer

Job

Vendor

Partner

Employee hr general

Contact

general

financial main general

financial main

financial

main access access access access payroll financial general financial financial general main financial web hr financial general general general general financial general general general

Resale Number financial Resident Status Sales Rep Mr./Ms... Send Notification Email Shipping Item Social Security Social Security Start Date financial financial access access access general general access general hrwork status

shippingitem socialsecurity socialsecuritynum ber startdate

financial payfed hr

Client SuiteScript Developers Guide

Code Names Code Names by Field Type

42

Code Name subpartnerlogin

Field Name Can give login access To Subpartners Supervisor Supervisor Phone Taxable Tax ID Tax Item Template

Customer

Job

Vendor

Partner access

Employee

Contact

supervisor supervisorphone taxable taxidnum taxitem template

hr

general general

financial financial financial main hr financial general hr general general general general general general payroll financial financial hrwork status hrwork status web payfed general general general general financial general

terminationbydeat Termination h Due To Death terms territory title unsubscribe url usetimedata vatregnumber visaexpdate visatype visits w4completed weblead Terms Territory Job Title Unsubscribe Web Address Use Time Data VAT Registration N Visa Expiration Date Visa Type Number of Visits W4 Completed Web Lead

CRM Fields
Code Name accesslevel assigned casenumber category company Field Name Access Level Assigned Case Number Category Company Task main main Event main main main main main Case Campaign Solution Call main main

Client SuiteScript Developers Guide

Code Names Code Names by Field Type

43

Code Name completeddate contact convcostpercustomer cost costpercustomer createddate customform displayonline email emailemployees emailform enddate endtime escalationmessage expectedrevenue helpdesk inboundemail incomingmessage internalonly isinactive issue item lastmessagedate lastmodifieddate location longdescription message order organizer origin outgoingmessage owner phone priority

Field Name Date Completed Contact Cost Per Customer Conversion Cost Cost Per Customer Acquisition Creation Date Custom Form Display Online E-mail E-Mail Employees E-mail reply End Date End Time Escalation Message Expected Revenue Help Desk Inbound E-mail Incoming Message Internal Only Inactive Issue Item Last Message Date Last Modified Date Location Long Description Message Order Organizer Origin Outgoing Message Owner Phone Priority

Task main

Event

Case

Campaign Solution

Call main

main stat main stat main main main main main main main main main main main main escalation main main main main main main main main main main main detail main main main main main main main main main main main main main main main main main main main main main main

Client SuiteScript Developers Guide

Code Names Code Names by Field Type

44

Code Name profit reminderminutes remindertype roi sendemail serialnumber solutioncode startdate starttime status title transaction

Field Name Profit Minutes Reminder Type Return on Investment Send E-mail Serial Number Solution Code Start Date Start Time Status Title Opportunity

Task

Event

Case

Campaign Solution stat

Call

main main stat main main main main main main main main main main main main main main main main main main main main main main main main main

Item Fields
Code Name account amortization period amortization template assetaccount Field Name Account Amortization Period Amortization Template Asset Account basic main basic main basic inventory basic basic basic basic basic basic main basic main basic basic basic main basic main basic inventory basic basic basic main main main main main main Inventory Part NonInventory Part Group/Kit/ Assembly Discount/ Markup basic Payment basic Description/ Subtotal

availabletopa Available To rtners Adv. Partners billingsched ule class cogsaccount cost costingmeth od countryofma nufacture currency Billing Schedule Class COGS Account Purchase Price Costing Method Country of Manufacture Currency

Client SuiteScript Developers Guide

Code Names Code Names by Field Type

45

Code Name customform

Field Name

Inventory Part

NonInventory Part main basic basic

Group/Kit/ Assembly main

Discount/ Markup main

Payment main

Description/ Subtotal main

Custom Form main

daysbeforeex Days Before piration Expiration deferralacco unt deferredreve nueaccount demandmod ifier department description displayname expenseacco unt featureddesc ription Deferral Account Deferred Revenue Account Estimated Demand Change Department Description Display Name Expense Account Featured Description specials main basic

basic

basic

inventory

inventory

main

main

main basic

main basic main

main basic main

main basic

main basic specials store basic basic store store basic specials main main

main

specials store basic basic store store

froogleprodu Froogle store ctfeed Product Feed handlingcost Handling Cost basic basic store store basic specials main main

incomeaccou Income nt Account internalid isdonationite m isdropshipite m isfeatured isinactive isonline ispretax istaxable Internal ID Variable Amount Drop Ship Item Featured Item Inactive Display in Web Site Apply Before Sales Tax Taxable

specials main main basic main main main

basic

basic

basic main

isvsoebundle Is VSOE Bundle?

Client SuiteScript Developers Guide

Code Names Code Names by Field Type

46

Code Name itemid leadtime liabilityaccou nt location manufacture r metataghtml mpn nextagcateg ory nextagprodu ctfeed numofallowe ddownloads offersupport onspecial

Field Name Item Name/ Number Lead Time Liability Account Location Manufacture r Meta Tag HTML MPN NexTag Category

Inventory Part main inventory

NonInventory Part main

Group/Kit/ Assembly main inventory

Discount/ Markup main

Payment main

Description/ Subtotal main

basic main basic store basic store main basic store basic store store basic main basic store basic store store main main main

NexTag store Product Feed Number of Allowed Downloads Offer Support On Special main specials pricing

main specials pricing

main specials pricing

overallquanti Calculate typricingtype Quantity Discounts pagetitle parent paymentmet hod Page Title Subitem Of Payment Method

store main

store main

store main main basic

preferredloca Preferred tion Location preferredstoc Preferred klevel Stock Level pricinggroup printitems purchasedes cription Pricing Group Print Items Purchase Description

inventory inventory pricing pricing

inventory inventory pricing main

basic basic

basic basic

purchasetaxc Purchase Tax ode Code

Client SuiteScript Developers Guide

Code Names Code Names by Field Type

47

Code Name quantityavail able quantityback ordered quantitycom mitted quantityonh and quantityonor der quantityprici ngschedule rate relateditems description reorderpoint residual

Field Name Quantity Available

Inventory Part inventory

NonInventory Part

Group/Kit/ Assembly inventory inventory inventory inventory inventory

Discount/ Markup

Payment

Description/ Subtotal

Quantity inventory Back Ordered Quantity Committed Quantity On Hand Quantity On Order Quantity Pricing Schedule Rate Related Items Description Reorder Point Residual basic inventory inventory inventory pricing pricing

pricing

basic relitems

basic relitems

basic relitems

basic

inventory basic basic

inventory

revrecschedu Revenue le Recognition Template safetystockle vel Safety Stock Level

basic

inventory basic basic inventory inventory basic store basic store store store basic basic

inventory

salesdescripti Sales on Description salestaxcode seasonaldem and Sales Tax Code Seasonal Demand

basic inventory inventory basic store store store

basic

serialnumber Serial s Numbers shippingcost shoppingcat egory shoppingpro ductfeed shopzillacate goryid Shipping Cost Shopping Category

Shopping store Product Feed Shopzilla Category ID store

Client SuiteScript Developers Guide

Code Names Code Names by Field Type

48

Code Name shopzillapro ductfeed specialsdescr iption

Field Name

Inventory Part

NonInventory Part store specials basic store store store store store store

Group/Kit/ Assembly store specials basic store store store store store store

Discount/ Markup

Payment

Description/ Subtotal

Shopzilla store Product Feed Specials Description specials basic store store store store store store

stockdescript Stock ion Description storedescript ion storedetailed description storedisplayi mage Store Description Detailed Description Item Display Image

storedisplayn Store Display ame Name storedisplayt humbnail storeitemte mplate totalvalue unitstype usemarginalr ates vendor vendorname vsoedeferral vsoedelivere d vsoepermitdi scount vsoeprice weight Item Display Thumbnail Item Drilldown Template Total Value Units Type Use Marginal Rates Preferred Vendor Vendor Name Deferral Delivered Permit Discount VSOE Price Item Weight

inventory basic pricing basic main vsoepricing vsoepricing vsoepricing vsoepricing basic basic pricing basic main vsoepricing vsoepricing vsoepricing vsoepricing basic

inventory basic pricing

main vsoepricing vsoepricing vsoepricing vsoepricing basic

main

Transaction Fields
For convenience, the transaction fields information has been split into multiple tables, each table defining the fields available for a specific set of records as follows:

Table 1 Remittance Slip, Return Request-Credit, Return Request-Cash, Online Order-Invoice, Online Order-Cash Sale

Client SuiteScript Developers Guide

Code Names Code Names by Field Type

49

Table 2 Opportunity, Drop Ship Purchase Order, Shipping Label, Return Form, Statement Table 3 Packing Slip, Picking Ticket, Return Authorization - Cash, Return Authorization - Credit, Sales Order - Progress Billing Table 4 Progress Invoice, Sales Order - Cash Sale, Sales Order - Invoice, Canada Finance Charge, Service Invoice Table 5 Product Invoice, Professional Invoice, Credit Memo, Cash Sale Table 6 Cash Refund, Estimate, Purchase Order, Finance Charge

Note: For line items on transactions, you may only set values for line items in edit mode.

Table 1
Code Name accountnumber amount amountdue amountpaid balance barcode billaddress billingschedule billingschedule ccinfo ccnumber companyaddress companyfednum companylogo companyname companyphone companyurl createpo creditcardprocessor currencyname customername description discountitem Field Name Acct. No. Amount Amount Due Amount Paid Balance Barcode Bill To Bill. Sched. Billing Schedule Credit Card Info Credit Card # Company Address Business Number Company Logo Company Name Company Phone Company URL Create PO Credit Card Processor Currency Customer Description Discount items payment items Print Both Both Both Both Both Both Screen Screen Screen Screen Print payment Print Print Off Print Off Off Off Print Both Print Off Print Off Off Off Print Off Print Off Off Off Off Both Print Off Print Off Off Off Off Screen Screen address main main Print Both Both Both Off Off Both Off Off Print Print Off Tab Remittance Slip Return Request Credit off both Return Request Cash off both Online Order Invoice off both Online Order Cash Sale off both

Client SuiteScript Developers Guide

Code Names Code Names by Field Type

50

Code Name enddate entity exchangerate excludecommission fob formtitle grossamt istaxable istaxable item job memo options otherrefnum pagenumber partner paymentmethod paypalstatus paypaltranid percentcomplete porate povendor project promocode quantity quantityavailable quantitybackordere d quantitycommitted quantityfulfilled quantityonhand quantityreceived rate

Field Name End Date Entity Exchange Rate Exclude Commissions FOB Form Title Gross Amt Tax Taxable Item Job Memo Options Ref. No. Page Number Partner Pymt. Method PayPal Status PayPal Tran. ID % Complete PO Rate PO Vendor Project Promotion Code Quantity Available Back Ordered Committed Quantity This Shipment On Hand Received Rate

Tab main main items main shipping

Remittance Slip

Return Request Credit

Return Request Cash

Online Order Invoice Off

Online Order Cash Sale Off Screen Screen Off Off Print Both Both Screen Both Off Screen Both Print Print Off Both Screen Screen

Screen Screen Off

Screen Screen Off

Screen Screen Off Off

Print

Print Both Both

Print Both Both Screen Both Off Screen Both Print Print Off Both

Print Both Both Screen Both Off Screen Both Print Print Off

items

Screen Both Off

main

Screen Both

main

Print Print

main payment payment payment

Off

Off Off Off Print items Both Both Print Print Both Both Off Off Off Off Off Screen Both Screen Both Both

Off Off Off Print Both Both Off Off Off Off Off

Both

Client SuiteScript Developers Guide

Code Names Code Names by Field Type

51

Code Name revrecenddate

Field Name Revenue Recognition End Date Revenue Recognition End Date Revenue Recognition Schedule Revenue Recognition Schedule Revenue Recognition Start Date Revenue Recognition Start Date Sales Rep Ship To Ship Date Shipment # Ship Via Shipping Cost Customer Start Date Start Date Subcustomer/Job Subtotal Supervisor Approval Tax Amt Tax Code Tax Item Tax Rate Tax Rate Tax Total

Tab main

Remittance Slip

Return Request Credit Off

Return Request Cash Off

Online Order Invoice Off

Online Order Cash Sale Off

revrecenddate

Off

Off

Off

Off

revrecschedule

main

Off

Off

Off

Off

revrecschedule

Off

Off

Off

Off

revrecstartdate

main

Off

Off

Off

Off

revrecstartdate

Off

Off

Off

Off

salesrep shipaddress shipdate shipid shipmethod shippingcost shipto startdate startdate subname subtotal supervisorapproval tax1amt taxcode taxitem taxrate taxrate1 taxtotal

main address shipping shipping shipping shipping main main

Off Off

Off Off

Off Both Print

Off Both Print

Both Off

Both Off

Off

Off

Both main Both Screen items items Screen Screen Both Both

Both

Both

Both

Both Screen Screen Screen Both Both

Both Screen Screen Screen Both Both

Both Screen Screen Screen Both Both

Client SuiteScript Developers Guide

Code Names Code Names by Field Type

52

Code Name terminmonths

Field Name Revenue Recognition Term in Months Terms Terms Title To Be E-mailed To Be Faxed To Be Printed Total Total Pkgs. Total Weight Tracking # Date Record Doc. No. Ultimate Destination Unapplied Units Tax Id Weight Weighted Total Win/Loss Reason

Tab

Remittance Slip

Return Request Credit

Return Request Cash

Online Order Invoice

Online Order Cash Sale

terms terms title tobeemailed tobefaxed tobeprinted total totalpackages totalweight trackingnumbers trandate trandocnkey tranid ultimatedestination unapplied units vatregnum weight weightedtotal winlossreason

main

Off

main output output output Off Off Off Both main main shipping main Both Both Both Both Both Both Off Off Off Both Off Off Off Both Off Off Off Both

main main items

Print

Both

Both

Both

Both

main items main main

Both

Both

Both

Both

Table 2
Code Name account accountnumber actionitem aging1 aging2 aging3 aging4 Field Name Account Acct. No. Action Item Aging: Current Aging: 1-30 Days Aging: 31-60 Days Aging: 61-90 Days main Screen Print Print Print Print Tab main Opportunity Drop Ship Purchase Order Screen Off Shipping Label Return Form Statement

Client SuiteScript Developers Guide

Code Names Code Names by Field Type

53

Code Name aging5 agingbal altsalesamt amount amountdue amountenclosed amountremaining availableoffline balance balance barcode billaddress charge class class companyaddress companyfednum companylogo companyname companyphone companyurl createdfrom creditlimit currencyname customer customername customform datecol department department description duedate

Field Name Aging: Over 90 Days Aging: Amount Due Alt.Sales Amount Amount Due Amount Encl. Open Amount Always Available Offline Balance Balance Barcode Bill To Charge Class Class Company Address Business Number Company Logo Company Name Company Phone Company URL Created From Credit Limit Currency Customer Customer Custom Form Date Department Department Description Due Date

Tab

Opportunity

Drop Ship Purchase Order

Shipping Label

Return Form

Statement Print Print

Screen Screen Both Print Print Off main main Screen Off Print Print address Both Both Print Print Print Off main Screen Screen Screen Print Off Print Off Off Off main Screen Off items Screen Screen Screen Print main Screen Screen Print Off main Screen Screen main Screen Screen Both Both Print Print Off Off Print Print Off Print Off Print Off Off Off

Client SuiteScript Developers Guide

Code Names Code Names by Field Type

54

Code Name duedate employee enddate entity entitystatus exchangerate expectedclosedate fob forecasttype formtitle grossamt isbillable item job leadsource location location memo memo message options orderstatus otherrefnum otherrefnum pagenumber partner payment probability projaltsalesamt project projectedtotal quantity quantityavailable quantityonhand

Field Name Due Date Employee End Date Entity Entity Status Exchange Rate Exp. Close Date FOB Forecast Type Form Title Gross Amt Billable Item Job Lead Source Location Location Memo Memo Message Options Order Status Ref. No. PO/Check # Page Number Partner Payment Probability Alt.Sales Amount Project Projected Total Quantity Available On Hand

Tab

Opportunity

Drop Ship Purchase Order

Shipping Label

Return Form

Statement Off

main

Screen Off

main main items main shipping main

Screen Screen Screen Screen

Screen

Screen

Off Screen Print Both Both Screen Screen Off Both Print Print Print

main

Screen Off Off Screen Screen Off

main main

Screen Screen

output

Both Both

main main Both Off Print main Screen Print main main Screen Screen Off main Screen Screen Off Off Both Off Off Print Print Print

Client SuiteScript Developers Guide

Code Names Code Names by Field Type

55

Code Name quantityreceived rate reason returnaddress rmanum salesrep serialnumbers shipaddress shipdate shipmethod shipto startdate subname subtotal supervisorapproval tax1amt taxcode taxrate1 terminmonths

Field Name Received Rate Reason For Returning Ship Returns To Ret. Auth. # Sales Rep Serial Numbers Ship To Ship Date Ship Via Customer Start Date Subcustomer/Job Subtotal Supervisor Approval Tax Amt Tax Code Tax Rate Revenue Recognition Term in Months Terms Terms Title To Be E-mailed To Be Faxed To Be Printed Total Tracking # Date Doc. No. Units Tax Id

Tab

Opportunity

Drop Ship Purchase Order Screen

Shipping Label

Return Form

Statement

Screen

Both Print Print Print

main

Screen Screen Both Both Both Both Screen Print

Off

address shipping shipping main

Both

Off Off Both main Both Screen Both Off Screen Both Screen Both

terms terms title tobeemailed tobefaxed tobeprinted total trackingnumbers trandate tranid units vatregnum

main

Off

Off Off

main output output output

Screen Screen Screen Screen Both

shipping main main Screen Screen Screen main Both

Both Both Both Both Both Print Print

Client SuiteScript Developers Guide

Code Names Code Names by Field Type

56

Code Name weightedtotal winlossreason

Field Name Weighted Total Win/Loss Reason

Tab main main

Opportunity Screen Screen

Drop Ship Purchase Order

Shipping Label

Return Form

Statement

Table 3
Packing Slip Off Picking Ticket Off Return Authorization - Cash Off Screen Both main Return Authorization - Credit Off Screen Both Sales Order Progress Billing Off Screen Both Off

Code Name

Field Name

Tab

accountnumber altsalesamt amount balance balance barcode billaddress billingschedule billingschedule ccapproved ccnumber class class companyaddress companyfednum companylogo companyname companyphone companyurl createdfrom createpo creditcardprocessor currencyname customform department department

Acct. No. Alt.Sales Amount Balance Balance Barcode Bill To Bill. Sched. Billing Schedule Credit Card Approved Credit Card # Class Class Company Address Business Number Company Logo Company Name Company Phone Company URL Created From Create PO Credit Card Processor Currency Custom Form Department Department main payment items main main main payment address main

Print Off

Print

Print Both

Print Both

Print Both Screen Off

Screen Both Off Screen Print Off Print Off Off Off Print Off Print Off Off Off Print Off Print Off Off Off Screen Off Screen Print Off Print Off Off Off Screen Off Screen Print Off Print Off Off Off Screen Screen Screen Screen Screen Off Off Screen Screen Screen Off Screen Screen Screen Off Screen

payment Both Off

Client SuiteScript Developers Guide

Code Names Code Names by Field Type

57

Code Name

Field Name

Tab

Packing Slip Print

Picking Ticket Print

Return Authorization - Cash Both Both

Return Authorization - Credit Both Both

Sales Order Progress Billing Both Both Screen

description discountitem enddate entity exchangerate excludecommission fob formtitle grossamt istaxable istaxable item job location location memo message opportunity options orderstatus otherrefnum pagenumber partner paymentmethod percentcomplete porate povendor project promocode quantity quantitybackordere d quantitycommitted

Description Discount End Date Entity Exchange Rate Exclude Commissions FOB Form Title Gross Amt Tax Taxable Item Job Location Location Memo Message Opportunity Options Order Status Ref. No. Page Number Partner Pymt. Method % Complete PO Rate PO Vendor Project Promotion Code Quantity Back Ordered Committed items main main main main main output main items items main main items main

Off Screen Screen Screen Screen Screen Screen

Screen Screen Screen Off

shipping Off Print Print Print Both Both Screen Print Off Off Off Print Both Off Off Screen Off Print Off Screen Both Print Both Both Screen Both Off Off Screen Screen Both

Print Both Both Screen Both Off Off Screen Screen Both Screen

Print

Print

Both Screen

Both Screen Both Print Screen

Both Screen Both Print Screen

Off Print Off

Off Print

Both Print Screen Both

payment Off

Screen Off Off Off Print Both Print Print Off Print Both Print Both Both Print Both Off

Client SuiteScript Developers Guide

Code Names Code Names by Field Type

58

Code Name

Field Name

Tab

Packing Slip

Picking Ticket Print Off

Return Authorization - Cash

Return Authorization - Credit

Sales Order Progress Billing

quantityfulfilled quantityonhand quantityordered quantityreceived quantityremaining rate revrecenddate

Quantity This Shipment On Hand Qty. Ordered Received Remaining Rate Revenue Recognition End Date Revenue Recognition End Date Revenue Recognition Schedule Revenue Recognition Schedule Revenue Recognition Start Date Revenue Recognition Start Date Sales Rep Serial Numbers Ship To Ship Date Shipment # Ship Via Shipping Cost Start Date Subtotal Tax Amt Tax Code Tax Item Tax Rate items items address main Off Print Print main main main Print Print

Screen Off Both Off

Screen

Both Off

Off Off

revrecenddate

Screen

Screen

Screen

revrecschedule

Off

Off

Off

revrecschedule

Screen

Screen

Screen

revrecstartdate

Off

Off

Off

revrecstartdate

Screen

Screen

Screen

salesrep serialnumbers shipaddress shipdate shipid shipmethod shippingcost startdate subtotal tax1amt taxcode taxitem taxrate

Screen Print Print Off Both Off

Screen Both Off

Screen Off Off Off

shipping Print shipping Off shipping Print shipping main Off

Off

Off Off Screen Both Both Screen Screen Screen Both Both Screen Screen Screen Both Both Screen Screen Screen

Client SuiteScript Developers Guide

Code Names Code Names by Field Type

59

Code Name

Field Name

Tab

Packing Slip

Picking Ticket

Return Authorization - Cash Both Both Off

Return Authorization - Credit Both Both Off

Sales Order Progress Billing Both Both Off

taxrate1 taxtotal terminmonths

Tax Rate Tax Total Revenue Recognition Term in Months Terms To Be E-mailed To Be Faxed To Be Printed Total Tracking # Date Doc. No. Units Tax Id main shipping Print main main Print Print Print Off Print Print Print main output output output

terms tobeemailed tobefaxed tobeprinted total trackingnumbers trandate tranid units vatregnum

Both Screen Screen Screen Both Screen Screen Screen Both Screen Screen Screen Both Off Both Both Both Both Both Both Both Both Both Both Off Both

Table 4
Code Name account accountnumber aging1 aging2 aging3 aging4 aging5 agingbal altsalesamt amount amountordered amountpaid amountremaining Field Name Account Acct. No. Aging: Current Aging: 1-30 Days Aging: 31-60 Days Aging: 61-90 Days Aging: Over 90 Days Aging: Amount Due Alt.Sales Amount Order Amt. Amount Paid Amount Remaining main main Both Both Off Off Off Off Tab main Progress Invoice Screen Off Off Off Off Off Off Off Screen Both Screen Both Both Both Off Off Off Off Off Sales Order Cash Sale Sales Order Invoice Canada Finance Charge Screen Off Off Off Off Off Off Off Service Invoice Screen Off Off Off Off Off Off Off

Client SuiteScript Developers Guide

Code Names Code Names by Field Type

60

Code Name balance barcode billaddress billeddate billingschedule billingschedule ccapproved ccnumber class class companyaddress companyfednum companylogo companyname companyphone companyurl createdfrom createpo

Field Name Balance Barcode Bill To Date Billed Bill. Sched. Billing Schedule Credit Card Approved Credit Card # Class Class Company Address Business Number Company Logo Company Name Company Phone Company URL Created From Create PO

Tab main

Progress Invoice Off Print

Sales Order Cash Sale

Sales Order Invoice Off

Canada Finance Charge Off Print Both

Service Invoice Off Print Both Off

Print Both

Print Both

address

Both Off

main

Screen Off

Screen Off

payment payment Off main Screen Print Off Print Off Off Off main Screen

Screen Both Off Screen Print Off Print Off Off Off Screen Screen Off Screen Print Off Print Off Off Off Screen Screen Off Screen Print Off Print Off Off Off Screen Off Screen Print Off Print Off Off Off Screen

creditcardprocessor Credit Card Processor currencyname currentpercent customform department department description discountamount discountdate discountitem duedate employee employeefullname enddate Currency Current % Custom Form Department Department Description Disc. Amt. Disc. Date Discount Due Date Employee (Initials) Employee (Full Name) End Date

payment items Screen Both main Screen Off main Screen Both main main items main Off Off Both Both Off Off main Screen

Screen Screen Screen Screen Screen Off Screen Off Screen Both Screen Off Screen Both Screen Off Screen Both Screen Off Screen Both Off Off Both Both Both Both Both Both Off Off Screen Screen Both

Client SuiteScript Developers Guide

Code Names Code Names by Field Type

61

Code Name entity event exchangerate excludecommissio n fob formtitle grossamt istaxable istaxable item job location location memo message opportunity options orderstatus otherrefnum pagenumber partner paymentmethod paypalstatus paypaltranid percentcomplete porate postingperiod povendor project promocode quantity quantityavailable

Field Name Entity Event Exchange Rate Exclude Commissions FOB Form Title Gross Amt Tax Taxable Item Job Location Location Memo Message Opportunity Options Order Status Ref. No. Page Number Partner Pymt. Method PayPal Status PayPal Tran. ID % Complete PO Rate Posting Period PO Vendor Project Promotion Code Quantity Available

Tab main

Progress Invoice Screen Off

Sales Order Cash Sale Screen

Sales Order Invoice Screen

Canada Finance Charge Screen

Service Invoice Screen Off

items main

Screen

Screen Screen Off Print Both Both Screen Both Off Off Screen Screen Both Screen Both Screen

Screen Screen Off Print Both Both Screen Both Off Off Screen Screen Both Screen Both Screen Both Print Screen

Screen

Screen

shipping Off Print Both Both items Screen Both Off Off main main output main Screen Screen Both Screen Both main main Both Print main payment payment payment Both Screen

Off Print Both Both Off Both

Off Print Both Both Screen Both Off

Off Screen Screen Both

Off Screen Screen Both Screen

Off

Both

Both Print Screen Both Screen Screen Off Off

Off Print Off

Both Print Screen

Off Off Screen

Off

main

Screen Off Print Print Both Both Off Screen Off Print Both Both Off Screen

Screen

Print Both Off

Print Both Both Off

items

Both Off

quantitybackordere Back Ordered d

Client SuiteScript Developers Guide

Code Names Code Names by Field Type

62

Code Name quantitycommitted quantityfulfilled quantityonhand quantityordered quantityremaining rate revrecenddate

Field Name Committed Quantity This Shipment On Hand Qty. Ordered Remaining Rate Revenue Recognition End Date Revenue Recognition End Date Revenue Recognition Schedule Revenue Recognition Schedule Revenue Recognition Start Date Revenue Recognition Start Date Sales Rep Serial Numbers Ship To Ship Date Ship Via Shipping Cost Start Date Subtotal Tax Amt Tax Code Tax Item Tax Rate Tax Rate Tax Total

Tab

Progress Invoice

Sales Order Cash Sale Screen Screen Off

Sales Order Invoice Screen Screen Off

Canada Finance Charge

Service Invoice

Off Off Off Screen

Off

Off main Off

Both Off

Both Off

Off Off

Both Off

revrecenddate

Screen

Screen

Screen

Screen

Screen

revrecschedule

main

Off

Off

Off

Off

Off

revrecschedule

Screen

Screen

Screen

Screen

Screen

revrecstartdate

main

Off

Off

Off

Off

Off

revrecstartdate

Screen

Screen

Screen

Screen

Screen

salesrep serialnumbers shipaddress shipdate shipmethod shippingcost startdate subtotal tax1amt taxcode taxitem taxrate taxrate1 taxtotal

main

Screen Off

Screen Both Both Both Both Off Screen Both Both Screen Screen Screen Both Both

Screen Both Both Both Both Off Screen Both Both Screen Screen Screen Both Both

Off Off Off Off

Screen Both Off Off Off Off Both

address

Off

shipping Off shipping Off shipping Off main Screen Both Both Screen items items Screen Screen Both Both

Both Both Screen Off Off Both Both

Both Both Screen Screen Screen Both Both

Client SuiteScript Developers Guide

Code Names Code Names by Field Type

63

Code Name terminmonths

Field Name Revenue Recognition Term in Months Terms To Be E-mailed To Be Faxed To Be Printed Total Tracking # Date Doc. No. Units Tax Id

Tab

Progress Invoice

Sales Order Cash Sale Off

Sales Order Invoice Off

Canada Finance Charge

Service Invoice

terms tobeemailed tobefaxed tobeprinted total trackingnumbers trandate tranid units vatregnum

main output output output

Both Screen Screen Screen Both Screen Screen Screen Both Both Both Both Both Both

Both Screen Screen Screen Both Both Both Both Both Both

Both Screen Screen Screen Both

Both Screen Screen Screen Both Off

shipping Off main main Both Both Off main Both

Both Both Off Both

Both Both Both Both

Table 5
Code Name account accountnumber aging1 aging2 aging3 aging4 aging5 agingbal amount amountordered amountpaid amountremaining applied balance barcode billaddress Field Name Account Acct. No. Aging: Current Aging: 1-30 Days Aging: 31-60 Days Aging: 61-90 Days Aging: Over 90 Days Aging: Amount Due Amount Order Amt. Amount Paid Amount Remaining Applied Balance Barcode Bill To address main main items main Off Print Both Off Print Both Tab main Product Invoice Screen Off Off Off Off Off Off Off Both Off Off Off Professional Invoice Screen Off Off Off Off Off Off Off Both Off Off Off Off Off Screen Off Print Both Print Both Both Both Off Credit Memo Screen Off Cash Sale Screen Off

Client SuiteScript Developers Guide

Code Names Code Names by Field Type

64

Code Name billeddate ccapproved ccnumber class class companyaddress companyfednum companylogo companyname companyphone companyurl createdfrom

Field Name Date Billed Credit Card Approved Credit Card # Class Class Company Address Business Number Company Logo Company Name Company Phone Company URL Created From

Tab

Product Invoice Off

Professional Invoice Off

Credit Memo

Cash Sale

payment payment Off main Screen Print Off Print Off Off Off main payment items Screen Off main Screen Off main Screen Both main main items main Off Off Both Both Off Off main main main Off items Screen Off Screen Off Print Both Print Both Screen Screen Screen Screen Off Screen Off Screen Both Off Off Both Both Off Off Both Screen Screen Both Screen Off Screen Both Screen Screen Off Screen Print Off Print Off Off Off Screen Off Screen Print Off Print Off Off Off Screen

Screen Both Off Screen Print Off Print Off Off Off Screen Screen Screen Off Screen Off Screen Both

creditcardprocessor Credit Card Processor currencyname currentpercent customform department department description discountamount discountdate discountitem duedate employee employeefullname enddate entity entitystatus event exchangerate fob formtitle grossamt Currency Current % Custom Form Department Department Description Disc. Amt. Disc. Date Discount Due Date Employee (Initials) Employee (Full Name) End Date Entity Entity Status Event Exchange Rate FOB Form Title Gross Amt

Both

Both Screen

Screen Off Print Both

shipping Both Print Both

Client SuiteScript Developers Guide

Code Names Code Names by Field Type

65

Code Name istaxable istaxable item job location location memo message opportunity options otherrefnum pagenumber partner paymentmethod paypalstatus paypaltranid percentcomplete postingperiod project promocode quantity quantityavailable quantityfulfilled quantityonhand quantityordered quantityremaining rate revrecenddate

Field Name Tax Taxable Item Job Location Location Memo Message Opportunity Options Ref. No. Page Number Partner Pymt. Method PayPal Status PayPal Tran. ID % Complete Posting Period Project Promotion Code Quantity Available Quantity This Shipment On Hand Qty. Ordered Remaining Rate Revenue Recognition End Date Revenue Recognition End Date Revenue Recognition Schedule

Tab

Product Invoice Both

Professional Invoice Both Screen Both Off Off Screen Screen Both Screen Both Off Print Screen

Credit Memo Both Screen Both Off Off Screen Screen Both

Cash Sale Both Screen Both Off Off Screen Screen Both Screen

items

Screen Both Off Off

main main output main

Screen Screen Both Screen Both

Both Both Print Screen

Both Both Print Screen Both Screen Screen

main

Both Print

main payment payment payment

Both

Off main Screen Print items Both Both Off Off Off Off Screen Both main Off

Off Screen Print Both Off Off Off Off Off Off Off Off Both Off Screen Print Both Both

Off Screen Print Both Both Off Off Off Off Screen Both Off

revrecenddate

Screen

Screen

Screen

Screen

revrecschedule

main

Off

Off

Off

Off

Client SuiteScript Developers Guide

Code Names Code Names by Field Type

66

Code Name revrecschedule

Field Name Revenue Recognition Schedule Revenue Recognition Start Date Revenue Recognition Start Date Sales Rep Serial Numbers Ship To Ship Date Ship Via Shipping Cost Start Date Subtotal Tax Amt Tax Code Tax Item Tax Rate Tax Rate Tax Total Terms To Be E-mailed To Be Faxed To Be Printed Total Tracking # Date Doc. No. Unapplied Units Tax Id

Tab

Product Invoice Screen

Professional Invoice Screen

Credit Memo Screen

Cash Sale Screen

revrecstartdate

main

Off

Off

Off

Off

revrecstartdate

Screen

Screen

Screen

Screen

salesrep serialnumbers shipaddress shipdate shipmethod shippingcost startdate subtotal tax1amt taxcode taxitem taxrate taxrate1 taxtotal terms tobeemailed tobefaxed tobeprinted total trackingnumbers trandate tranid unapplied units vatregnum

main

Both Both

Screen Off Off Off Off Off Both Both Both Screen Screen Screen Both Both Both Screen Screen Screen Both Off Both Both

Screen Both

Screen Both Off Off

address

Both

shipping Both shipping Both shipping Off main Screen Both Both Screen items items Screen Screen Both Both main output output output Both Screen Screen Screen Both shipping Both main main items Both main Both Both Both

Off Off

Off Off Both

Both Both Screen Screen Screen Both Both

Both Both Screen Screen Screen Both Both

Screen Screen Screen Both

Screen Screen Screen Both Off

Both Both Screen

Both Both

Off Both

Both Both

Both Both

Client SuiteScript Developers Guide

Code Names Code Names by Field Type

67

Table 6

Code Name account accountnumber aging1 aging2 aging3 aging4 aging5 agingbal altsalesamt amount amountpaid amountremaining balance barcode billaddress billingschedule billingschedule ccapproved ccnumber class class companyaddress companyfednum companylogo companyname companyphone companyurl createdfrom

Field Name Account Acct. No. Aging: Current Aging: 1-30 Days Aging: 31-60 Days Aging: 61-90 Days Aging: Over 90 Days Aging: Amount Due Alt.Sales Amount Amount Paid Amount Remaining Balance Barcode Bill To Bill. Sched. Billing Schedule Credit Card Approved Credit Card # Class Class Company Address Business Number Company Logo Company Name Company Phone Company URL Created From

Tab main

Cash Refund Screen Off

Estimate

Purchase Order Screen

Finance Charge Screen Off Off Off Off Off Off Off

Off

Screen Both main main main Print address main Both Off Print Both Screen Off payment Screen payment Both Off main Screen Print Off Print Off Off Off main Screen Off Screen Print Off Print Off Off Off Screen Screen Print Off Print Off Off Off Screen Off Screen Print Off Print Off Off Off Screen Print Both Both Both Both Off Off Off Print Both

creditcardprocessor Credit Card Processor

payment Screen

Client SuiteScript Developers Guide

Code Names Code Names by Field Type

68

Code Name currencyname customer customform department department description discountitem duedate employee enddate entity entitystatus exchangerate expectedclosedate fob forecasttype formtitle grossamt includeinforecast isbillable istaxable istaxable item job location location memo message opportunity options otherrefnum pagenumber partner paymentmethod

Field Name Currency Customer Custom Form Department Department Description Discount Due Date Employee End Date Entity Entity Status Exchange Rate Exp. Close Date FOB Forecast Type Form Title Gross Amt Include In Forecast Billable Tax Taxable Item Job Location Location Memo Message Opportunity Options Ref. No. Page Number Partner Pymt. Method

Tab items

Cash Refund Screen

Estimate Screen

Purchase Order Screen Screen

Finance Charge Screen

main

Screen Off

Screen Off Screen Both Both Both

Screen Screen Screen Both

Screen Off Screen Both Both

main

Screen Both

items main main main main main items main shipping main

Both

Both Screen

Both

Off Screen Screen Screen Screen Screen Both Off Screen Print Both Print Both Screen Screen Both Both Screen Both Off Off Screen Screen Both Screen Both Both Off Print Screen Both Both Print Off Off Print Off Off Screen Screen Both Off Screen Screen Both Both Off Off Both Print Both Print Both Off Off Screen Screen Screen Screen

main

items

Screen Both Off Off

main main output main

Screen Screen Both

main

Both Print

main

Screen

payment Both

Client SuiteScript Developers Guide

Code Names Code Names by Field Type

69

Code Name postingperiod probability project promocode quantity quantityavailable quantityonhand quantityreceived rate revrecenddate

Field Name Posting Period Probability Project Promotion Code Quantity Available On Hand Received Rate Revenue Recognition End Date Revenue Recognition End Date Revenue Recognition Schedule Revenue Recognition Schedule Revenue Recognition Start Date Revenue Recognition Start Date Sales Rep Serial Numbers Ship To Ship Date Ship Via Shipping Cost Customer Start Date Subtotal Supervisor Approval Tax Amt

Tab main main

Cash Refund Screen

Estimate

Purchase Order

Finance Charge Screen

Screen Print Print Both Both Off Off Both Off Off Screen Both Both Both Off Off Print Both Off

items

Both Both

main

Off

revrecenddate

Screen

Screen

revrecschedule

main

Off

Off

revrecschedule

Screen

Screen

revrecstartdate

main

Off

Off

revrecstartdate

Screen

Screen

salesrep serialnumbers shipaddress shipdate shipmethod shippingcost shipto startdate subtotal supervisorapproval tax1amt

main

Screen Both

Screen Both Off Off Off Off Off Off Both Off Off Off

Off Off Off Off

address shipping shipping Off shipping Off main main Both main Both

Both

Both Screen

Both

Both

Both

Both

Client SuiteScript Developers Guide

Code Names Code Names by Field Type

70

Code Name taxcode taxitem taxrate taxrate1 taxtotal terminmonths

Field Name Tax Code Tax Item Tax Rate Tax Rate Tax Total Revenue Recognition Term in Months Terms To Be E-mailed To Be Faxed To Be Printed Total Tracking # Date Doc. No. Units Tax Id

Tab

Cash Refund Screen

Estimate Screen Screen Screen Both Both Off

Purchase Order Screen

Finance Charge Screen Off Off

items items

Screen Screen Both Both

Both

Both Both

terms tobeemailed tobefaxed tobeprinted total trackingnumbers trandate tranid units vatregnum

main output output output Screen Screen Screen Both shipping main main Both Both Both main Both

Off Screen Screen Screen Both Off Both Both Both Both

Off Screen Screen Screen Both Off Both Both Both Both

Both Screen Screen Screen Both

Both Both Off Both

Client SuiteScript Developers Guide

Appendix: Tutorial Code


Following is the complete code used for the tutorial in Chapter 3 "Client SuiteScript Tutorial". Copy this information exactly as it appears here. Comments are included in the code to help illustrate the purpose of each portion of the code.
//===================================================== function samplePageInit() { // Customers that make purchases in the store, as opposed to from a Web site, // automatically receives a 5% in-store transaction discount. This discount is // NOT in addition to other discounts they may have available to them. // // NOTE: you could also have used nlapiSetFieldText('discountitem', 'In-store // Discount'); // The 92 is the ID of the item in your NetSuite account. You can determine the // ID of an item by navigating to the item, and inspecting the id= parameter of // the URL. nlapiSetFieldValue('discountitem', 92); } //===================================================== function sampleSaveRecord() { return confirm("Are you sure you want to save this record?"); } //===================================================== function sampleValidateField(type, name) { // This script does not allow discounts equal to or greater than $50 or greater // than 30%, without manager approval. // If the transaction discount rate is positive, which adds to the order total, // prompt to reset the transaction discount to the better of the In-store or // Cust. Discount. // // Also, if the rate is a percent and is not as high as the Cust. Discount or // In-store Discount, check to see if they would like to reset the discount // to the higher rate. // // // The three variable initialization functions that are called from this function (calcIsPercent, calcTransactionDiscountRate and calcCustomerDiscountRate) are defined at the end of this script file.

if (name == 'discountrate') { // intialize variables

Client SuiteScript Developers Guide

Appendix: Tutorial Code

72

// Customers that purchase in the store, as opposed to from a Web site, // automatically receive a 5% in-store transaction discount. var instore_discount = -5; // Start by assuming the customer discount is better than the in-store // discount. var useCustomerDiscount = true; // Is the transaction discount field a percent? var isPercent = calcIsPercent(); // If a transaction discount is present, set tran_discount_rate, // otherwise initialize to zero. var tran_discount_rate = calcTransactionDiscountRate(); // If a customer discount is present, set cust_discount, // otherwise initialize to zero. var cust_discount = calcCustomerDiscountRate(); // If the In-store discount is higher than the customer discount, use it // instead. if ( instore_discount <= cust_discount ) useCustomerDiscount = false; // Check to see that the discount is not a percent. if (!isPercent) { // If the discount is not a percent... // Is the transaction discount rate > 0 (which adds to the order total)? // If so, prompt to reset Transaction Discount to the higher of In-house or // Cust. Discount if (tran_discount_rate > 0) { if ( confirm("The Transaction Discount Rate is positive, which adds to the order total.\n\nReset Transaction Discount to the better of Cust. Discount or In-store Discount?\n\n(OK = Yes, Cancel = No)") ) { // Use the higher of the In-store or the Cust. Discount rate. if( useCustomerDiscount ) { // alert("custbody_cust_discount: '" + nlapiGetFieldText('custbody_cust_discount') + "'"); nlapiSetFieldText('discountitem', nlapiGetFieldText('custbody_cust_discount')); } else { nlapiSetFieldText('discountitem', "In-store Discount"); } } } // If the discount is not percent, is the discount equal to or more than // $50? else if (parseInt(nlapiGetFieldValue('discountrate')) <= -50) { if (!confirm("Please confirm that you have a manager's approval for this discount amount.\n\n(OK = Yes, Cancel = No)")) { // Use the higher of the In-store or the Cust. Discount rate if( useCustomerDiscount ) { alert("Discount level not approved, resetting to Customer

Client SuiteScript Developers Guide

Appendix: Tutorial Code

73

Discount."); // alert("custbody_cust_discount: '" + nlapiGetFieldText('custbody_cust_discount') + "'"); nlapiSetFieldText('discountitem', nlapiGetFieldText('custbody_cust_discount')); } else { alert("Discount level not approved, resetting to In-store Discount."); nlapiSetFieldText('discountitem', "In-store Discount"); } } } } // If the discount is a percent... // Is that percent more than 30% off? else { if ( parseFloat(nlapiGetFieldValue('discountrate')) < -30 ) { // If so, prompt... if (!confirm("Please confirm that you have a manager's approval for this discount percent.\n\n(OK = Yes, Cancel = No)")) { // Reset to the higher of In-store discount or Cust. Discount. if( useCustomerDiscount ) { alert("Discount level not approved, resetting to Customer Discount."); nlapiSetFieldText('discountitem', nlapiGetFieldText('custbody_cust_discount')); } else { alert("Discount level not approved, resetting to In-store Discount."); nlapiSetFieldText('discountitem', "In-store Discount"); } } } // If the Transaction Discount Rate is a percent and is lower than Cust. // Discount or In-Store Discount, then prompt to reset Transaction Discount // to the higher of the two. if (tran_discount_rate > cust_discount || tran_discount_rate > instore_discount) { if ( confirm("The Transaction Discount Rate is not as good as the Cust. Discount or the In-store Discount.\n\nReset Transaction Discount to the better of the two?\n\n(OK = Yes, Cancel = No)") ) { // Use the higher of the In-store or Cust. Discount rate. if( useCustomerDiscount ) {

Client SuiteScript Developers Guide

Appendix: Tutorial Code

74

// alert("custbody_cust_discount: '" + nlapiGetFieldText('custbody_cust_discount') + "'"); nlapiSetFieldText('discountitem', nlapiGetFieldText('custbody_cust_discount')); } else { nlapiSetFieldText('discountitem', "In-store Discount"); } } } } } // If any single line-item quantity exceeds 20, ask if this is correct. else if ( (type == 'item') && (name == 'quantity') ) { var count = parseFloat(nlapiGetCurrentLineItemValue('item', 'quantity')); if(count > 20) { return confirm("Do you really want to add " + count + " of this item?\n\n(OK = Yes, Cancel = No)"); } } // Always return true at this level to validate all the fields that you // are not specifically validating... return true; } //===================================================== function sampleFieldChanged(type, name) { // A custom checkbox field for customers records whether the customer has "had // order problems." // A locked transaction body field (checkbox) sources the value from the // customer record onto the transaction. // On field change of customer (entity), check the sourced locked field. If it // is "T", then pop an alert saying // "This customer has had order problems previously. Be sure to verify all // items with the customer before // submitting the order." if (name == 'custbody_had_order_problems') { // if customer is not null and this customer has had order problems, // remind the employee to double check the order... 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; } } return true;

Client SuiteScript Developers Guide

Appendix: Tutorial Code

75

} //===================================================== function sampleValidateLine(type) { // Prevents a service line item to be added without specifying the service rep // employee. // // // // // // // alert("service item flag: " + nlapiGetCurrentLineItemValue('item', 'custcol_service_item')); alert("service rep: " + nlapiGetCurrentLineItemText('item', 'custcol_service_rep')); if ( (nlapiGetCurrentLineItemValue('item', 'custcol_service_item') == 'T') && (String(nlapiGetCurrentLineItemText('item', 'custcol_service_rep')) == "") )

if ( (nlapiGetCurrentLineItemValue('item', 'custcol_service_item') == 'T') && (!nlapiGetCurrentLineItemText('item', 'custcol_service_rep')) ) //(nlapiGetCurrentLineItemText('item', 'custcol_service_rep')) == "" ) { alert("You must choose a Service Rep for this service item."); return false; } return true; } //===================================================== function sampleRecalc(type) { // // // // // For each service line item that is added, its total is added to the service bookings field. The custcol_service_item field sources its value from the Service Item custom field checkbox on the item.

// initialize total var total = 0; // Run through each line item looking for service items. for ( i = 1; i <= nlapiGetLineItemCount('item'); i++) { // Set item_amount for the current item. var item_amount = parseFloat(nlapiGetLineItemValue('item', 'amount', i)); // If the item is a service item, add its value to the total. if (nlapiGetLineItemValue('item', 'custcol_service_item', i) == 'T') { total += item_amount; } } // Set the service bookings custom field to the total of all service items. nlapiSetFieldValue('custbody_service_bookings', nlapiFormatCurrency(total));

Client SuiteScript Developers Guide

Appendix: Tutorial Code

76

} //===================================================== // // // // The following scripts are the three variable init functions called from the sampleValidateField function.

function calcIsPercent() { // If you cannot find a percent sign in the discount field, set isPercent to // false. if( nlapiGetFieldValue('discountrate').indexOf('%') == -1 ) return false; else return true; } function calcTransactionDiscountRate() { // // If a transaction discount is present, set tran_discount_rate, otherwise initialize to zero.

if( !isNaN(parseFloat(nlapiGetFieldValue('discountrate'))) ) return parseFloat(nlapiGetFieldValue('discountrate')); else return 0; } function calcCustomerDiscountRate() { if( !isNaN(parseFloat(nlapiGetFieldText('custbody_cust_discount'))) ) // Multiply the rate by -1 because all discounts must be negative or they // add to order total. return ((parseFloat(nlapiGetFieldText('custbody_cust_discount'))) * -1); else return 0; } //=====================================================

Client SuiteScript Developers Guide

Das könnte Ihnen auch gefallen