SuiteScript Developer &

SuiteScript Developer & Reference Guide
Version 2012 Release 2 | October 17, 2012
SuiteScript Developer & Reference Guide
Contents
Part 1
Getting Started with SuiteScript
Chapter 1
SuiteScript - The Basics 14
Chapter 2
What is SuiteScript? 16
What can I do with the SuiteScript API? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Using the SuiteScript API with NetSuite Records. . . . . . . . . . . . . . . . . . . . . . . . . . 18
Chapter 3
Setting Up Your SuiteScript Environment 20
Environment Setup Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Configuring NetSuite for SuiteScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Setting Up Your SuiteScript Development Environment (SuiteCloud IDE) . . . .
Working with Your SuiteScript Development Environment (SuiteCloud IDE) .
Working with IDEs Other Than SuiteCloud IDE. . . . . . . . . . . . . . . . . . . . . . . . . .
Part 2
20
20
26
42
70
Running a Script in NetSuite
Chapter 4
Step 1: Create Your Script 74
Chapter 5
Step 2: Add Script to NetSuite File Cabinet 75
Chapter 6
Step 3: Attach Script to Form 76
Chapter 7
Step 4: Create Script Record 79
Steps for Creating a Script Record . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
Creating a Custom Script Record ID . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
Chapter 8
Step 5: Define Script Deployment 87
Steps for Defining a Script Deployment. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
Creating a Custom Script Deployment ID . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
Part 3
Chapter 9
Viewing Script Deployments 90
Chapter 10
Using the Scripted Records Page 91
Chapter 11
Using the Script Execution Log 94
Scripting Records, Fields, Forms, and Sublists
SuiteTalk Platform Guide
Chapter 12
Working with Records and Subrecords in SuiteScript 97
Working with Records in SuiteScript. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
How Records are Processed in Scripting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
Working with Subrecords in SuiteScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
Working with Records in Dynamic Mode. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
Chapter 13
Working with Fields 116
Working with Fields Overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
Referencing Fields in SuiteScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
Working with Custom Fields in SuiteScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
Chapter 14
Working with Subtabs and Sublists 121
Subtabs and Sublists Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Subtabs and Sublists - What’s the Difference? . . . . . . . . . . . . . . . . . . . . . . . . . . .
Sublist Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Adding Subtabs with SuiteScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Adding Sublists with SuiteScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Working with Sublist Line Items . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Working with Item Groups in a Sublist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Working with Sublists in Dynamic Mode and Client
SuiteScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Chapter 15
Working with Online Forms 149
Chapter 16
Inline Editing and SuiteScript 152
Inline Editing and SuiteScript Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Why Inline Edit in SuiteScript? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Inline Editing Using nlapiSubmitField . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Consequences of Using nlapiSubmitField on Non Inline Editable Fields. . . . . .
Inline Editing (xedit) as a User Event Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
What’s the Difference Between xedit and edit User Event Types? . . . . . . . . . . .
Inline Editing and nlapiGetNewRecord() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Inline Editing and nlapiGetOldRecord(). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Part 4
121
121
125
133
135
138
145
146
152
153
153
155
156
157
157
157
Understanding NetSuite Script Types
Chapter 17
Script Types Overview 160
Chapter 18
SuiteScript Execution Diagram 162
SuiteTalk Platform Guide
Chapter 19
Client Scripts 164
What is Client SuiteScript?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Client Script Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Client Event Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Form-level and Record-level Client Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Client Script Metering. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Role Restrictions in Client SuiteScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
How Many Client Events Can I Execute on One Form? . . . . . . . . . . . . . . . . . . .
Error Handling and Debugging Client SuiteScript. . . . . . . . . . . . . . . . . . . . . . . .
Client SuiteScript and Online Forms. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Running a Client Script in NetSuite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Client SuiteScript Samples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Chapter 20
User Event Scripts 183
What Are User Event Scripts? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
User Event Script Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Setting the User Event type Argument. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
User Event Script Execution Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
How Many User Events Can I Have on One Record? . . . . . . . . . . . . . . . . . . . . .
Running a User Event Script in NetSuite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
User Event Script Samples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Chapter 21
183
184
186
189
193
194
194
Suitelets 201
What Are Suitelets?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Suitelet Script Execution. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Building Custom Workflows with Suitelets. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Building Suitelets with UI Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Backend Suitelets. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Restricted Parameters in Suitelet URLs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
SuiteScript and Externally Available Suitelets . . . . . . . . . . . . . . . . . . . . . . . . . . .
Running a Suitelet in NetSuite. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Suitelets Samples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Chapter 22
164
165
166
168
169
170
170
171
172
173
174
202
203
205
205
206
208
209
210
211
RESTlets 222
What Are RESTlets? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
RESTlets vs. Other NetSuite Integration Options. . . . . . . . . . . . . . . . . . . . . . . . .
Creating a RESTlet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Debugging a RESTlet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Sample RESTlet Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Sample RESTlet Input Formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
RESTlet Status Codes and Error Message Formats . . . . . . . . . . . . . . . . . . . . . . .
224
234
237
239
242
246
256
SuiteTalk Platform Guide
Chapter 23
Scheduled Scripts 259
Understanding Scheduled Script Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Deploying Scheduled Scripts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Creating Multiple Deployments for a Scheduled Script . . . . . . . . . . . . . . . . . . . .
Running Scheduled Scripts Using nlapiScheduleScript . . . . . . . . . . . . . . . . . . . .
Setting the Scheduled Script type Argument . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Setting Recovery Points in Scheduled Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Understanding Memory Usage in Scheduled Scripts . . . . . . . . . . . . . . . . . . . . . .
Monitoring Scheduled Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Scheduled Script Samples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Using Multiple Script Queues to Run Scheduled Scripts . . . . . . . . . . . . . . . . . . .
Chapter 24
Portlet Scripts 285
What Are Portlet Scripts? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Portlet Script Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Assigning the Portlet Preference to a Script Parameter . . . . . . . . . . . . . . . . . . . .
Running a Portlet Script in NetSuite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Displaying Portlet Scripts on the Dashboard . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Portlet Scripts Samples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Chapter 25
285
286
287
287
288
288
Mass Update Scripts 296
What Are Mass Update Scripts? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Mass Update Script Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Running a Mass Update Script in NetSuite . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Mass Update Scripts Samples. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Chapter 26
260
264
268
272
272
273
274
276
277
283
296
298
299
300
Bundle Installation Scripts 305
What are Bundle Installation Scripts?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
Setting Up a Bundle Installation Script. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
Sample Bundle Installation Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312
Part 5
Setting Runtime Options
Chapter 27
Setting Runtime Options Overview 317
Chapter 28
Setting Script Execution Event Type from the UI 318
Chapter 29
Setting Script Execution Log Levels 320
Chapter 30
Executing Scripts as Admin 322
Chapter 31
Setting Available Without Login 324
Chapter 32
Setting Script Deployment Status 326
Chapter 33
Defining Script Audience 328
SuiteTalk Platform Guide
Part 6
Part 7
Creating Script Parameters (Custom Fields)
Chapter 34
Creating Script Parameters Overview 331
Chapter 35
Why Create Script Parameters? 332
Chapter 36
Creating Script Parameters 333
Chapter 37
Referencing Script Parameters 336
Chapter 38
Setting Script Parameter Preferences 337
Searching with SuiteScript
Chapter 39
Searching Overview 342
Chapter 40
Understanding SuiteScript Search Objects 343
Chapter 41
Search Samples 346
Creating Saved Searches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Executing Existing Saved Searches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Filtering a Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Returning Specific Fields in a Search. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Searching on Custom Records . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Searching Custom Lists. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Executing Joined Searches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Searching for an Item ID . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Searching for Duplicate Records . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Performing Global Searches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Searching CSV Saved Imports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Using Formulas, Special Functions, and Sorting in Search . . . . . . . . . . . . . . . . .
Using Summary Filters in Search. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Chapter 42
361
346
347
349
352
352
353
354
358
358
359
359
359
360
Supported Search Operators, Summary Types, and Date Filters
Search Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
Search Summary Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
Search Date Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
Part 8
Working with UI Objects
Chapter 43
UI Objects Overview 367
Chapter 44
Creating Custom NetSuite Pages with UI Objects 369
SuiteTalk Platform Guide
Chapter 45
InlineHTML UI Objects 371
Chapter 46
Building a NetSuite Assistant with UI Objects 373
NetSuite UI Object Assistant Overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373
Understanding NetSuite Assistants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373
Using UI Objects to Build an Assistant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
Part 9
Debugging SuiteScript
Chapter 47
Debugging SuiteScript 393
Debugging Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393
Part 10
Chapter 48
Before Using the Debugger 395
Chapter 49
Ad-hoc Debugging 397
Chapter 50
Deployed Debugging 403
Chapter 51
Debugger Metering and Permissions 410
Chapter 52
SuiteScript Debugger Interface 412
Chapter 53
Debugger Keyboard Shortcuts 418
Chapter 54
Debugger Glossary 419
SuiteScript API
Chapter 55
SuiteScript API Overview 421
SuiteTalk Platform Guide
Chapter 56
SuiteScript Functions 422
SuiteScript Functions Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Record APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Subrecord APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Field APIs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Sublist APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Search APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Scheduling APIs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Execution Context APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
UI Builder APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Application Navigation APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Date APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Currency APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Encryption APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
XML APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
File APIs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Error Handling APIs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Communication APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Configuration APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
SuiteFlow APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Portlet APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
SuiteAnalytics APIs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
User Credentials APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Chapter 57
422
430
456
463
476
503
512
519
524
529
537
539
541
542
549
552
553
561
563
565
567
569
SuiteScript Objects 571
SuiteScript Objects Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 571
Standard Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 571
UI Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 712
Chapter 58
Part 11
SuiteScript API - Alphabetized Index 802
SuiteScript Reference
Chapter 59
SuiteScript Reference 809
SuiteScript References Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 809
Using the SuiteScript Records Browser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 811
Chapter 60
SuiteScript Supported Records 813
SuiteTalk Platform Guide
Chapter 71
Scriptable Sublists 873
Scriptable Sublists Overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Access Sublist (contact roles) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Address Sublist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Adjustments Sublist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Apply Sublist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Assignees Sublist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Attendees Sublist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Billable Expenses Sublist. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Billable Items Sublist. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Billable Time Sublist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Bin Numbers Sublist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Company Contributions Sublist. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Company Taxes Sublist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Competitors Sublist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Credits Sublist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Currencies Sublist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Custom Child Record Sublists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Deductions Sublist. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Demand Plan Detail Sublist. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Deposits Sublist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Direct Mail Sublist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Download Sublist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Earnings Sublist. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
E-mail Sublist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Employee Taxes Sublist. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Escalate To Sublist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Expenses Sublist. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Group Pricing Sublist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Item Fulfillment/Receipt Sublist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Items Sublist. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Item Pricing Sublist. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Lead Nurturing Sublist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Line Sublist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Members Sublist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Orders Sublist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Other Events Sublist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Partners Sublist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Pricing Sublist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Predecessors Sublist. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Related Solutions Sublist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Resources Sublist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Sales Team Sublist. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Shipping Sublist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Site Category . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Time Tracking Sublist. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Topics Sublist. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Units . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Vendors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Chapter 72
Record Initialization Defaults 924
Chapter 73
Transaction Type IDs 934
873
875
875
875
876
876
876
877
877
877
877
878
878
878
878
879
879
892
892
898
899
899
899
899
900
900
900
900
901
902
902
903
903
903
903
904
904
905
921
921
921
921
922
922
922
923
923
923
SuiteTalk Platform Guide
Chapter 74
Permission Names and IDs 936
Chapter 75
Preference Names and IDs 945
Chapter 76
Feature Names and IDs 954
Chapter 77
Supported File Types 958
Chapter 78
Button IDs 960
Chapter 79
Supported Tasklinks 963
Chapter 80
SuiteScript Errors 991
Chapter 81
SuiteScript Governance 1057
API Governance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Script Usage Unit Limits. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Monitoring Script Usage. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Governance on Script Logging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Search Result Limits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Part 12
1058
1059
1061
1061
1063
Chapter 82
Multiple Shipping Routes and SuiteScript 1064
Chapter 83
Setting Custom Addresses Using SuiteScript 1072
Chapter 84
Referencing the currencyname Field in SuiteScript 1074
SuiteScript Developer Resources
Chapter 85
SuiteScript Developer Resources 1076
Chapter 86
SuiteScript Samples 1077
Chapter 87
SuiteScript Tutorials 1078
Getting Started with Your SuiteScript Development Environment Tutorial . . 1078
Client SuiteScript Tutorials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1082
User Event SuiteScript Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1099
Part 13
SuiteScript Best Practices
Chapter 88
General Development Guidelines 1111
Chapter 89
Suitelets and UI Object Best Practices 1113
SuiteTalk Platform Guide
Chapter 90
User Event Best Practices 1114
Chapter 91
Scheduled Script Best Practices 1115
Chapter 92
Client Script Best Practices 1117
Chapter 93
Security Considerations 1118
Chapter 94
Script Optimization 1119
SuiteTalk Platform Guide
Part 1 Getting Started
with SuiteScript
Chapter 1 SuiteScript - The Basics
If you are new to SuiteScript, it is recommended that you see these topics in order. You do not
need to read every topic that is associated with each Overview, but you should at least read the
Overviews to get a sense of how to use SuiteScript in your account.
1.
What is SuiteScript?
2.
Running a Script in NetSuite
3.
SuiteScript API Overview
4.
Script Types Overview
5.
SuiteScript Reference
6.
Setting Up Your SuiteScript Environment
Important: Throughout your SuiteScript development, you may end up referring to the
SuiteBuilder Guide the NetSuite Help Center. This guide provides detailed
information on creating custom records, forms, fields, and sublists. In
SuiteScript, much of what you will be doing is extending or getting|setting
values on many of these custom elements. The SuiteBuilder Guide provides a
basic understanding of how these elements are created and their
relationship to one another. In Help, see SuiteBuilder Overview to learn more
about SuiteBuilder.
Additional Topics
Once you understand the basic concepts behind SuiteScript and how to run a script in
NetSuite, see the following topics for details on how to maximize SuiteScript in your account.
These topics do not need to be read in order. However, as you progress through SuiteScript
development, you will refer to each section often:
•
Working with Records and Subrecords in SuiteScript - Defines what a NetSuite record
is as it pertains to SuiteScript. Also provides links to the Record APIs you will use
when working with the entire record object.
•
Working with Fields - Defines what a field is as it pertains to SuiteScript. Also provides
links to the Field APIs you will use when working with fields on a record.
•
Working with Subtabs and Sublists - Defines what a sublist is as it pertains to
SuiteScript. Also provides links to the Sublist APIs you will use when working with
sublists on a record.
•
Setting Runtime Options Overview - Provides additional information on the types of
runtime options available on a Script Deployment record.
SuiteScript Developer and Reference Guide
SuiteScript - The Basics
15
•
Creating Script Parameters Overview- Defines the concept of “script parameters” as
they pertain to SuiteScript. Also provides information on how to assign company, user,
or portlet preference values to a script parameter.
•
Searching Overview - Explains how to search NetSuite using SuiteScript and the types
of searches that are supported in scripting.
•
UI Objects Overview - Explains the concept of UI objects and how these objects can be
used in NetSuite to extend your application.
•
Debugging Overview - Describes how to use the SuiteScript Debugger to debug
server-side SuiteScripts.
•
SuiteScript Governance - Describes governance limits that are applied to each API and
each SuiteScript type.
•
SuiteScript Developer Resources - Provides a central location to access SuiteScript
samples, tutorials, and FAQs. Also provided are links to the NetSuite User Group, the
Developer Portal, and the SuiteSource repository.
SuiteScript Developer and Reference Guide
Chapter 2 What is SuiteScript?
The following topics are covered in this section. If you are new to SuiteScript they should be
read in order.
•
What can I do with the SuiteScript API?
•
Using the SuiteScript API with NetSuite Records
What can I do with the SuiteScript API?
SuiteScript is a JavaScript-based API that gives developers the ability to extend NetSuite
beyond the capabilities provided through SuiteBuilder point-and-click customization.
The majority of NetSuite forms, records, customization objects and their event/trigger points
are programmatically accessible through SuiteScript. What you decide to do with SuiteScript
depends on which part of NetSuite you are trying to extend, search, or process.
When you think about using SuiteScript in NetSuite, you must ask yourself:
1.
What do I want to do?
2.
Which APIs support what I want to do?
3.
How do I run a script in NetSuite?
What do I want to do?
The following are just some of the uses for SuiteScript. Next to each use case is a link to the
NetSuite script type you might use to programmatically accomplish the tasks involved.
Using SuiteScript you can:
•
Perform custom business processing when NetSuite records are updated, created,
deleted (using User Event Scripts).
•
Perform custom validations and calculations in the browser client (using Client
Scripts).
•
Create custom user interfaces (using script types such as Suitelets or User Event Scripts
and UI Objects).
•
Run batch processes (using Scheduled Scripts).
•
Execute NetSuite searches (using script types such as User Event Scripts or Scheduled
Scripts).
•
Perform various utility processing such as sending email and faxes, creating and
uploading files, or working with XML documents (using script types such as User
Event Scripts or Suitelets).
SuiteScript Developer and Reference Guide
What is SuiteScript?
What can I do with the SuiteScript API?
•
Create custom dashboard portlets (using Portlet Scripts).
•
Perform processing in target accounts for bundled solutions as part of bundle
installation or update (using Bundle Installation Scripts).
17
Which APIs support what I want to do?
In the documentation, the SuiteScript API is organized by the types of tasks most developers
want to perform. See SuiteScript API Overview to get started with the SuiteScript API.
See SuiteScript Functions to see how all APIs are organized. The documentation for each API
lists whether the API can be used in client, user event, scheduled, Suitelet, or portlets scripts.
How do I run a script in NetSuite?
The overall process for getting a script to run in NetSuite is fairly basic. This process includes:
1.
Creating a JavaScript file for your script.
2.
Uploading the file into NetSuite.
3.
Creating a NetSuite “Script” record for your script.
4.
Defining script runtime options on a NetSuite Script Deployment page.
For complete details on each step in the process, start with the Running Scripts in NetSuite
Overview topic in the NetSuite Help Center.
SuiteScript Developer and Reference Guide
What is SuiteScript?
Using the SuiteScript API with NetSuite Records
Using the SuiteScript API with NetSuite Records
The figure below shows a standard Sales Order record in NetSuite.
The figure outlines the basic components of the record, such as:
1.
Record object
2.
Body fields
3.
Buttons and Actions
4.
Subtabs and Sublists
5.
Body fields
SuiteScript Developer and Reference Guide
18
What is SuiteScript?
Using the SuiteScript API with NetSuite Records
6.
19
Sublist fields
Many of the APIs in SuiteScript are used to get and set values on each of these components. You
can also use SuiteScript to create these components.
Records
Use Record APIs to interact with the entire record object.
Fields
Use Field APIs to interact with the body fields on the main area of the record. Body fields can
also appear on a subtab.
Buttons
The use of SuiteScript on built-in buttons is not currently supported. However, you can add a
new button object to a page using the nlobjButton UI object.
Tabs
You can programmatically add fields to NetSuite tabs. You can also add custom tabs using the
nlobjTab UI object.
Sublists
Use Sublist APIs to interact with “line item” sublist fields.
SuiteScript Developer and Reference Guide
Chapter 3 Setting Up Your SuiteScript
Environment
Environment Setup Overview
Before working with SuiteScript, you should configure both your NetSuite account and your
SuiteScript development environment accordingly. See the following sections:
•
Configuring NetSuite for SuiteScript
•
Setting Up Your SuiteScript Development Environment (SuiteCloud IDE)
Related Topics
•
•
SuiteScript - The Basics
SuiteScript API Overview
Configuring NetSuite for SuiteScript
You must complete all of the following tasks to enable SuiteScript in your account and to access
the internal record and fields IDs that may be required as parameter values in your SuiteScript
code. These tasks include:
1.
Enabling SuiteScript
2.
Showing Record and Field IDs in Your Account
3.
Setting Roles and Permissions for SuiteScript
Important: After completing these tasks, see Setting Up Your SuiteScript Development
Environment (SuiteCloud IDE).
Related Topics
•
•
Environment Setup Overview
Setting Up Your SuiteScript Development Environment (SuiteCloud IDE)
Enabling SuiteScript
Before you can run SuiteScript in your NetSuite account, you must enable the SuiteScript
feature.
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Configuring NetSuite for SuiteScript
21
To enable SuiteScript:
1.
Go to Setup > Company > Setup Tasks > Enable Features.
2.
Click the SuiteCloud tab.
3.
Under SuiteScript click the Client SuiteScript or Server SuiteScript check box (or both,
depending on the scripts you want to run).
4.
Click Save.
Important: If Client SuiteScript is enabled, the Custom Code tab becomes available on
entry and transactions forms (see figure). Here you define which client scripts
to associate with the current form. For information on attaching client
scripts to NetSuite forms, see Running Scripts in NetSuite Overview. For
information on entry and transactions forms, see Custom Forms in the
SuiteBuilder (Customization) Guide.
Related Topics
•
•
•
Showing Record and Field IDs in Your Account
Setting Up Your SuiteScript Development Environment (SuiteCloud IDE)
SuiteScript API Overview
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Configuring NetSuite for SuiteScript
22
Showing Record and Field IDs in Your Account
After enabling the SuiteScript feature, NetSuite recommends that you enable the Show
Internal IDs preference. Enabling this preference lets you see the internal IDs for all fields and
records in NetSuite. (Note that if you have enabled the Web Services you will also want to
enable the Show Internal IDs preference.)
When referencing a record or field in SuiteScript, you will generally always use the internal ID.
Even if the record or field’s UI label is changed, the internal ID will remain constant.
After enabling Show Internal IDs, see these sections for steps on viewing the IDs from within
NetSuite:
•
How do I find a record’s internal ID?
•
How do I find a field’s internal ID?
Important: You can also obtain record and field internal IDs by going to SuiteScript
Supported Records in the NetSuite Help Center. This section lists all NetSuite
records that currently support SuiteScript. Click on the record you are
scripting against to see the record’s internal ID, as well as all of the field IDs
associated with the record.
To show internal NetSuite IDs:
1.
Go to Home > Set Preferences.
2.
Click the General tab and then click the Show Internal IDs checkbox (see figure).
3.
Click Save.
Note: For examples of how internal IDs are referenced in the SuiteScript API, see
nlapiLoadRecord(type, id, initializeValues) or nlapiSearchRecord(type, id, filters,
columns). Also note that when writing SuiteScript, all record and field IDs must
be in lowercase.
How do I find a record’s internal ID?
Record IDs are unique IDs associated with a record at the time the record is created. Once the
Show Internal IDs preference is enabled, the internal IDs for each record are displayed in the
Internal ID column of record lists (see figure).
For example, to see an internal ID for a specific customer record, go to Lists > Relationships >
Customer. In the Internal ID column, the internal ID appears next to each record in the
Customers list (see figure).
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Configuring NetSuite for SuiteScript
23
If the Show Internal IDs preference is NOT enabled, or if the internal IDs are not displayed on a
given page within NetSuite, you can see the internal ID for a record by hovering over a link to
that record. The internal ID is displayed as a parameter in the URL in the browser status bar.
The following figure shows that if you hover over a link to the Adina Fitzpatrick customer
record, the internal record ID (149) appears in the browser status bar.
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Configuring NetSuite for SuiteScript
24
How do I find a field’s internal ID?
Internal field IDs must be used when calling a field from a SuiteScript API. When the Show
Internal IDs preference is enabled, internal IDs for each field are displayed in the Internal ID
column of a custom field page. For example, to see the internal IDs for custom CRM fields, go
to Setup > Customization > CRM Fields. The ID column appears in the list of custom fields, as
shown in the figure.
With Show Internal IDs enabled, you can also view internal field IDs by clicking the field label
in the UI. The figure below shows the Field Level Help window that opens when a field label is
clicked, in this case, the Company Name label. The internal ID for the Company Name field is
companyname, which appears in the bottom-right corner of the Field Level Help window.
Note: When creating custom fields, you can specify your own field ID, 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 define your own
custom field IDs. For detailed information on creating custom fields and assigning
custom field IDs, refer to Custom Fields in the NetSuite Help Center.
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Configuring NetSuite for SuiteScript
25
Setting Roles and Permissions for SuiteScript
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 SuiteScript feature is also controlled using roles and permissions. When you
assign the SuiteScript permission to a role, you are allowing the users who have that role to
write, upload, and run SuiteScript files in your company’s NetSuite account. To assign the
SuiteScript permission to a role, a NetSuite administrator must use the following steps:
To assign the SuiteScript permission to a role:
1.
Go to Setup > Users/Roles > Manage Roles.
2.
Next, click Edit or Customize next to the role.
3.
On the Permissions tab, select the Setup subtab.
4.
In the Permissions dropdown, select SuiteScript.
5.
Click Save.
Note that there are seven standard roles that already have full access to the SuiteScript feature.
Users who have the following roles can already write, upload, and run SuiteScript files.
Role
SuiteScript Access Level
Administrator
FULL
Full Access
FULL
Marketing Manager
FULL
Marketing Administrator
FULL
Sales Manager
FULL
Sales Administrator
FULL
Support Administrator
FULL
Important:
•
When customizing a role to add SuiteScript capabilities, you must also add
permission for customizing entry forms and transaction forms.
•
Depending on the NetSuite product you subscribe to, not all of the roles listed in
the table above may be available to you. Also, in addition to these standard roles
there may be custom roles created with the SuiteScript permissions assigned to
them.
Related Topics
•
•
Setting Up Your SuiteScript Development Environment (SuiteCloud IDE)
Enabling SuiteScript
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Setting Up Your SuiteScript Development Environment
26
Setting Up Your SuiteScript Development Environment
(SuiteCloud IDE)
Before setting up your SuiteScript development environment, be sure you have completed the
NetSuite configuration tasks described in Configuring NetSuite for SuiteScript.
Once your account has been configured accordingly, NetSuite recommends you read the
SuiteCloud IDE Overview and follow the steps (in order) to set up your SuiteScript
development environment:
1.
Installing SuiteCloud IDE
2.
Launching SuiteCloud IDE
3.
Selecting a Workspace
4.
Setting Up a Master Password
5.
(Optional) Setting Up an Environment
6.
Setting Up an Account
7.
Importing Existing NetSuite Projects into SuiteCloud IDE
8.
Setting SuiteCloud IDE Preferences
After setting up your SuiteCloud IDE, see Working with Your SuiteScript Development
Environment (SuiteCloud IDE). If you choose to set up a SuiteScript development
environment other than SuiteCloud IDE, see Working with IDEs Other Than SuiteCloud IDE.
Related Topics
•
•
•
•
•
Environment Setup Overview
Configuring NetSuite for SuiteScript
Working with Your SuiteScript Development Environment (SuiteCloud IDE)
Working with IDEs Other Than SuiteCloud IDE
Setting Up Your SuiteScript Environment
SuiteCloud IDE Overview
SuiteCloud IDE is an Eclipse-based IDE that is packaged for NetSuite platform development.
SuiteCloud IDE creates a development environment that offers:
•
Code Completion for SuiteScript API and Internal IDs
•
Upload and Download of Files from NetSuite File Cabinet
•
Comparison of Files with NetSuite File Cabinet Version
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Setting Up Your SuiteScript Development Environment
•
Validation of Internal IDs
•
Integration with the SuiteScript Records Browser
•
Management of Multiple NetSuite Accounts
•
Support for JSDoc
27
For more information about how these features work for SuiteCloud IDE, see Usage Examples.
Related Topics
•
•
•
•
•
•
•
•
•
Installing SuiteCloud IDE
Launching SuiteCloud IDE
Selecting a Workspace
Setting Up a Master Password
Setting Up an Environment
Setting Up an Account
Importing Existing NetSuite Projects into SuiteCloud IDE
Setting SuiteCloud IDE Preferences
Setting Up Your SuiteScript Development Environment (SuiteCloud IDE)
Installing SuiteCloud IDE
NetSuite recommends that you install and use the SuiteCloud IDE to write SuiteScript.
If you are not currently using SuiteCloud IDE, and you are installing it for the sole purpose of
writing SuiteScript, NetSuite recommends that you install the current version of SuiteCloud
IDE.
Important: Make sure that you have the latest Java software (Java Runtime Environment
or JRE) installed, version 1.5 and above to be specific.
In order to properly run 64-bit versions of SuiteCloud IDE, make sure your
operating system and Java versions are both 64-bit versions.
The current version of SuiteCloud IDE works only in accounts that do not
have 2-factor authentication. Additionally, web services must be enabled for
NetSuite accounts in order to use the SuiteCloud IDE.
ANT is not enabled in the current version of SuiteCloud IDE. For more
information about adding ANT, see SuiteCloud IDE FAQ.
To install the SuiteCloudIDE, click the link below that is specific to your operating system.
•
Windows 32-bit
•
Windows 64-bit
•
Linux 32-bit
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Setting Up Your SuiteScript Development Environment
•
Linux 64-bit
•
Mac OS 64 bit
28
Unpack the archive file you downloaded, and place it anywhere on your hard drive. You will see
a directory named eclipse. Within that directory you will see an executable named eclipse.
For more information about launching SuiteCloud IDE, see Launching SuiteCloud IDE.
Related Topics
•
•
•
SuiteCloud IDE Overview
Launching SuiteCloud IDE
Setting Up Your SuiteScript Development Environment (SuiteCloud IDE)
Launching SuiteCloud IDE
When you launch your SuiteCloud IDE for the first time after installation, you will be asked to
select a workspace. For more information, see Selecting a Workspace. Once you have a
workspace selected, you will then be asked to accept the terms of the license agreement.
Note:
The Usage Data Collector (UDC) is a default Eclipse feature that may appear from
time to time (every five days by default) when you launch the SuiteCloud IDE. UDC
gathers data on how you use the Eclipse platform. The gathered data is not stored
in any NetSuite server at all. You may disable this feature by selecting Turn UDC
feature off the first time it appears. For more information about how it works and
its terms of use, see Usage Data Collector in the Eclipse documentation.
To launch SuiteCloud IDE:
1.
Navigate to the folder location of your SuiteCloud IDE.
2.
Locate the eclipse application.
3.
Double-click eclipse.
The NetSuite splash screen with progress bar appears and the SuiteCloud IDE window
opens immediately after completion.
Related Topics
•
•
•
Installing SuiteCloud IDE
Selecting a Workspace
Setting Up Your SuiteScript Development Environment (SuiteCloud IDE)
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Setting Up Your SuiteScript Development Environment
29
Selecting a Workspace
Upon launching SuiteCloud IDE after installation, you are prompted to select a workspace for
your projects. Navigate to your desired workspace location and then click OK. You will then be
asked to accept the terms of the license agreement.
Important:
NetSuite recommends that you create a new workspace for SuiteCloud IDE
instead of reusing an existing workspace. This is to avoid the possibility of
carrying over incompatible settings from an old workspace.
You may check the Use this as the default and do not ask again box if you want your selected
workspace location to become the default location.
Related Topics
•
•
•
Launching SuiteCloud IDE
Setting Up a Master Password
Setting Up Your SuiteScript Development Environment (SuiteCloud IDE)
Setting Up a Master Password
SuiteCloud IDE stores all of your account login information every time you add an account.
With this, any succeeding upload or download operations will no longer prompt you to enter
your account login information. To prevent unauthorized running of these operations, you
need to set up a master password. Once you have it set up, you are only required to enter it
once per session before any account-driven operations can be done.
Important: You need to set up a master password once for every workspace.
Your master password does not only protect all of your account login information, but it also
saves you from entering different passwords for different accounts when you have multiple
NetSuite accounts (different email addresses and passwords, to be specific).
To set up a master password, see the following procedures:
•
Setting a Master Password
•
Authenticating a Master Password
•
Revoking a Master Password
•
Changing a Master Password
Related Topics
•
•
•
Selecting a Workspace
Setting Up an Environment
Setting Up Your SuiteScript Development Environment (SuiteCloud IDE)
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Setting Up Your SuiteScript Development Environment
30
Setting a Master Password
After installing the SuiteCloud IDE for the first time, you need to set a master password for
your workspace to protect all of your NetSuite account login information.
To set a master password:
1.
Launch SuiteCloud IDE.
2.
In SuiteCloud IDE, go to NetSuite > Master Password > Set Master Password. The Set
Master Password window opens.
3.
Enter the following information: New Master Password and Re-enter New Master
Password.
4.
Click OK.
Related Topics
•
•
•
•
•
Authenticating a Master Password
Revoking a Master Password
Changing a Master Password
Setting Up a Master Password
Launching SuiteCloud IDE
Authenticating a Master Password
In order to upload a project, download a project, or interact with your NetSuite account, you
need to authenticate your master password once per session until you close your SuiteCloud
IDE.
To authenticate a master password:
1.
Launch SuiteCloud IDE.
2.
In SuiteCloud IDE, go to NetSuite > Master Password > Authenticate Master Password.
The Authenticate Master Password window opens.
3.
Enter the master password.
4.
Click OK.
Note: You can also authenticate your master password from the NS Explorer pane or the
editor area. Right-click on the pane or the editor area, and go to NetSuite >
Authenticate Master Password.
You can also use the shortcut, Ctrl + Alt + A. For more information, see Shortcuts in
SuiteCloud IDE Tips.
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Setting Up Your SuiteScript Development Environment
31
Related Topics
•
•
•
•
•
•
Setting a Master Password
Revoking a Master Password
Changing a Master Password
Setting Up a Master Password
Launching SuiteCloud IDE
SuiteCloud IDE Tips
Revoking a Master Password
You can revoke your master password to avoid any mistaken or unauthorized upload,
download, and interaction with your NetSuite account. For example, someone else needs to
look at your SuiteCloud IDE editor to do a peer review of your code. You need to revoke your
master password so that your NetSuite accounts are protected.
To revoke a master password in SuiteCloud IDE, go to NetSuite > Master Password > Revoke
Master Password, and click OK when the Revoke Master Password window opens.
Note: Revoking a master password only logs you out. It does not delete the master
password.
You can also revoke your master password from the NS Explorer pane or the editor
area. Right-click on the pane or the editor area, and go to NetSuite > Revoke Master
Password.
Related Topics
•
•
•
•
Setting a Master Password
Authenticating a Master Password
Changing a Master Password
Setting Up a Master Password
Changing a Master Password
You can change a master password.
To change a master password:
1.
Launch SuiteCloud IDE.
2.
In SuiteCloud IDE, go to NetSuite > Master Password > Change Master Password. The
Change Master Password window opens.
3.
Enter the following information: Old Master Password, New Master Password, and Reenter New Master Password.
4.
Click OK.
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Setting Up Your SuiteScript Development Environment
32
Related Topics
•
•
•
•
Authenticating a Master Password
Revoking a Master Password
Setting Up a Master Password
Launching SuiteCloud IDE
Setting Up an Environment
After setting up your master password, you can opt to set up a NetSuite environment where
you want to run your scripts. The three predefined NetSuite environments in SuiteCloud IDE
are:
•
Production
•
Release Preview
•
Sandbox
To set up an environment, see the following procedures:
•
Adding an Environment
•
Modifying an Environment
•
Removing an Environment
Related Topics
•
•
•
Setting Up a Master Password
Setting Up an Account
Setting Up Your SuiteScript Development Environment (SuiteCloud IDE)
Adding an Environment
Use the following steps to add a NetSuite environment to the SuiteCloud IDE.
To add an environment:
1.
Launch SuiteCloud IDE.
2.
In SuiteCloud IDE, go to NetSuite > Environments. The Environments window opens.
3.
Click New. The New Environment window opens.
4.
Enter the following information: Name and URL.
5.
Click OK.
6.
Click Close.
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Setting Up Your SuiteScript Development Environment
33
Related Topics
•
•
•
•
Modifying an Environment
Removing an Environment
Setting Up an Environment
Launching SuiteCloud IDE
Modifying an Environment
Use the following steps to modify an existing NetSuite environment. You can change its name
or point to its updated URL.
To modify an environment:
1.
Launch SuiteCloud IDE.
2.
In SuiteCloud IDE, go to NetSuite > Environments. The Environments window opens.
3.
In the Environment list, select an environment that you want to edit.
4.
Click Edit. The Edit Environment window opens.
5.
Modify the following information: Name and URL.
6.
Click OK.
7.
Click Close.
Related Topics
•
•
•
•
Adding an Environment
Removing an Environment
Setting Up an Environment
Launching SuiteCloud IDE
Removing an Environment
Use the following steps to remove a NetSuite environment from the SuiteCloud IDE. You can
remove unused or unnecessary environment to have the environment options you only need at
a given period of time.
To remove an environment:
1.
Launch SuiteCloud IDE.
2.
In SuiteCloud IDE, go to NetSuite > Environments. The Environments window opens.
3.
In the Environment list, select an environment that you want to remove.
4.
Click Remove. The Remove Environment dialog opens.
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Setting Up Your SuiteScript Development Environment
5.
Click OK.
6.
Click Close.
34
Related Topics
•
•
•
•
Adding an Environment
Modifying an Environment
Setting Up an Environment
Launching SuiteCloud IDE
Setting Up an Account
After setting up your master password, you need to set up the NetSuite accounts you will be
writing scripts for. If you have set up environments in addition to the three predefined NetSuite
environments, you need to configure account-specific details for these additional
environments.
To set up an account, see the following procedures:
•
Adding an Account
•
Removing an Account
Related Topics
•
•
•
•
Setting Up a Master Password
Setting Up an Environment
Importing Existing NetSuite Projects into SuiteCloud IDE
Setting Up Your SuiteScript Development Environment (SuiteCloud IDE)
Adding an Account
Use the following steps to add an account. SuiteCloud IDE passes your account information to
NetSuite during the IDE authentication process.
Important: Make sure to add NetSuite accounts that comply with NetSuite’s password
requirements, specially in terms of the recommended special characters you
can use. For more information, see NetSuite Password Requirements.
Whenever you change your NetSuite password, you will need to re-add your
accounts using your latest NetSuite login credentials. However, SuiteCloud
IDE will automatically prompt you to enter your latest NetSuite login
credentials if you have updated your NetSuite login credentials but have not
re-added your accounts in the IDE.
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Setting Up Your SuiteScript Development Environment
35
To add an account:
1.
Launch SuiteCloud IDE.
2.
In SuiteCloud IDE, go to NetSuite > Accounts. The Accounts window opens.
3.
Click Add. The Add Account(s) window opens.
4.
Select an environment.
5.
Enter the following information: Email and Password.
Important: The password referred to here is the NetSuite password associated with
your email.
6.
Click Next. The Select Account(s) window opens.
7.
Select the account you want to add. You may click Select All; or click Deselect All and
then select what you need.
8.
Click Finish. The Accounts window opens with your added accounts.
Existing accounts are maintained. Newly-found accounts are added when you select
and add them.
9.
Click Close.
Related Topics
•
•
•
Removing an Account
Setting Up an Account
Launching SuiteCloud IDE
Removing an Account
Use the following steps to remove an account. You can remove inactive or unused accounts that
you no longer need.
To remove an account:
1.
Launch SuiteCloud IDE.
2.
In SuiteCloud IDE, go to NetSuite > Accounts. The Accounts window opens.
3.
In the Accounts list, select an account that you want to remove.
4.
Click Remove. The Remove Account dialog opens.
5.
Click OK.
6.
Click Close.
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Setting Up Your SuiteScript Development Environment
36
Related Topics
•
•
•
Adding an Account
Setting Up an Account
Launching SuiteCloud IDE
Importing Existing NetSuite Projects into SuiteCloud IDE
If you already have existing projects in the NetSuite file cabinet, synchronize your file cabinet
with SuiteCloud IDE by importing your projects into SuiteCloud IDE. Before doing so, ensure
that all your project files are up-to-date in the NetSuite file cabinet.
To import existing NetSuite projects into SuiteCloud IDE:
1.
Launch SuiteCloud IDE.
2.
In SuiteCloud IDE, authenticate your master password.
3.
Right-click in the NS Explorer pane. The context menu appears.
4.
In the context menu, go to NetSuite > Download Project. The Download Project
window opens.
5.
Select an account.
6.
Select a role.
7.
Click Get File List.
Note: Hidden bundles, inactive files, and empty folders are excluded from the file list.
8.
Wait for the progress bar to complete.
9.
Select the projects that you want to import.
10.
Select Use project name in file cabinet.
11.
Select Use this project name.
12.
Enter the project name that you want to use.
13.
Click OK.
14.
Check your project folder to verify that all files were imported.
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Setting Up Your SuiteScript Development Environment
37
Related Topics
•
•
•
•
•
Setting Up an Account
Setting SuiteCloud IDE Preferences
Setting Up Your SuiteScript Development Environment (SuiteCloud IDE)
Launching SuiteCloud IDE
Authenticating a Master Password
Setting SuiteCloud IDE Preferences
To set SuiteCloud IDE preferences, see the following procedures:
•
Setting SuiteCloud IDE General Preferences
•
Setting SuiteCloud IDE Code Template Preferences
•
Setting SuiteCloud IDE Validation Preferences
•
Restoring SuiteCloud IDE Default Preferences
Related Topics
•
•
Importing Existing NetSuite Projects into SuiteCloud IDE
Setting Up Your SuiteScript Development Environment (SuiteCloud IDE)
Setting SuiteCloud IDE General Preferences
You can set SuiteCloud IDE general preferences such as the display setting for the Start Page,
the file backup mechanism, and the Internal ID Quote Character option. The preferred quote
character will be automatically used when an internal ID is selected as a function parameter
after pressing the shortcut, Ctrl + Space.
For example, if you set single quotes as the Internal ID Quote Character, typing
nlapiLoadRecord( followed by the shortcut, Ctrl + Space, and then selecting an internal
ID such as salesorder automatically results to nlapiLoadRecord(‘salesorder’).
To set SuiteCloud IDE general preferences:
1.
Launch SuiteCloud IDE.
2.
In SuiteCloud IDE, go to Window > Preferences. The Preferences window opens.
The Preferences window defaults to the NetSuite Preferences view.
3.
Under General Preferences, if you want to display the Start Page on startup, check
Show Start Page on startup.
4.
If you want to enable backing up of existing files during download, check Enable file
backup (*.bak) for project or file downloads.
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Setting Up Your SuiteScript Development Environment
5.
Select the Internal ID Quote Character that you want.
6.
Click Apply.
7.
Click OK.
38
Related Topics
•
•
•
•
•
Setting SuiteCloud IDE Code Template Preferences
Setting SuiteCloud IDE Validation Preferences
Restoring SuiteCloud IDE Default Preferences
Setting SuiteCloud IDE Preferences
Launching SuiteCloud IDE
Setting SuiteCloud IDE Code Template Preferences
You can set SuiteCloud IDE code template preferences. You can create your own custom
headers and function templates with the appropriate content and file name; and specify a folder
to where these custom code templates for your team are located. If you do not specify a folder
location, the default templates are used.
The following are the files you can customize code templates for:
•
bundle_install_after_install.js
•
bundle_install_after_update.js
•
bundle_install_before_install.js
•
bundle_install_before_update.js
•
client_field_changed.js
•
client_line_init.js
•
client_page_init.js
•
client_post_sourcing.js
•
client_recalc.js
•
client_save_record.js
•
client_validate_delete.js
•
client_validate_field.js
•
client_validate_insert.js
•
client_validate_line.js
•
header.js
•
mass_update.js
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Setting Up Your SuiteScript Development Environment
•
portlet_form.js
•
portlet_html.js
•
portlet_links.js
•
portlet_list.js
•
RESTlet_delete.js
•
RESTlet_get.js
•
RESTlet_post.js
•
RESTlet_put.js
•
ssp.ss
•
ssp.ssp
•
scheduled.js
•
suitelet.js
•
templates.xml
•
user_event_after_submit.js
•
user_event_before_load.js
•
user_event_before_submit.js
•
workflow_action.js
Moreover, the table below shows the tokens you can use in creating your customized code
template for the header.js file.
Token
Description
${filename}
Current filename
${project}
Current project
${year}
Current year
${date}
Current date
Note: The preferred date format can be specified in the Date Format field.
${author}
Current user name
Note: The current user name defaults to the system user name. The preferred
user name can be specified in the User Name field.
For example, you can have the following text as code template for your header.js file:
/**
* Module Description
*
* Version
Date
* 1.00
${date}
*
Author
${author}
Remarks
SuiteScript Developer and Reference Guide
39
Setting Up Your SuiteScript Environment
Setting Up Your SuiteScript Development Environment
40
*/
To set SuiteCloud IDE code template preferences:
1.
Launch SuiteCloud IDE.
2.
In SuiteCloud IDE, go to Window > Preferences. The Preferences window opens.
The Preferences window defaults to the NetSuite Preferences view.
3.
In the left-hand pane, navigate to NetSuite > Code Templates. The Code Templates
Preferences view is shown.
4.
Select the Code Templates Folder location.
5.
Enter the following information: User Name and Date Format.
6.
Click Apply.
7.
Click OK.
Related Topics
•
•
•
•
•
Setting SuiteCloud IDE General Preferences
Setting SuiteCloud IDE Validation Preferences
Restoring SuiteCloud IDE Default Preferences
Setting SuiteCloud IDE Preferences
Launching SuiteCloud IDE
Setting SuiteCloud IDE Validation Preferences
You can set SuiteCloud validation preferences and specify a text file as Ignore list. Validation
for internal IDs is done whenever you save a file or you build or rebuild a project. The table
below shows the three validation types you can use.
Type
Description
Off
This switches off the validation feature and the system performance is not impacted.
Fast
This determines context within the current file and the system performance is average.
Full
This determines context across different files but the system performance is slow.
Note: By default, the validation type is set to Fast.
To set SuiteCloud IDE validation preferences:
1.
Launch SuiteCloud IDE.
2.
In SuiteCloud IDE, go to Window > Preferences. The Preferences window opens.
The Preferences window defaults to the NetSuite Preferences view.
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Setting Up Your SuiteScript Development Environment
3.
In the left-hand pane, navigate to NetSuite > Validation. The Validation Preferences
view is shown.
4.
Under Validation Preferences, select the Validation Type that you want.
5.
Select the Ignore List text file.
41
Important: In your text file, make sure that the items to be ignored are entered per
line.
6.
Click Apply.
7.
Click OK.
Related Topics
•
•
•
•
•
Setting SuiteCloud IDE General Preferences
Setting SuiteCloud IDE Code Template Preferences
Restoring SuiteCloud IDE Default Preferences
Setting SuiteCloud IDE Preferences
Launching SuiteCloud IDE
Restoring SuiteCloud IDE Default Preferences
Use the following steps to restore IDE default preferences.
To restore SuiteCloud IDE default preferences:
1.
Launch SuiteCloud IDE.
2.
In SuiteCloud IDE, go to Window > Preferences. The Preferences window opens.
The Preferences window defaults to the NetSuite Preferences view.
3.
In the left-hand pane, navigate to the specific preferences for NetSuite (such as general,
code templates, and validation) that you want to restore default settings to.
4.
Click Restore Defaults.
5.
Click Apply.
6.
Click OK.
Related Topics
•
•
•
•
•
Setting SuiteCloud IDE General Preferences
Setting SuiteCloud IDE Code Template Preferences
Setting SuiteCloud IDE Validation Preferences
Setting SuiteCloud IDE Preferences
Launching SuiteCloud IDE
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Working with Your SuiteScript Development Environment
42
Working with Your SuiteScript Development Environment (SuiteCloud IDE)
Before you can start working with SuiteCloud IDE, you need to familiarize yourself with the
following:
•
NetSuite Perspective Overview
•
SuiteCloud IDE Tips
•
Usage Examples
With your SuiteCloud IDE, you can do the following procedures:
•
Working with SuiteScript Projects
•
Working with SuiteScript Files
•
Working with SSP Application Projects
•
Changing Project Settings
•
Converting a Project to a SuiteScript Project
•
Converting a Project to an SSP Application Project
•
Logging in to a Project Account
•
Debugging a Project Account
•
Launching the SuiteScript Records Browser
•
Viewing Error Logs
•
Resetting Your Master Password and Account Info
Related Topics
•
•
•
•
•
Environment Setup Overview
Configuring NetSuite for SuiteScript
Setting Up Your SuiteScript Development Environment (SuiteCloud IDE)
Working with IDEs Other Than SuiteCloud IDE
Setting Up Your SuiteScript Environment
NetSuite Perspective Overview
The NetSuite Perspective is an added perspective in the Eclipse workbench for SuiteCloud IDE.
It provides a set of functionality for manipulating your NetSuite projects and resources that are
accessible through certain menus and toolbars.
The NetSuite perspective consists of an editor area and one or more views that you will use to
accomplish your NetSuite projects.
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Working with Your SuiteScript Development Environment
43
Editor Area
The Editor area displays the source file editors you can use for your code. The NetSuite
Perspective mainly uses the JavaScript and HTML editor for NetSuite projects, such as
SuiteScript and SSP application projects.
For more information, see Editors in the Eclipse documentation.
NS Explorer View
The NetSuite Explorer view, referred to as the NS Explorer view, displays the hierarchical view
of your NetSuite projects (their folders and files) and resources. It works similar to the Project
Explorer view of Eclipse.
The table below shows the additional icons that can appear in the NS Explorer view.
Icon
Description
SuiteScript Project (open)
SSP Application Project (open)
In NS Explorer view, you can hover over the project folders to see the following details when
available:
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Working with Your SuiteScript Development Environment
•
Project Type
•
NetSuite Account ID
•
Company
•
Email
•
Environment
•
File Cabinet Folder
44
For more information, see Project Explorer view in the Eclipse documentation.
Outline View
The Outline view displays the organizational structure of your source file that is active in the
editor area. In general, it lists the structural elements of your source file by function.
For more information, see Outline view in the Eclipse documentation.
Problems View
The Problems view displays the errors and warnings found in your source file that is active in
the editor area. The information found in this view corresponds to the problem markers shown
in the marker bar of the editor area.
For more information, see Problems view in the Eclipse documentation.
Documentation View
The Documentation view displays the corresponding documentation or comment details you
have for your code that is active in the editor area. This view displays only the documentation
details for your functions. The same details appear in the popup when you click or hover over a
function name.
Progress View
The Progress view displays the progress bar of all your upload or download actions.
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Working with Your SuiteScript Development Environment
45
Related Topics
•
•
•
•
•
•
•
•
•
•
•
•
•
SuiteCloud IDE Tips
Usage Examples
Working with SuiteScript Projects
Working with SuiteScript Files
Working with SSP Application Projects
Changing Project Settings
Converting a Project to a SuiteScript Project
Converting a Project to an SSP Application Project
Logging in to a Project Account
Debugging a Project Account
Launching the SuiteScript Records Browser
Viewing Error Logs
Working with Your SuiteScript Development Environment (SuiteCloud IDE)
SuiteCloud IDE Tips
When working with SuiteCloud IDE, the following information will make your development
experience easier:
•
Shortcuts
•
Validation Markers
•
Guidelines
Shortcuts
The following table shows the different shortcuts you can use within the SuiteCloud IDE.
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Working with Your SuiteScript Development Environment
Shortcut
Description
Ctrl + Space
This is an existing Eclipse shortcut.
46
This is used to get a dropdown of all possible code completion
options available in a particular context.
Note:
<x> + Space
•
In cases wherein a number of record types are involved,
you can precede this shortcut with the shortcut, <x> +
Space + <y>, to specify the record context you need.
•
In cases wherein a number of sublists of a record are
involved, you can precede this shortcut with the shortcut,
<x> + Space + <y> + Space + <z>, to specify the recordsublist context you need.
This is used to get all possible code completion options for a
record; where <x> is your filter against record types.
For example, you type ‘s’ + Space if you want to get all possible
code completion options for salesorder fields.
This is used in conjunction with the shortcut, Ctrl + Space.
For more information, see Usage Examples.
<x> + Space + <y>
This is used to get all possible code completion options for a
field in a particular record context; where <x> is your filter
against record types and <y> is your filter against fields of a
record type.
For example, you type ‘s’ + Space + ‘a’ if you want to get all
possible code completion options for salesorder fields starting
with the letter ‘a’.
Note: For internal ID code completion options, append an
exclamation point ‘!’ to override and ignore the context when
“No Proposal” appears for your given prefix filter.
This is used in conjuction with the shortcut, Ctrl + Space.
For more information, see Usage Examples.
<x> + Space + <y> + Space + <z>
This is used to get all possible code completion options for a
sublist field in a particular record-sublist context; where <x> is
your filter against record types, <y> is your filter against sublists
of a record type, and <z> is your filter against fields of a sublist.
For example, you type ‘s’ + Space + ‘i’ + Space + ‘a’ if you want
to get all possible code completion options for salesorder-item
sublist fields starting with the letter ‘a’.
This is used in conjunction with the shortcut, Ctrl + Space.
For more information, see Usage Examples.
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Working with Your SuiteScript Development Environment
Shortcut
Description
<xYZ>
This is an existing Eclipse shortcut.
47
This is used to get code completion options using camel case
patterns/filters; where xYZ is your camel case filter against
methods and variables.
For example, you type ‘nLR’ if you want to get code completion
options for methods using the camel case pattern such as
nlapiLoadRecord.
This is used in conjunction with the shortcut, Ctrl + Space.
For more information, see Usage Examples.
Ctrl + Alt + A
This is used to authenticate your master password.
Ctrl + U
This is used to upload file(s) from the editor area.
Ctrl + B
This is used to log in to a project account from the editor area.
Tab
This is used to globally change function names, record names,
variables, and parameters.
Note: This is applicable only for newly created SuiteScript files.
Esc
This is used to exit the mode set in conjunction with the
shortcut, Tab.
Ctrl + Click <internal ID>
This is used to launch the Record Browser specific to the
internal ID from the editor.
Type /** and press Enter
This is an existing Eclipse shortcut.
This is used to enter a standard JSDoc comment.
Alt + Up or Alt + Down
This is an existing Eclipse shortcut.
This is used to move the current line/selection up or down.
Ctrl + Alt + Up or Ctrl + Alt + Down
This is an existing Eclipse shortcut.
This is used to duplicate the current line/selection, and place
the clone above (Up) or below (Down) the current line/
selection.
Alt + Shift + A
This is an existing Eclipse shortcut.
This is used to toggle block selection mode (formerly column
mode). Block selection mode allows you to select a rectangle of
text and modify the highlighted text altogether instead of
selecting text and modifying them a line at a time.
Validation Markers
The table below shows the Editor area validation markers that were augmented for SuiteCloud
IDE.
Validation Marker
Description
Warning
Augmented to indicate the source location of NetSuite-related
code completion warnings
Error
Augmented to indicate the source location of NetSuite-related
syntax or compilation errors
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Working with Your SuiteScript Development Environment
48
For more information, see Markers in the Eclipse documentation.
Guidelines
When working with SuiteCloud IDE, you need to take note of the following guidelines:
•
Use top-down coding method. Make sure to write your code from top to bottom. The
code preceding the cursor should always be completely valid or syntactically correct.
For code completion to work, there should be no undeclared variables. For more
information about the different ways to maximize code completion, see SuiteCloud
IDE FAQ.
•
Use camel case filters. You can use filters in camel case format inherent to Eclipse to
maximize code completion. If you want to display nlapiLoadRecord as an option, enter
‘nLR’ followed by the code completion shortcut (Ctrl + Space). For more information
about other ways to maximize code completion, see SuiteCloud IDE FAQ.
Note: Make sure that the Show camel case matches preference is enabled. To verify if
it is enabled, go to Window > Preferences > JavaScript > Editor > Content Assist in
SuiteCloud IDE.
•
Pass variables to functions. When variables (simple variables and not object
properties) are passed to a SuiteScript function, code completion will work. This
approach is applicable to all parameters that have code completion. For more
information about other ways to maximize code completion, see SuiteCloud IDE FAQ.
•
Use prefix filters. When working with multiple records, use prefix filters to specify the
record context you need for code completion. The prefix filter shortcuts are: ‘<x> +
Space’, ‘<x> + Space + <y>’, and ‘<x> + Space + <y> + Space + <z>’. Use them in
conjunction with the code completion shortcut (Ctrl + Space). For more information
about prefix filter shortcuts, see Shortcuts. For more information about the different
ways to maximize code completion, see SuiteCloud IDE FAQ.
•
Use standard JSDoc. Based on JavaDoc, you can use the standard format of a JSDoc
comment/tags for a function (including variable type declaration) for documenting
the parameter (@param) and return (@returns) types to maximize code completion.
For more information about the shortcut for a standard JSDoc comment, see
Shortcuts. Additionally, you can specify the variable type (@type) for variable
declarations. For more information about the different ways to maximize code
completion, see SuiteCloud IDE FAQ.
•
Use custom NetSuite JSDoc. You can use the custom NetSuite JSDoc tags,
@appliedtorecord and @record, to augment code completion. The @appliedtorecord
tag corresponds to the Applied To record in your NetSuite script deployment and is
only applicable for client and user event script functions that rely on the specified
Applied To record. The @record tag can be used in conjunction with standard JSDoc
tags such as @param, @returns, and @type to specify the needed record context. For
more information about the different ways to maximize code completion, see
SuiteCloud IDE FAQ.
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Working with Your SuiteScript Development Environment
•
49
Activate code completion automatically. By default, code completion is activated in
SuiteCloud IDE by pressing the shortcut, Ctrl + Space. However, you can automatically
trigger code completion through the Enable auto activation preference. To enable
auto activation, go to Window > Preferences > JavaScript > Editor > Content Assist in
SuiteCloud IDE. Make sure that the preference is checked and that the following fields
are set accordingly:
Auto activation delay: 0
Auto action triggers for JavaScript: .nfo
For more information about auto activation and the different ways to maximize code
completion, see SuiteCloud IDE FAQ.
•
Close unused projects. For optimum performance, make sure that the only open
project in your SuiteCloud IDE is the project you are currently working on. Always
close unused projects. For more information about closing a project, see Closing
projects in the Eclipse documentation.
•
Use unique names. Make sure that you use unique names for global functions.
Additionally, use unique function names and parameter names within a single object
literal.
•
Increase available memory. You can increase the memory available for SuiteCloud
IDE to allow a maximum amount instead of just the default allocation. However, the
maximum heap memory depends on your SuiteCloud IDE version (32-bit or 64-bit,
with the latter having a higher maximum), operating system, and Java virtual machine
(JVM). For more information, see SuiteCloud IDE FAQ.
•
Specify preferred JVM. You can specify your preferred JVM when there are multiple
copies available. For more information about working with multiple copies of JVM, see
SuiteCloud IDE FAQ.
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Working with Your SuiteScript Development Environment
50
Related Topics
•
•
•
•
•
•
•
•
•
•
•
•
•
NetSuite Perspective Overview
Usage Examples
Working with SuiteScript Projects
Working with SuiteScript Files
Working with SSP Application Projects
Changing Project Settings
Converting a Project to a SuiteScript Project
Converting a Project to an SSP Application Project
Logging in to a Project Account
Debugging a Project Account
Launching the SuiteScript Records Browser
Viewing Error Logs
Working with Your SuiteScript Development Environment (SuiteCloud IDE)
Usage Examples
Code completion works by examining the source code around the cursor. When the code
completion shortcut (Ctrl + Space) is pressed, the system displays a popup with the appropriate
text options to insert at the cursor. This popup may include record types, field names, or other
information, depending on where the caret is positioned.
To learn the basics of code completion hands-on, download the DemoProject files included
with the SuiteCloud IDE here.
Important: After downloading the DemoProject files, make sure to add the files to a
SuiteScript project in your SuiteCloud IDE. For more information, see
Importing files in the Eclipse documentation.
If you have no existing SuiteScript projects yet in your SuiteCloud IDE, you
need to create one before you add the DemoProject files. For more
information, see Creating a SuiteScript Project.
For information about the different ways to maximize code completion, see SuiteCloud IDE
FAQ.
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Working with Your SuiteScript Development Environment
Related Topics
•
•
•
•
•
•
•
•
•
•
•
•
•
NetSuite Perspective Overview
SuiteCloud IDE Tips
Working with SuiteScript Projects
Working with SuiteScript Files
Working with SSP Application Projects
Changing Project Settings
Converting a Project to a SuiteScript Project
Converting a Project to an SSP Application Project
Logging in to a Project Account
Debugging a Project Account
Launching the SuiteScript Records Browser
Viewing Error Logs
Working with Your SuiteScript Development Environment (SuiteCloud IDE)
Working with SuiteScript Projects
A SuiteScript project is a type of project that is based on the JavaScript project but with the
NetSuite SuiteScript library automatically added to enable the auto completion and content
assist features.
With SuiteScript projects, you can do the following procedures:
•
Creating a SuiteScript Project
•
Uploading Files in a SuiteScript Project
•
Downloading Files in a SuiteScript Project
SuiteScript Developer and Reference Guide
51
Setting Up Your SuiteScript Environment
Working with Your SuiteScript Development Environment
Related Topics
•
•
•
•
•
•
•
•
•
•
•
•
•
NetSuite Perspective Overview
SuiteCloud IDE Tips
Usage Examples
Working with SuiteScript Files
Working with SSP Application Projects
Changing Project Settings
Converting a Project to a SuiteScript Project
Converting a Project to an SSP Application Project
Logging in to a Project Account
Debugging a Project Account
Launching the SuiteScript Records Browser
Viewing Error Logs
Working with Your SuiteScript Development Environment (SuiteCloud IDE)
Creating a SuiteScript Project
Use the following steps to create a SuiteScript project in the SuiteCloud IDE.
To create a SuiteScript project:
1.
Launch SuiteCloud IDE.
2.
In SuiteCloud IDE, go to File > New > NetSuite Project. The New NetSuite Project
window opens.
3.
Enter a project name.
4.
Select SuiteScript Project as project type.
5.
Select Use default location.
6.
If you do not want to use the default location, deselect Use default location and
navigate to your desired location.
7.
Click Finish.
Related Topics
•
•
•
•
Uploading Files in a SuiteScript Project
Downloading Files in a SuiteScript Project
Working with SuiteScript Projects
Launching SuiteCloud IDE
SuiteScript Developer and Reference Guide
52
Setting Up Your SuiteScript Environment
Working with Your SuiteScript Development Environment
53
Uploading Files in a SuiteScript Project
You can upload files in a SuiteScript project to the NetSuite file cabinet. If you are uploading
files from a project that does not exist yet in the NetSuite file cabinet, a folder with the same
name as the SuiteScript project where the files belong to will be created.
Note: You can select only one project to upload files from. If you are uploading files for a
selected project that is a closed project in the SuiteCloud IDE, you need to re-open
the project before you can download the files. For more information about closing
and re-opening projects, see Closing projects in the Eclipse documentation.
To upload files in a SuiteScript project:
1.
Launch SuiteCloud IDE.
2.
In SuiteCloud IDE, right-click a project in the NS Explorer pane. The context menu
appears.
3.
In the context menu, go to NetSuite > Upload File(s) to Project. The Upload File(s) to
Project window opens.
4.
Select an account.
5.
Select a role.
6.
Select a file cabinet folder.
7.
Click OK.
Related Topics
•
•
•
•
Creating a SuiteScript Project
Downloading Files in a SuiteScript Project
Working with SuiteScript Projects
Launching SuiteCloud IDE
Downloading Files in a SuiteScript Project
You can download files in a SuiteScript project from the NetSuite file cabinet. If you are
downloading files that already exist in your SuiteCloud IDE, the existing files will be backed up
prior to download and will have the extension, .bak.
Note: You can choose to download files to their respective project folders using Use
project name in file cabinet or to a single target project folder using Use this
project name.
If you are downloading files for a project that is a closed project in the SuiteCloud
IDE, you need to re-open the project first before you can download the files. For
more information about closing and re-opening projects, see Closing projects in the
Eclipse documentation.
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Working with Your SuiteScript Development Environment
54
To download files in a SuiteScript project:
1.
Launch SuiteCloud IDE.
2.
In SuiteCloud IDE, right-click a project in the NS Explorer pane. The context menu
appears.
3.
In the context menu, go to NetSuite > Download File(s) to Project. The Download
File(s) to Project window opens.
4.
Select an account.
5.
Select a role.
6.
Click Get File List.
Note: Hidden bundles, inactive files, and empty folders are excluded from the file list.
7.
Wait for the progress bar to complete.
8.
Select the files that you want to download.
9.
Select Use project name in file cabinet or select Use this project name and enter the
project name that you want to use.
10.
Click OK.
Related Topics
•
•
•
•
Creating a SuiteScript Project
Uploading Files in a SuiteScript Project
Working with SuiteScript Projects
Launching SuiteCloud IDE
Working with SuiteScript Files
With SuiteScript files, you can do the following procedures:
•
Creating a SuiteScript File
•
Uploading a SuiteScript File
•
Downloading a SuiteScript File
•
Comparing a SuiteScript File with File Cabinet Copy
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Working with Your SuiteScript Development Environment
55
Related Topics
•
•
•
•
•
•
•
•
•
•
•
•
•
NetSuite Perspective Overview
SuiteCloud IDE Tips
Usage Examples
Working with SuiteScript Projects
Working with SSP Application Projects
Changing Project Settings
Converting a Project to a SuiteScript Project
Converting a Project to an SSP Application Project
Logging in to a Project Account
Debugging a Project Account
Launching the SuiteScript Records Browser
Viewing Error Logs
Working with Your SuiteScript Development Environment (SuiteCloud IDE)
Creating a SuiteScript File
Use the following steps to create a SuiteScript file in the SuiteCloud IDE.
To create a SuiteScript file:
1.
Launch SuiteCloud IDE.
2.
In SuiteCloud IDE, go to File > New > SuiteScript File. The New SuiteScript File
window opens.
3.
Select a script type.
4.
Enter or select a parent folder.
5.
Enter a script filename.
6.
Click Finish.
Note: You can also create a SuiteScript file through the toolbar. Click the dropdown arrow
beside the NetSuite icon and select SuiteScript File.
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Working with Your SuiteScript Development Environment
56
Related Topics
•
•
•
•
•
Uploading a SuiteScript File
Downloading a SuiteScript File
Comparing a SuiteScript File with File Cabinet Copy
Working with SuiteScript Files
Launching SuiteCloud IDE
Uploading a SuiteScript File
You can upload a SuiteScript file to the NetSuite file cabinet from a SuiteScript project in your
SuiteCloud IDE. If you are uploading a SuiteScript file from a project that does not exist yet in
the NetSuite file cabinet, a folder with the same name as the SuiteScript project where the file
belongs to will be created.
Note: Also, you can upload multiple files but these files must belong to a single project at
a time.
To upload a SuiteScript file:
1.
Launch SuiteCloud IDE.
2.
In SuiteCloud IDE, right-click a file in the NS Explorer pane. The context menu
appears.
3.
In the context menu, go to NetSuite > Upload Selected File(s). The Upload Selected
File(s) window opens.
4.
Select an account.
5.
Select a role.
6.
Select a file cabinet folder.
7.
Click OK.
Note: You can upload a file directly from your Editor area. Right-click anywhere on the
area and then go to NetSuite > Upload File in Editor. You can also use the shortcut,
Ctrl + U. For more information, see Shortcuts in SuiteCloud IDE Tips.
Related Topics
•
•
•
•
•
Creating a SuiteScript File
Downloading a SuiteScript File
Comparing a SuiteScript File with File Cabinet Copy
Working with SuiteScript Files
Launching SuiteCloud IDE
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Working with Your SuiteScript Development Environment
57
Downloading a SuiteScript File
You can download a SuiteScript file from the NetSuite file cabinet to a specified SuiteScript
project in your SuiteCloud IDE. If a SuiteScript file already exists, the existing file will be
backed up prior to download and will have the extension, .bak.
Note: Also, you can download multiple files but these files must belong to a single project
at a time.
To download a SuiteScript file:
1.
Launch SuiteCloud IDE.
2.
In SuiteCloud IDE, right-click a file in the NS Explorer pane. The context menu
appears.
3.
In the context menu, go to NetSuite > Download Selected File(s). The Download
Selected File(s) window opens.
4.
Select an account.
5.
Select a role.
6.
Select a file cabinet folder.
7.
Click OK.
Note: You can download a file directly from your Editor area. Right-click anywhere on the
area and then go to NetSuite > Download File in Editor.
Related Topics
•
•
•
•
•
Creating a SuiteScript File
Uploading a SuiteScript File
Comparing a SuiteScript File with File Cabinet Copy
Working with SuiteScript Files
Launching SuiteCloud IDE
Comparing a SuiteScript File with File Cabinet Copy
Use the following steps to compare your SuiteScript file with its file cabinet copy.
To compare a SuiteScript file with file cabinet copy:
1.
Launch SuiteCloud IDE.
2.
In SuiteCloud IDE, right-click a file in the NS Explorer pane. The context menu
appears.
3.
In the context menu, go to NetSuite > Compare Selected File with File Cabinet Copy.
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Working with Your SuiteScript Development Environment
58
Note: You can compare a file with its file cabinet copy directly from your Editor area.
Right-click anywhere on the area and then go to NetSuite > Compare Selected File
with File Cabinet Copy.
Related Topics
•
•
•
•
•
Creating a SuiteScript File
Uploading a SuiteScript File
Downloading a SuiteScript File
Working with SuiteScript Files
Launching SuiteCloud IDE
Working with SSP Application Projects
SSP application projects are packaged NetSuite Web store customization projects that you can
use to fully customize key NetSuite Web store touch points, such as login, cart, and checkout.
You can use familiar HTML and SuiteScript, and even other Ecommerce platforms for these
customizations.
For more information, see Using SuiteScript Server Pages for Web Store Customizations.
Important: The current version of SuiteCloud IDE only supports code completion for .ss
files. Code completion for .ssp files is not yet supported, and the editor
utilized for these .ssp files is the default HTML editor of Eclipse.
With SSP application projects, you can do the following procedures:
•
Creating an SSP Application Project
•
Uploading Files in an SSP Application Project
•
Downloading Files in an SSP Application Project
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Working with Your SuiteScript Development Environment
Related Topics
•
•
•
•
•
•
•
•
•
•
•
•
•
•
NetSuite Perspective Overview
SuiteCloud IDE Tips
Usage Examples
Working with SuiteScript Projects
Working with SuiteScript Files
Changing Project Settings
Converting a Project to a SuiteScript Project
Converting a Project to an SSP Application Project
Logging in to a Project Account
Debugging a Project Account
Launching the SuiteScript Records Browser
Viewing Error Logs
Working with Your SuiteScript Development Environment (SuiteCloud IDE)
Using SuiteScript Server Pages for Web Store Customizations
Creating an SSP Application Project
Use the following steps to create an SSP application project in the SuiteCloud IDE.
To create an SSP application project:
1.
Launch SuiteCloud IDE.
2.
In SuiteCloud IDE, go to File > New > NetSuite Project. The New NetSuite Project
window opens.
3.
Enter a project name.
4.
Select SSP Application Project as project type.
5.
Select Use default location.
6.
If you do not want to use the default location, deselect Use default location and
navigate to your desired location.
7.
Click Finish.
Related Topics
•
•
•
•
Uploading Files in an SSP Application Project
Downloading Files in an SSP Application Project
Working with SSP Application Projects
Launching SuiteCloud IDE
SuiteScript Developer and Reference Guide
59
Setting Up Your SuiteScript Environment
Working with Your SuiteScript Development Environment
60
Uploading Files in an SSP Application Project
You can upload files in an SSP application project to the NetSuite file cabinet. If you are
uploading files from a project that does not exist yet in the NetSuite file cabinet, a folder with
the same name as the SSP application project where the files belong to will be created.
Note: You can select only one project to upload files from. If you are uploading files for a
selected project that is a closed project in the SuiteCloud IDE, you need to re-open
the project before you can download the files. For more information about closing
and re-opening projects, see Closing projects in the Eclipse documentation.
It is recommended that you already have an application record created for your SSP
application project. This allows you to easily select the directory structure you will
need in the File Cabinet Folder field when you upload your project files. For more
information about creating an application record, see Creating an SSP Application
Record.
To upload files in an SSP application project:
1.
Launch SuiteCloud IDE.
2.
In SuiteCloud IDE, right-click a project in the NS Explorer pane. The context menu
appears.
3.
In the context menu, go to NetSuite > Upload File(s) to Project. The Upload File(s) to
Project window opens.
4.
Select an account.
5.
Select a role.
6.
Select a file cabinet folder.
7.
Click OK.
Related Topics
•
•
•
•
•
Creating an SSP Application Project
Downloading Files in an SSP Application Project
Working with SSP Application Projects
Launching SuiteCloud IDE
Creating an SSP Application Record
Downloading Files in an SSP Application Project
You can download files in an SSP application project from the NetSuite file cabinet. If you are
downloading files that already exist in your SuiteCloud IDE, the existing files will be backed up
prior to download and will have the extension, .bak.
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Working with Your SuiteScript Development Environment
61
Note: You can choose to download files to their respective project folders using Use
project name in file cabinet or to a single target project folder using Use this
project name.
If you are downloading files for a project that is a closed project in the SuiteCloud
IDE, you need to re-open the project first before you can download the files. For
more information about closing and re-opening projects, see Closing projects in the
Eclipse documentation.
To download files in an SSP application project:
1.
Launch SuiteCloud IDE.
2.
In SuiteCloud IDE, right-click a project in the NS Explorer pane. The context menu
appears.
3.
In the context menu, go to NetSuite > Download File(s) to Project. The Download
File(s) to Project window opens.
4.
Select an account.
5.
Select a role.
6.
Click Get File List.
Note: Hidden bundles, inactive files, and empty folders are excluded from the file list.
7.
Wait for the progress bar to complete.
8.
Select the files that you want to download.
9.
Select Use project name in file cabinet or select Use this project name and enter the
project name that you want to use.
10.
Click OK.
Related Topics
•
•
•
•
Creating an SSP Application Project
Uploading Files in an SSP Application Project
Working with SSP Application Projects
Launching SuiteCloud IDE
Changing Project Settings
You can change the settings of a project such as accounts, roles, and file cabinet folders.
To change project settings:
1.
Launch SuiteCloud IDE.
2.
In SuiteCloud IDE, right-click a project in the NS Explorer pane. The context menu
appears.
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Working with Your SuiteScript Development Environment
3.
In the context menu, go to NetSuite > Change Project Settings. The Change Project
Settings window opens.
4.
Select an account.
5.
Select a role.
6.
Select a file cabinet folder.
7.
Click OK.
62
Related Topics
•
•
•
•
•
•
•
•
•
•
•
•
•
•
NetSuite Perspective Overview
SuiteCloud IDE Tips
Usage Examples
Working with SuiteScript Projects
Working with SuiteScript Files
Working with SSP Application Projects
Converting a Project to a SuiteScript Project
Converting a Project to an SSP Application Project
Logging in to a Project Account
Debugging a Project Account
Launching the SuiteScript Records Browser
Viewing Error Logs
Working with Your SuiteScript Development Environment (SuiteCloud IDE)
Launching SuiteCloud IDE
Converting a Project to a SuiteScript Project
You can convert any project to a SuiteScript project.
Important: Only the type and the associated NetSuite libraries of a project are changed.
To convert a project to a SuiteScript project:
1.
Launch SuiteCloud IDE.
2.
In SuiteCloud IDE, right-click a non-SuiteScript project in the NS Explorer pane. The
context menu appears.
3.
In the context menu, go to NetSuite > Convert to SuiteScript Project. The project is
converted into a SuiteScript project.
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Working with Your SuiteScript Development Environment
63
Related Topics
•
•
•
•
•
•
•
•
•
•
•
•
•
•
NetSuite Perspective Overview
SuiteCloud IDE Tips
Usage Examples
Working with SuiteScript Projects
Working with SuiteScript Files
Working with SSP Application Projects
Changing Project Settings
Converting a Project to an SSP Application Project
Logging in to a Project Account
Debugging a Project Account
Launching the SuiteScript Records Browser
Viewing Error Logs
Working with Your SuiteScript Development Environment (SuiteCloud IDE)
Launching SuiteCloud IDE
Converting a Project to an SSP Application Project
You can convert a project to an SSP application project.
Important: Only the type and the associated NetSuite libraries of a project are changed.
To convert a project to an SSP application project:
1.
Launch SuiteCloud IDE.
2.
In SuiteCloud IDE, right-click a non-SSP application project in the NS Explorer pane.
The context menu appears.
3.
In the context menu, go to NetSuite > Convert to SSP Application Project. The project
is converted into an SSP application project.
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Working with Your SuiteScript Development Environment
64
Related Topics
•
•
•
•
•
•
•
•
•
•
•
•
•
•
NetSuite Perspective Overview
SuiteCloud IDE Tips
Usage Examples
Working with SuiteScript Projects
Working with SuiteScript Files
Working with SSP Application Projects
Changing Project Settings
Converting a Project to a SuiteScript Project
Logging in to a Project Account
Debugging a Project Account
Launching the SuiteScript Records Browser
Viewing Error Logs
Working with Your SuiteScript Development Environment (SuiteCloud IDE)
Launching SuiteCloud IDE
Logging in to a Project Account
You can log in to a project account directly from the SuiteCloud IDE.
Important: The current version of SuiteCloud IDE does not support logging in to a
project account for some Linux distributions (or flavors) depending on the
desktop environment used. However, it works well for Windows and Mac OS.
To log in to a project account:
1.
Launch SuiteCloud IDE.
2.
In SuiteCloud IDE, right-click a file or a project in the NS Explorer pane. The context
menu appears.
3.
In the context menu, go to NetSuite > Login Project Account. A browser opens with
your NetSuite account loaded.
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Working with Your SuiteScript Development Environment
65
Related Topics
•
•
•
•
•
•
•
•
•
•
•
•
•
•
NetSuite Perspective Overview
SuiteCloud IDE Tips
Usage Examples
Working with SuiteScript Projects
Working with SuiteScript Files
Working with SSP Application Projects
Changing Project Settings
Converting a Project to a SuiteScript Project
Converting a Project to an SSP Application Project
Debugging a Project Account
Launching the SuiteScript Records Browser
Viewing Error Logs
Working with Your SuiteScript Development Environment (SuiteCloud IDE)
Launching SuiteCloud IDE
Debugging a Project Account
You can debug a project account using the SuiteScript Debugger directly from the SuiteCloud
IDE.
Important: The current version of SuiteCloud IDE does not support debugging a project
account for some Linux distributions (or flavors) depending on the desktop
environment used. However, it works well for Windows and MacOS.
For more information about using the SuiteScript Debugger, see Debugging SuiteScript.
To debug a project account:
1.
Launch SuiteCloud IDE.
2.
In SuiteCloud IDE, right-click a file or a project in the NS Explorer pane. The context
menu appears.
3.
In the context menu, go to NetSuite > Debug Project Account. A browser opens with
your NetSuite account loaded in debug mode.
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Working with Your SuiteScript Development Environment
66
Related Topics
•
•
•
•
•
•
•
•
•
•
•
•
•
•
NetSuite Perspective Overview
SuiteCloud IDE Tips
Usage Examples
Working with SuiteScript Projects
Working with SuiteScript Files
Working with SSP Application Projects
Changing Project Settings
Converting a Project to a SuiteScript Project
Converting a Project to an SSP Application Project
Logging in to a Project Account
Launching the SuiteScript Records Browser
Viewing Error Logs
Working with Your SuiteScript Development Environment (SuiteCloud IDE)
Launching SuiteCloud IDE
Launching the SuiteScript Records Browser
You can launch the SuiteScript Records Browser from the SuiteCloud IDE. The SuiteScript
Records Browser provides a Web-based view of all records, fields, sublists, search joins, search
filters, search columns, and record transformations that are supported in SuiteScript.
For more information, see Using the SuiteScript Records Browser.
To launch Record Browser:
1.
Launch SuiteCloud IDE.
2.
In SuiteCloud IDE, go to Help > Help Contents. The Help - SuiteCloud IDE window
opens.
3.
In the Contents pane, navigate to NetSuite User Guide > Record Browser. The
SuiteScript Records Browser is shown.
Note: You can launch the SuiteScript Records Browser from the editor by pressing Ctrl +
mouse over an internal id. For more information, see Shortcuts in SuiteCloud IDE
Tips.
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Working with Your SuiteScript Development Environment
Related Topics
•
•
•
•
•
•
•
•
•
•
•
•
•
•
NetSuite Perspective Overview
SuiteCloud IDE Tips
Usage Examples
Working with SuiteScript Projects
Working with SuiteScript Files
Working with SSP Application Projects
Changing Project Settings
Converting a Project to a SuiteScript Project
Converting a Project to an SSP Application Project
Logging in to a Project Account
Debugging a Project Account
Viewing Error Logs
Working with Your SuiteScript Development Environment (SuiteCloud IDE)
Launching SuiteCloud IDE
Viewing Error Logs
You can view error logs to help you diagnose or troubleshoot the SuiteCloud IDE. Viewing
error logs is particularly useful for Support teams.
Note: Another way to view error logs in your SuiteCloud IDE is to go to NetSuite >
TroubleShoot > View Log File.
To view error logs:
1.
Launch SuiteCloud IDE.
2.
In SuiteCloud IDE, go to Help > About SuiteCloud IDE. The About SuiteCloud IDE
window opens.
Important: You can see the version of SuiteCloud IDE from this window. The
version number is necessary when filing issues for SuiteCloud IDE.
3.
Click Installation Details. The SuiteCloud IDE Installation Details window opens.
4.
Click Configuration. The Configuration tab is shown.
5.
Click View Error Log. A browser opens with the error log details.
SuiteScript Developer and Reference Guide
67
Setting Up Your SuiteScript Environment
Working with Your SuiteScript Development Environment
68
Related Topics
•
•
•
•
•
•
•
•
•
•
•
•
•
•
NetSuite Perspective Overview
SuiteCloud IDE Tips
Usage Examples
Working with SuiteScript Projects
Working with SuiteScript Files
Working with SSP Application Projects
Changing Project Settings
Converting a Project to a SuiteScript Project
Converting a Project to an SSP Application Project
Logging in to a Project Account
Debugging a Project Account
Launching the SuiteScript Records Browser
Working with Your SuiteScript Development Environment (SuiteCloud IDE)
Launching SuiteCloud IDE
Resetting Your Master Password and Account Info
If you forgot what your master password is, you need to reset your master password and
account info. For security reasons, there is no way for you to retrieve your master password.
This is by design.
To reset your master password and account info:
1.
Launch SuiteCloud IDE.
2.
In SuiteCloud IDE, go to NetSuite > Troubleshoot > Reset Master Password and
Account Info. A dialog appears warning you that your SuiteCloud IDE will be restarted
and that your master password, along with all of your account information, will be
deleted.
3.
Click OK. SuiteCloud IDE restarts with your workspace still intact but your master
password and account info deleted.
4.
Set up your master password and account info. For more information, see Setting a
Master Password and Adding an Account.
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Working with Your SuiteScript Development Environment
Related Topics
•
•
•
•
•
•
•
•
•
•
•
•
•
•
NetSuite Perspective Overview
SuiteCloud IDE Tips
Usage Examples
Working with SuiteScript Projects
Working with SuiteScript Files
Working with SSP Application Projects
Changing Project Settings
Converting a Project to a SuiteScript Project
Converting a Project to an SSP Application Project
Logging in to a Project Account
Debugging a Project Account
Launching the SuiteScript Records Browser
Working with Your SuiteScript Development Environment (SuiteCloud IDE)
Launching SuiteCloud IDE
SuiteScript Developer and Reference Guide
69
Setting Up Your SuiteScript Environment
Working with IDEs Other Than SuiteCloud IDE
70
Working with IDEs Other Than SuiteCloud IDE
Although NetSuite recommends that you use SuiteCloud IDE when writing SuiteScript, you
can still use other development tools to create SuiteScript. Note, however, without SuiteCloud
IDE, you will not be able to automatically upload SuiteScript files into the NetSuite file cabinet.
Important: For more information about NetSuite’s recommended development
environment, see Setting Up Your SuiteScript Development Environment
(SuiteCloud IDE).
If you choose to use a development tool or IDE other than SuiteCloud IDE, see the following
sections:
•
Adding the SuiteScript Library File to Your IDE
•
Uploading SuiteScript into the File Cabinet Without the SuiteCloud IDE
Adding the SuiteScript Library File to Your IDE
If you are working with an IDE other than SuiteCloud IDE, you should still add the SuiteScript
library file to your SuiteScript project folder in your IDE.
To add the SuiteScript library file:
1.
In NetSuite, go to Documents > Files > SuiteScripts.
2.
Next, click the link to the SuiteScript API file (see figure).
3.
Copy and paste the SuiteScript API file into your IDE.
4.
Save the file as a .js file.
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Working with IDEs Other Than SuiteCloud IDE
71
Uploading SuiteScript into the File Cabinet Without the SuiteCloud IDE
Once the SuiteScript feature is enabled, a new SuiteScripts folder is created in the NetSuite file
cabinet. The file cabinet is considered as the central repository for all your .js SuiteScript files.
Therefore, your SuiteScript files should exist in the file cabinet before they can be executed in
your NetSuite account.
Note:
•
The SuiteScripts folder within the file cabinet is provided for convenience,
however, you can store the script files in any location.
•
For steps on enabling the SuiteScript feature, see Enabling SuiteScript.
If you are not uploading your scripts into the file cabinet using the SuiteCloud IDE, use the
following steps.
To upload SuiteScript into the file cabinet:
1.
Go to Documents > Files > SuiteScripts.
2.
Click the Add File button in the lower-left corner of your screen (see figure).
3.
In the File Upload window that appears, navigate to the file you want to upload, select
the file, and click Open.
Note: If you make changes to a SuiteScript file that already exists in the file cabinet, follow
steps 1–3 to re-upload the changed file. Click OK to overwrite the previous file and
load your changes (see figure).
SuiteScript Developer and Reference Guide
Setting Up Your SuiteScript Environment
Working with IDEs Other Than SuiteCloud IDE
SuiteScript Developer and Reference Guide
72
Part 2 Running a Script in
NetSuite
Chapter 4 Step 1: Create Your Script
All SuiteScript files must end with a JavaScript (.js) file extension. Although you can use any
text editor (including Notepad) to write your SuiteScript .js files, NetSuite recommends you use
the SuiteCloud IDE. If you have not installed SuiteCloud IDE, see Setting Up Your SuiteScript
Development Environment (SuiteCloud IDE) in the NetSuite Help Center.
Depending on what you are trying to do in NetSuite, the code in your .js file can be as simple as
a client script that never even touches a NetSuite server. It runs purely client-side in the
browser and alerts users after they have loaded a specific NetSuite record, for example:
function pageInitAlertUser()
{
alert ('You have loaded a record');
}
Alternatively, your script can be can be as complex as executing a NetSuite search, getting the
results, and then transforming the results into a PDF document. See the samples for
nlapiXMLToPDF(xmlstring) as an example.
The APIs you use in your code and the logic you write will depend on what you’re trying to
accomplish in NetSuite. See What can I do with the SuiteScript API? if you are unsure of what
you can do using the SuiteScript API.
After you have created your .js file, see Step 2: Add Script to NetSuite File Cabinet.
Note: To see which APIs are included in the SuiteScript API, start with SuiteScript API
Overview.
SuiteScript Developer and Reference Guide
Chapter 5 Step 2: Add Script to NetSuite
File Cabinet
If you are writing your script files in SuiteCloud IDE, loading a file into the NetSuite file
cabinet is as easy as right-clicking on your file in SuiteCloud IDE and selecting NetSuite >
Upload Selected File(s). For more information, see Uploading a SuiteScript File.
If you have written your .js files in anything other than SuiteCloud IDE, you will need to
manually upload your files into NetSuite. See Uploading SuiteScript into the File Cabinet
Without the SuiteCloud IDE for details.
Note: The SuiteScripts folder in the file cabinet is provided for convenience, however,
you can store your script files in any location.
Once your script has been added to the NetSuite file cabinet, see either:
•
Step 3: Attach Script to Form (if you want to run a form-level client script in NetSuite)
•
Step 4: Create Script Record (if you want to run any other script type. For example, if
you want to run a user event, scheduled, portlet, Suitelet, action, or record-level client
script, proceed to Step 4.)
SuiteScript Developer and Reference Guide
Chapter 6 Step 3: Attach Script to Form
Form-level client scripts are simply “attached” to the forms they run against. Be aware that in
NetSuite, there are two different types of client SuiteScript. The information in this section
pertains ONLY to form-level client scripts.
Important: For the differences between form- and record-level client scripts, see Formlevel and Record-level Client Scripts.
To attach a form-level client script to a custom form:
1.
Ensure your client script has been uploaded into NetSuite. (See Step 2: Add Script to
NetSuite File Cabinet.)
2.
Go to the desired custom form in NetSuite.
Form-level client scripts can only be attached to custom entry forms, custom
transaction forms, and custom online forms. Click Setup > Customization > [Form].
3.
Next, click Customize next to the desired custom form, or click Customize next to an
existing standard form in order to create a new custom form based that is based on the
standard version.
Note: For more information on creating custom entry, transaction, and online forms,
refer to the SuiteBuilder (Customization) Guide.
4.
On the Custom Code tab on the form, select your script file and, if necessary, the
library file to associate with the current form (see figure).
The library script file should contain any commonly used functions. The SuiteScript
file should contain functions specific to the current form.
5.
Based on the APIs used in your SuiteScript or library files, define which functions
should be called on which client events. If you are unsure of which actions trigger each
client event, see Client Event Functions. To learn how many functions you can execute
on one form, see How Many Client Events Can I Execute on One Form?
The following figure shows a custom form called Wolfe Electronics Sales Order. This
form is set as the “preferred” form for sales orders. What this means is that all
customizations made to this form, and any client script file attached to the form will
run whenever a NetSuite user navigates to and loads sales order record. This figure
indicates that when a sales order loads, three different functions will execute.
• The savRecUpdatePrice function will execute when the record is saved.
• The valFieldItemPrice function will execute when a particular field on the sales
order is changed.
SuiteScript Developer and Reference Guide
Step 3: Attach Script to Form
77
• The recalcTotalAndTax function will execute when a line item as been added to a
sublist.
Important: Be sure to enter function names exactly as they appear in your script.
However, do not include parenthesis or parameter values when you enter
the function name on the custom form.
Important: When adding a client script file to an online form, select the Available
Without Login check box to ensure that the script will run on the form. If this
check box is not selected, the user will still have access to the form, however,
the client script will not run.
The Available Without Login check box appears in the File popup window
when adding a new file to the Script File field (by clicking the + icon). (See
previous figure.)
SuiteScript Developer and Reference Guide
Step 3: Attach Script to Form
78
If you are selecting your .js file from a list of files in the NetSuite file cabinet, click Edit next to
the script file, and then select Available Without Login on the script record.
After you have attached your form-level client script to a form, your script will execute
whenever the triggering action occurs. For a list of possible client event triggers, see Client
Event Functions.
If you have created a form-level client script, you do not need to go to Step 4: Create Script
Record or Step 5: Define Script Deployment. You are done!!!!!
Related Topics
•
•
•
Client Scripts
Form-level and Record-level Client Scripts
Client Script Best Practices
SuiteScript Developer and Reference Guide
Chapter 7 Step 4: Create Script Record
After writing your SuiteScript .js file and uploading the file to the file cabinet, you must then
create a Script record for the file (see figure).
On the Script record you will:
•
Add your SuiteScript .js file.
•
Define the script owner.
•
If applicable, add one or more library files.
•
Define the function(s) from your SuiteScript file you want executed.
•
If applicable, create script parameters (custom fields) that are unique to the Script
record.
•
Specify who should be contacted if an error is thrown in your script.
Although you do not need to set every field on the Script record, at a minimum you must set
the following (see figure):
1.
Provide a name for the Script record.
2.
Specify the script owner.
3.
Load your SuiteScript .js file.
4.
Specify the main executing function within the file.
Important: See Steps for Creating a Script Record for more detailed information.
SuiteScript Developer and Reference Guide
Step 4: Create Script Record
SuiteScript Developer and Reference Guide
80
Step 4: Create Script Record
Steps for Creating a Script Record
81
Steps for Creating a Script Record
The following steps provide details for creating a Script record. For an overview that explains
the purpose of the Script record, be sure to see Step 4: Create Script Record.
To create a script record:
1.
Go to Setup > Customization > Scripts > New.
Note that after creating your script record, you can later access the record by going to
Setup > Customization > Scripts to see a list view of all Script records.
2.
Select the script type (see figure).
Note: The Client scripts listed here are record-level client script. These scripts run in
addition to any form-level client scripts that might have already been attached to
an existing form. For information on the differences between form- and recordlevel client scripts, see Form-level and Record-level Client Scripts.
3.
In the Script record Name field, enter a name for the script record.
You can have multiple deployments of the same SuiteScript file. Therefore, be sure that
the name of the Script record is generic enough to be relevant for all deployments.
For example, you may want your SuiteScript (.js) file to execute whenever Vendor
records are saved. You might also want this script to execute whenever Customer
records are saved. You will need to define two different deployments for the script.
However, both deployments will reference the same script / Script record.
(Information on defining script deployments is covered in Step 5: Define Script
Deployment.)
4.
In the ID field, if desired, enter a custom ID for the script record. If the ID field is left
blank, a system-generated internal ID is created for you.
For information on whether you should create your own custom ID, see Creating a
Custom Script Record ID.
5.
If you are creating a Script record for a Portlet script, select the portlet type from the
Portlet Type drop-down list.
For information on portlet types, see Portlet Scripts in the NetSuite Help Center.
6.
In the Description field, if desired, enter a description for the script.
SuiteScript Developer and Reference Guide
Step 4: Create Script Record
Steps for Creating a Script Record
7.
82
In the Owner field, select a script owner.
By default the owner is set to the currently logged-in user. Once the Script record is
saved, only the owner of the record or a system administrator can modify the record.
8.
(Optional) Select the Inactive check box if you do not want to deploy the script. When
a script is set to Inactive, all of the deployments associated with the script are also
inactive. If you wish to inactivate a specific deployment rather than all deployments of
this scripts, go to the Script Deployments page.
9.
On the Scripts tab, set the following:
a.
In the Script File field, select the SuiteScript .js file to associate with the current
script record.
If you have uploaded your script into the NetSuite file cabinet, your script will
appear in the Script File drop-down list. For directions on uploading scripts into
the file cabinet, see either of the following sections:
•
Uploading a SuiteScript File - If you are uploading scripts using the
SuiteCloud IDE.
•
Uploading SuiteScript into the File Cabinet Without the SuiteCloud IDE - If
you are not uploading your scripts using the SuiteScript plug-in for Eclipse.
Note: If you are maintaining your SuiteScript files outside of the file cabinet, click
the + button next to the Script File drop-down. In the popup window that appears,
browse for your .js file.
b.
(Optional) In the Library Script File field, select the library files you want to
associate with the Script record.
A library script file should contain any commonly used functions, whereas the
SuiteScript file should contain functions specific to the current Script record. Note
that multiple library files can be added to a script record.
Also be aware that the system reads your library files in the order they appear on
the Library Script File tab. For example, if your first library file references the
second library file, an error will be thrown, since the first library file is loaded
before the second.
c.
In the Function field(s), type the name of the function(s) you want executed in the
.js file. Do not include the function parentheses or any parameters. For example,
type myFunction rather than myFunction(param1, param2).
• If defining a User Event script, you can execute one function per operation type.
For example, you can have a before load function and an after submit function
defined within the same script execution. These functions must exist in either the
library script file or the SuiteScript file associated with the script record.
Note: For details on the before load, before submit, and after submit operations,
see User Event beforeLoad Operations andUser Event beforeSubmit and
afterSubmit Operations.
SuiteScript Developer and Reference Guide
Step 4: Create Script Record
Steps for Creating a Script Record
83
• If defining a record-level Client script, type the names of the functions you want
executed when the script runs. As the following figure shows, enter the function
name in the field next to the client event that will trigger the function. Note that
your functions must exist in either the library script file or the SuiteScript file
associated with the script record. You have the option of calling up to eight
functions from within the same script file.
• If defining a bundle installation script, type the names of the functions you want
executed before the bundle is installed, after the bundle is installed, before the
bundle is updated, or after the bundle is updated. Enter the function name in the
field next to the bundle deployment event that will trigger the function. Note that
these functions must exist in the SuiteScript file associated with the script record.
If these functions call functions in other script files, these files should be listed as
library files.
10.
On the Parameters tab, define possible parameters (custom fields) to pass to the
functions specified in the previous step.
11.
On the Unhandled Errors tab, define which individual(s) will be notified if script
errors occur.
• By default the Notify Script Owner check box is selected.
• (Optional) Select Notify All Admins if all admins should be notified.
SuiteScript Developer and Reference Guide
Step 4: Create Script Record
Steps for Creating a Script Record
84
• (Optional) Select the groups that should be notified. Only existing groups are
available in the Groups notification drop-down list. To define new groups, go to
Lists > Relationships > Groups > New.
• (Optional) Enter the email address of anyone who should be notified. You can also
enter a comma-separated list of email addresses.
12.
From the Save button:
a.
If you want to save the script record, but you are not ready to deploy the script,
select the Deployments tab, clear the Deployed check box, and click Save.
Important: Scripts will not execute until they are deployed.
13.
b.
If you want to Save the script record and deploy the script, but you are not yet
ready to define the script’s runtime/deployment behaviors, simply click Save.
c.
If you want to save the script record and automatically open the Script
Deployment page, click Save and Deploy. Use the Script Deployment page to
define runtime behaviors such as when the script will run and which accounts the
script will run in.
Now that you have created a Script record for your script, go to Step 5: Define Script
Deployment.
Note: Although the Script record has a Deployments tab that allows you to define many
of the same deployment options found on the Script Deployment page, it is
recommended that you define your deployments on the Script Deployment page.
This page provides deployment settings that are not available on the Deployments
tab of the Script record.
SuiteScript Developer and Reference Guide
Step 4: Create Script Record
Creating a Custom Script Record ID
85
Creating a Custom Script Record ID
All Script records have an ID. Many SuiteScript APIs contain parameters such as ID or
scriptID. Through these parameters you pass the scriptId or internalId of the script record.
The scriptId is considered to be a custom ID you create yourself for the Script record. If you do
not create your own scriptId, then the system generates an ID for you. In the documentation,
the system-generated ID is referred to as simply the Script record’s internalId.
For an example of how Script record IDs are used in a SuiteScript API call, see
nlapiScheduleScript(scriptId, deployId, params).
Note: You can programmatically get the the value of a scripId by calling
nlobjContext.getScriptId().
If you choose, you can create a custom ID for your Script record. If the ID field is left blank on
the Script record, a system-generated ID is created for you. This is the ID that appears in the
ID field once the Script record is saved.
Whether creating a custom ID or accepting a system-generated ID, once the script record is
saved, the system automatically adds customscript to the front of the ID.
Why Should I Create a Custom ID?
Custom IDs are recommended if you plan to use the SuiteBundler feature to bundle the script
and deploy it into another NetSuite account. Custom IDs reduce the risk of naming conflicts
for scripts deployed into other accounts. (For details on bundling scripts, see SuiteBundler
Overview in the NetSuite Help Center.)
When creating a custom ID it is recommended that you insert an underscore ( _ ) before the ID
to enhance readability. For example, a custom script ID called _employeeupdates will appear as
customscript_employeeupdates once the Script record is saved. Similarly, a custom deployment
ID will appear as customdeploy_employeeupdates once the Script Deployment page is saved.
Important: Custom IDs must be in lowercase and contain no spaces. Also, custom IDs cannot
exceed 30 characters in length. These 30 characters do not include the customscript or
customdeploy prefixes that are automatically appended to the ID.
SuiteScript Developer and Reference Guide
Step 4: Create Script Record
Creating a Custom Script Record ID
86
Can I Edit an ID?
Although not recommended, you can edit both custom and system-generated IDs once the
Script record or script deployment is saved. To edit an ID, click the Change ID button that
appears on both script record and script deployment pages AFTER each has already been
saved.
The following figure shows the Change ID button on a Script Deployment page after the
deployment has been saved.
After clicking the Change ID button, the Change Script ID page appears. This page shows the
old ID and provides a field for creating a new ID.
Important: Once you change a script record or script deployment ID, you MUST update
all references to that ID in your code files.
Related Topics
•
•
Step 4: Create Script Record
Step 5: Define Script Deployment
SuiteScript Developer and Reference Guide
Chapter 8 Step 5: Define Script
Deployment
Once you have created a Script record for your SuiteScript file, you must then “deploy” the
script into NetSuite. A script’s deployment definitions, as set on the Script Deployment page,
affect its runtime behaviors when it is released into NetSuite.
Some of these deployment definitions include:
•
When the script will be executed
•
Audience and role restrictions for a script
•
Script log levels
•
Deployment-specific parameter defaults
•
Specific records the script will run against
Note that Script Deployment pages look different for each script type. For example, the Script
Deployment page for a user event script will not include an area for you to define the script’s
deployment schedule. The Script Deployment page for a scheduled script, however, will
include an area for this. Deployment pages for Suitelets will include a field for setting whether
the Suitelet executes on a GET or POST request. The deployment page for a global client script
will not include such a field.
Because Script Deployment pages vary depending on the script type, see Steps for Defining a
Script Deployment for general steps that are applicable to most script types. See Setting
Runtime Options Overview for information on setting more advanced runtime options. In
many cases, these more advanced options are specific to a particular script type.
Important Things to Note:
•
You cannot edit a Script Deployment record while the script associated with the
deployment is running in NetSuite.
•
Multiple deployments can be applied to the same record. These deployments are
executed in the order specified in the UI. If an error occurs in one deployment,
subsequent deployed scripts may NOT be executed. When troubleshooting, verify you
are executing only one script per record type.
SuiteScript Developer and Reference Guide
Step 5: Define Script Deployment
Steps for Defining a Script Deployment
88
Steps for Defining a Script Deployment
For an overview of the Script Deployment record, be sure to see Step 5: Define Script
Deployment. This section describes why a Script Deployment record is required for each
script.
To define a script deployment:
1.
When you save your Script record, you can immediately create a Script Deployment
record by selecting Save and Deploy from the Script record Save button.
If you want to update a deployment that already exists, go to Setup > Customization >
Script Deployments > [deployment] > Edit.
2.
On the Script Deployment page:
• For Suitelet, Scheduled, and Portlet scripts, in the Title field, provide a name for
the deployment.
• For User Event and Client scripts, in the Applies To field, select the record the
script will run against. In the Applies To field you can also select All Records to
deploy the script to all records that officially support SuiteScript. (For a list of these
records, see SuiteScript Supported Records.)
3.
In the ID field, if desired, enter a custom scriptId for the deployment. If you do not
create a scriptId, a system-generated internalId is created for you.
For information on whether to create a custom ID, see Creating a Custom Script
Deployment ID.
4.
(Optional) Clear the Deployed check box if you do not want to deploy the script.
Otherwise, accept the default. A script will not run in NetSuite until the Deployed
check box is selected.
5.
In the Status field, set the script deployment status. See Setting Script Deployment
Status.
6.
(Optional) In the Event Type drop-down list, specify an event type for the script
execution. See Setting Script Execution Event Type from the UI.
7.
(Optional) In the Log Level field, specify which log messages will appear on the
Execution Log tab once the script is executed. See Setting Script Execution Log Levels.
8.
In the Execute as Admin check box, select whether you want the script to execute
using administrative priviledges, regardless of the permissions of the currently logged
in user. See Executing Scripts as Admin.
9.
On the Audience tab, specify the audiences for the script. See Defining Script
Audience.
10.
On the Links tab (for Suitelets only), if you want to launch your Suitelet from the UI,
create a menu link for the Suitelet. See Running a Suitelet in NetSuite.
SuiteScript Developer and Reference Guide
Step 5: Define Script Deployment
Creating a Custom Script Deployment ID
11.
(Optional) On the Execution Log tab, create custom views for all script logging
details. See Using the Script Execution Log.
12.
Click Save.
89
Note that for portlet scripts, you must enable the portlet to display on your dashboard
(see Displaying Portlet Scripts on the Dashboard).
Creating a Custom Script Deployment ID
Script deployment IDs are necessary for SuiteScript development. Many SuiteScript API calls
contain parameters such as ID, scriptID, and deployID that reference the IDs on the Script
Deployment page.
These parameters allow you to pass the values of an internalId (a system-generated ID) or a
scriptId (a custom ID that you provide). For an example of how script record and script
deployment IDs are used in a SuiteScript API call, see nlapiScheduleScript(scriptId, deployId,
params).
If you choose, you can create a custom ID for your script deployment. If the ID field is left
blank on the Script Deployment page, a system-generated ID is created for you. This is the ID
that appears in the ID field once the Script Deployment page is saved.
Whether creating a custom ID or accepting a system-generated ID, once the script deployment
is saved, the system automatically adds customdeploy to the front of the ID.
The following figure shows a list of script deployments (Setup > Customization > Script
Deployments). Note that there is a combination of custom IDs (for example,
customdeploy_campaign_assistant) and system-generated deployment IDs (for example
customdeploy1). Although customdeploy1 is the ID for many script deployments, be aware
that deployment IDs are unique only within a given script definition.
If you are unsure whether to create your own custom ID or accept a system-generated ID, see
Why Should I Create a Custom ID? for more information.
Also see Can I Edit an ID? for information on editing IDs.
SuiteScript Developer and Reference Guide
Chapter 9 Viewing Script Deployments
There are several ways to view your script deployments:
•
Go directly to the script deployment by clicking Setup > Customization > Scripting >
Script Deployments.
•
View deployed scripts by clicking View Deployments in the upper-right corner of the
Script record.
•
Click the Deployments tab on a Script record to see the deployments specific to that
Script record. Next, click on a specific deployment to go to the deployment record.
Remember: In each specific deployment record you can define default parameter
values for that deployment. Note that first you must create the script parameter before
you can define its value on a Script Deployment record.
For more information, see Creating Script Parameters Overview in the NetSuite Help
Center. Also see Setting Script Parameter Preferences for information that is specific to
setting script parameter values on the Script Deployment record.
•
View a list of records that have scripts associated with them at Setup > Customization >
Scripting > Scripted Records. For complete details, see Using the Scripted Records
Page in the NetSuite Help Center.
By default, the Scripted Records list displays only those records that have at least one
script associated with them.
Related Topics
•
•
Running Scripts in NetSuite Overview
Step 5: Define Script Deployment
SuiteScript Developer and Reference Guide
Chapter 10 Using the Scripted Records
Page
Within NetSuite you can view a list of all records that have user event or global client scripts
associated with the record (see figure). By default, only the records that have at least one script
associated with them will appear in the list.
Note: To see a list of all records in your account, click the Show Undeployed check box in
the lower-left corner of the Scripted Records list. You can also use the Script filter
drop-down to show only those records associated with specific scripts.
The Scripted Records list is helpful if you are trying to determine whether a record has a script
associated with it that might be causing a problem. You can also use this list to drill down to a
specific record to specify the execution order of scripts associated with each record, edit script
deployment statuses, and inactivate specific deployments.
To view this list, go to Setup > Customization > Scripted Records.
To change the deployment status of a script associated with a specific record, click Edit in the
Scripted Records list.
The following figure shows a Scripted Record page for the Case (supportcase) record.
SuiteScript Developer and Reference Guide
Using the Scripted Records Page
92
On the Scripted Record page, use the User Event Scripts tab to:
•
Change the script execution order of user event scripts - in other words, have the third
script execute first by moving the script to the top of the list
•
Change script deployment statuses from Testing to Released
•
Set scripts to deployed or undeployed (by checking the Deployed check box)
•
View the names of the functions that are set to execute on before load, before submit,
and after submit user events
Use the Client Scripts tab to:
•
Change the script execution order of global client scripts
•
Change script deployment statuses from Testing to Released
•
Set scripts to deployed or undeployed (by checking the Deployed check box)
•
View the names of the functions that are set to execute on various client event triggers
Use the Custom Forms tab to:
•
View all forms associated with this record type. Even forms that do not have a script
attached will appear in this list.
•
Access each form directly by clicking the form links
•
View the name of the SuiteScript .js file that has been attached to each form
•
View the names of the functions that are set to execute on various client event triggers
SuiteScript Developer and Reference Guide
Using the Scripted Records Page
Related Topics
•
•
•
•
User Event Scripts
Client Scripts
Viewing Script Deployments
Step 5: Define Script Deployment
SuiteScript Developer and Reference Guide
93
Chapter 11 Using the Script Execution Log
Script execution details are logged on the Execution Log tab that appears on the Script
Deployment page and in the SuiteScript Debugger.
Important: If you are using the SuiteScript Debugger to debug a script, all logging
details will appear on the Execution Log tab in the Debugger. These details
will not also appear on the Execution Log tab on the Script Deployment
page for the same script. To have logging details appear on the Execution
Log tab of the Script Deployment page, you must deploy the script.
The figure below shows two types of execution details. One is an unexpected error that was
generated because a method was not defined in Suitelet script. The other is a user-generated
execution log that was generated by the following line in the Suitelet code:
nlapiLogExecution('DEBUG', 'Suitelet Details', 'Suitelet method = ' + request.getMethod());
Be aware that the View drop-down field in the Execution Log defaults to “Default Script Notes
View.” This default shows only the current day’s script executions. If you want to see script
executions for days other than the current day, click the Customize View button.
Within the Customize View window, you can specify values such as script execution dates,
details, names, and script types (see figure). In the Search Title field you can provide a custom
name for this view.
SuiteScript Developer and Reference Guide
Using the Script Execution Log
95
Important: When customizing your Execution Log view, be aware that NetSuite purges
user-generated execution log details every 30 days. System errors that
appear on the Execution Log are purged every 60 days. Although the UI
allows you to set date values as far back as two years (meaning you can see
the last two years of script execution details), you will actually only be able to
see up to 30 days of user-generated details (captured by nlapiLogExecution)
and 60 days for system errors.
The last figure shows a customized view of the Execution Log. Notice that the new view type
has been selected from the View drop-down. This view shows execution log details for days
other than just the current day.
Related Topics
•
•
•
Setting Script Execution Log Levels
Debugging SuiteScript
nlapiLogExecution(type, title, details)
SuiteScript Developer and Reference Guide
Part 3 Scripting Records,
Fields, Forms, and
Sublists
Chapter 12 Working with Records and
Subrecords in SuiteScript
The following topics are covered in this section:
•
Working with Records in SuiteScript
•
How Records are Processed in Scripting
•
Working with Subrecords in SuiteScript
•
Working with Records in Dynamic Mode
Note: For a list of SuiteScript supported records, see SuiteScript Supported Records in the
NetSuite Help Center.
Working with Records in SuiteScript
The SuiteScript API includes several Record APIs that interact with the entire NetSuite record
object. When you work with Record APIs, you are doing things such as creating, deleting,
copying, or loading all elements of a record.
Whether you are working with standard NetSuite records (for example, Sale Order, Invoice,
Customer, Vendor) or custom records you have created using SuiteBuilder, you will use all the
same Record APIs to interact with the record object.
Note: For a list of SuiteScript supported records, see SuiteScript Supported Records in the
NetSuite Help Center.
The following figure shows a Sale Order record. The elements of this record, as well as most
other records in NetSuite, include fields, subtabs, sublists, sublist fields, and buttons.
SuiteScript Developer and Reference Guide
Working with Records and Subrecords in SuiteScript
How Records are Processed in Scripting
98
How Records are Processed in Scripting
When using SuiteScript to interact with records, NetSuite will process your data and execute all
core NetSuite business logic once the data is submitted.
As a SuiteScript developer, note the following when working with records:
•
You can write your SuiteScript code without having to “reverse engineer” NetSuite
logic. When you submit the record, the validation, sourcing, and recalculation logic
that automatically occurs in the UI will also occur when you submit a record in
SuiteScript. This is considered the standard mode of processing.
•
When scripting in standard mode (as opposed to dynamic mode), you do not have to
write your code in a way that references fields in the order they are referenced in the
UI. (To learn more about dynamic mode scripting, see Working with Records in
Dynamic Mode.)
SuiteScript Developer and Reference Guide
Working with Records and Subrecords in SuiteScript
Working with Subrecords in SuiteScript
•
99
When scripting in standard mode (as opposed to dynamic mode), you will have to
submit and then reload a record to know the values for calculated fields. For example,
you will need to submit and then reload a record to know how much an item will cost
after NetSuite applies tax and shipping amounts to the data submitted.
Working with Subrecords in SuiteScript
This section contains following topics. If you are not familiar with subrecords, it is suggested
that you read these topics in order:
•
What is a Subrecord?
•
Using the SuiteScript API with Subrecords
•
Creating and Accessing Subrecords from a Body Field
•
Creating and Accessing Subrecords from a Sublist Field
•
Setting Values on Subrecord Sublists
•
Saving Subrecords Using SuiteScript
•
Guidelines for Working with Subrecords in SuiteScript
Important: Subrecords are used in the context of the Advanced Bin / Numbered
Inventory Management feature. Currently, the only supported subrecord in
NetSuite is the Inventory Detail subrecord. For scripting examples that show
how to use Subrecord APIs in the context of this feature, see Using
SuiteScript with Advanced Bin / Numbered Inventory Management.
What is a Subrecord?
A subrecord includes many of the same elements of a standard NetSuite record (body fields,
sublists and sublist fields, and so on). However, subrecords must be created, edited, removed,
or viewed from within the context of a standard (parent) record.
The purpose of a subrecord is to hold key related data about the parent record. For example, a
parent record would be a Serialized Inventory Item record. This record defines a type of item.
A subrecord would be an Inventory Detail subrecord. This is a subrecord that contains all data
related to where the item might be stored in a warehouse. In this way, the subrecord contains
data related to the item, but not data that directly defines the item. Without the parent record,
the subrecord would serve no purpose.
Important: Subrecords are used in the context of the Advanced Bin / Numbered
Inventory Management feature. Currently, the only supported subrecord in
NetSuite is the Inventory Detail subrecord.
The following figure shows an Inventory Detail subrecord. Its parent is a Bill record. In this
figure the Inventory Detail subrecord is accessed through the Inventory Details sublist field.
SuiteScript Developer and Reference Guide
Working with Records and Subrecords in SuiteScript
Working with Subrecords in SuiteScript
100
The Inventory Detail subrecord contains the inventory details for the item called the Lot Bin
Item.
In this case the parent record is still the Bill record, even though the subrecord tracks inventory
details related to the Lot Bin Item. Ultimately it is the Bill record that must be saved before the
subrecord (pertaining to an item on the Bill) is committed to the database.
Creating Subrecord Custom Entry Forms
You can create custom entry forms for subrecords by going Setup > Customization > Entry
Forms. Currently the only supported subrecord type is Inventory Detail, which is associated
with the Advanced Bin / Numbered Inventory Management feature. Therefore, in the Custom
Entry Forms list, you can select Customize next to Inventory Detail to create a custom form for
this subrecord type.
Note that when you create a custom form for Inventory Detail, you can use the Actions tab to
add new buttons to the custom form. When clicked, these buttons will execute client
SuiteScript. However, you cannot customize the buttons that currently exist on the Inventory
SuiteScript Developer and Reference Guide
Working with Records and Subrecords in SuiteScript
Working with Subrecords in SuiteScript
101
Detail record. These buttons are required; without them you cannot save this subrecord to its
parent record.
Also note that the Store Form with Record preference is not currently supported for custom
subrecord forms. You can, however, set the customized subrecord form as Preferred.
Additionally, like any other custom form, you can attach client scripts to the Custom Forms
tab.
Related Topics
•
•
•
•
•
•
Using the SuiteScript API with Subrecords (recommended next topic to read)
Creating and Accessing Subrecords from a Body Field
Creating and Accessing Subrecords from a Sublist Field
Setting Values on Subrecord Sublists
Saving Subrecords Using SuiteScript
Guidelines for Working with Subrecords in SuiteScript
Using the SuiteScript API with Subrecords
The SuiteScript API includes several Subrecord APIs to interact with the subrecord object
(nlobjSubrecord).
Using SuiteScript you can create and access subrecords through a body field on a parent
record. (See Creating and Accessing Subrecords from a Body Field for details.) You can also
create and access subrecords through a sublist field on a parent record. (See Creating and
Accessing Subrecords from a Sublist Field for details.)
To set values on sublists that appear on subrecords, you will use some of the same Sublist APIs
used to set values on sublists appearing on parent records. See Setting Values on Subrecord
Sublists for details.
To save a subrecord, you must follow the pattern outlined in the section Saving Subrecords
Using SuiteScript.
Related Topics
•
•
•
What is a Subrecord?
Guidelines for Working with Subrecords in SuiteScript
Using SuiteScript with Advanced Bin / Numbered Inventory Management
Creating and Accessing Subrecords from a Body Field
If you want to create a subrecord to hold data related to the parent, you can do so from a body
field on the parent. When working with subrecords from a body field on the parent, you will
SuiteScript Developer and Reference Guide
Working with Records and Subrecords in SuiteScript
Working with Subrecords in SuiteScript
102
use the following APIs if you are working with the parent record in a “current record” context,
such as in a user event script or a client script:
•
nlapiCreateSubrecord(fldname)
•
nlapiEditSubrecord(fldname)
•
nlapiRemoveSubrecord(fldname)
•
nlapiViewSubrecord(fldname)
Note: nlapiCreateSubrecord(fldname) and nlapiEditSubrecord(fldname) are not currently
supported in client scripts.
If you are loading the parent record using SuiteScript, you will use these methods on the
nlobjRecord object to create and access a subrecord:
•
createSubrecord(fldname)
•
editSubrecord(fldname)
•
removeSubrecord(fldname)
•
viewSubrecord(fldname)
The following figure shows the Inventory Details (inventorydetail) body field on the parent
record. To create a subrecord of inventory details related to the parent, you will do so from this
body field. After creating the subrecord, you can then edit, remove, or view the subrecord
through the same body field on the parent record.
Note that after creating or editing a subrecord, you must save both the subrecord and the
parent record for the changes to be committed to the database. See Saving Subrecords Using
SuiteScript for more information.
SuiteScript Developer and Reference Guide
Working with Records and Subrecords in SuiteScript
Working with Subrecords in SuiteScript
103
For code samples showing how “body field” subrecord APIs are used, see Using SuiteScript
with Advanced Bin / Numbered Inventory Management.
Related Topics
•
•
•
What is a Subrecord?
Creating and Accessing Subrecords from a Sublist Field
Guidelines for Working with Subrecords in SuiteScript
Creating and Accessing Subrecords from a Sublist Field
If you want to create a subrecord to hold data for a record in a sublist, you can do so from a
sublist field.
When working with subrecords from a sublist field on the parent record, you will use these
APIs if you are working with the parent record in a “current record” context, such as in a user
event script or a client script:
•
nlapiCreateCurrentLineItemSubrecord(sublist, fldname)
•
nlapiEditCurrentLineItemSubrecord(sublist, fldname)
•
nlapiRemoveCurrentLineItemSubrecord(sublist, fldname)
•
nlapiViewCurrentLineItemSubrecord(sublist, fldname)
•
nlapiViewLineItemSubrecord(sublist, fldname, linenum)
Note: nlapiCreateCurrentLineItemSubrecord(...) and
nlapiEditCurrentLineItemSubrecord(...) are not currently supported in client scripts.
If you are loading the parent record using SuiteScript, and you want to create/access a
subrecord from a sublist, you will use these methods on the nlobjRecord object:
•
createCurrentLineItemSubrecord(sublist, fldname)
•
editCurrentLineItemSubrecord(sublist, fldname)
•
removeCurrentLineItemSubrecord(sublist, fldname)
•
viewCurrentLineItemSubrecord(sublist, fldname)
•
viewLineItemSubrecord(sublist, fldname, linenum)
This figure shows that the subrecord for the Lot Bin Item is being edited.
SuiteScript Developer and Reference Guide
Working with Records and Subrecords in SuiteScript
Working with Subrecords in SuiteScript
104
For code samples showing how “sublist field” subrecord APIs are used, see Using SuiteScript
with Advanced Bin / Numbered Inventory Management.
Related Topics
•
•
•
What is a Subrecord?
Creating and Accessing Subrecords from a Body Field
Guidelines for Working with Subrecords in SuiteScript
Setting Values on Subrecord Sublists
When working with sublists on subrecords (see figure), you will use the following Sublist APIs
on the nlobjRecord object:
•
selectNewLineItem(group) - use if creating a new sublist line
SuiteScript Developer and Reference Guide
Working with Records and Subrecords in SuiteScript
Working with Subrecords in SuiteScript
•
selectLineItem(group, linenum) - use if selecting an existing line on the sublist
•
setCurrentLineItemValue(group, name, value) - use to set the values on a line
•
commitLineItem(group) - use to commit the line
105
Important: The nlapiSetLineItemValue(...) and nlobjRecord.setLineItemValue(...) APIs are
NOT supported when scripting a subrecord’s sublist.
The following sample shows how to use Sublist APIs to set values on a subrecord sublist.
var qtytobuild = 2;
var obj = nlapiCreateRecord('assemblybuild', {recordmode:'dynamic'});
obj.setFieldValue('subsidiary', 3 );
obj.setFieldValue('item', 174);
obj.setFieldValue('quantity', qtytobuild);
obj.setFieldValue('location', 2);
var bodySubRecord = obj.createSubrecord('inventorydetail');
var ctr;
for(ctr = 1; ctr <= qtytobuild ; ctr ++)
{
//Here we are selecting a new line on the Inventory Assignment sublist on the subrecord
bodySubRecord.selectNewLineItem('inventoryassignment');
bodySubRecord.setCurrentLineItemValue('inventoryassignment', 'newinventorynumber',
'amsh_' + ctr);
bodySubRecord.setCurrentLineItemValue('inventoryassignment', 'quantity', 1);
bodySubRecord.setCurrentLineItemValue('inventoryassignment', 'binnumber', 3);
bodySubRecord.commitLineItem('inventoryassignment');
}
bodySubRecord.commit();
SuiteScript Developer and Reference Guide
Working with Records and Subrecords in SuiteScript
Working with Subrecords in SuiteScript
106
//Here we are selecting and editing an existing line on the Components sublist
//on the parent record. Note that when working with the Assembly Build record only,
//the internal ID for the Inventory Details field on the Components sublist is
// 'componentinventorydetail'. This is because the Assembly Build record already contains
//an Inventory Details (inventorydetails) body field.
obj.selectLineItem('component', 1);
obj.setCurrentLineItemValue('component', 'quantity', qtytobuild);
var compSubRecord = obj.createCurrentLineItemSubrecord('component',
'componentinventorydetail');
//Here we are selecting and editing a new line on the Inventory Assignment sublist on
//the subrecord.
compSubRecord.selectNewLineItem('inventoryassignment');
compSubRecord.setCurrentLineItemValue('inventoryassignment', 'binnumber', 3);
compSubRecord.setCurrentLineItemValue('inventoryassignment', 'quantity', 2);
compSubRecord.commitLineItem('inventoryassignment');
compSubRecord.commit();
obj.commitLineItem('component');
var id = nlapiSubmitRecord(obj);
obj = nlapiLoadRecord('assemblybuild', id);
var subrecord = obj.viewSubrecord('inventorydetail');
subrecord.selectLineItem('inventoryassignment', 1);
var str;
str = subrecord.getCurrentLineItemValue('inventoryassignment', 'newinventorynumber');
if (str!= 2)
{
}
For additional code samples showing how to use Sublist APIs in the context of a subrecord, see
Using SuiteScript with Advanced Bin / Numbered Inventory Management.
Related Topics
•
•
•
What is a Subrecord?
Saving Subrecords Using SuiteScript
Guidelines for Working with Subrecords in SuiteScript
Saving Subrecords Using SuiteScript
To save a subrecord to a parent record you will call nlobjSubrecord.commit(). You must then
save the subrecord’s parent record using nlapiSubmitRecord(record, doSourcing,
ignoreMandatoryFields). If you do not commit both the subrecord and the parent record, all
changes to the subrecord are lost.
SuiteScript Developer and Reference Guide
Working with Records and Subrecords in SuiteScript
Working with Subrecords in SuiteScript
107
In the following sample an Inventory Detail subrecord is edited from the ‘inventorydetail’ field
on the Items sublist. Next, values are set on the ‘inventoryassignment’ sublist. This is the sublist
on the Inventory Detail subrecord. Once this sublist is edited, you must call
commitLineItem(...) to commit the changes to this sublist.
Next, you call commit() on the nlobjSubrecord object to commit the subrecord to the parent
record. After that, you must call commitLineItem(...) again, but this time on the Items sublist of
the parent record. This is necessary because, ultimately what you are doing in this script is
updating the Items sublist.
Finally, you must call nlapiSubmitRecord(...) on the Purchase Order record. This is the parent
record and must be saved for all changes in the script to be committed to the database.
var record2= nlapiLoadRecord('purchaseorder', id, {recordmode: 'dynamic'});
record2.selectLineItem('item', 1);
record2.setCurrentLineItemValue('item', 'quantity', 2);
var subrecord2= record2.editCurrentLineItemSubrecord('item', 'inventorydetail');
subrecord2.selectLineItem('inventoryassignment', 1);
subrecord2.setCurrentLineItemValue('inventoryassignment', 'inventorynumber', 'working123');
subrecord2.selectNewLineItem('inventoryassignment');
subrecord2.setCurrentLineItemValue('inventoryassignment', 'inventorynumber',
'2ndlineinventorynumber');
subrecord2.setCurrentLineItemValue('inventoryassignment', 'quantity', '1');
subrecord2.commitLineItem('inventoryassignment');
subrecord2.commit();
record2.commitLineItem('item');
var id = nlapiSubmitRecord(record2);
Related Topics
•
•
•
What is a Subrecord?
Setting Values on Subrecord Sublists
Guidelines for Working with Subrecords in SuiteScript
Guidelines for Working with Subrecords in SuiteScript
The following are guidelines you must following when working with subrecords.
•
In SuiteScript, you must first create or load a parent record before you can create/
access a subrecord. You can create/load the parent record in either standard mode or
dynamic mode.
SuiteScript Developer and Reference Guide
Working with Records and Subrecords in SuiteScript
Working with Subrecords in SuiteScript
108
•
You cannot create or edit a subrecord in a beforeLoad user event script. You must use a
pageInit client script if you want to create/edit a subrecord before the end user has
access to the page.
•
If you attempt to edit or view a subrecord that does not exist, null will be returned.
•
In a client script attached or deployed to the parent record, you cannot create or edit a
subrecord; you can only view or delete subrecords.
•
There is no automatic client-side validation on a subrecord when a field is changed on
the parent record. For example, if a user changes the quantity of an item on an item
line, there is no detection of a quantity mismatch between the item line and its
Inventory Detail. Note, however, validation can be implemented programmatically
using a validateLine() call.
•
To save a subrecord, you must commit both the subrecord, the line the subrecords
appears on (if accessing a subrecord through a sublist), and the parent record. See
Saving Subrecords Using SuiteScript for complete details.
•
If you call one of the Subrecord APIs on a non-subrecord field, an error is thrown.
•
The following sublist and body field APIs are not supported on subrecords:
• nlapiGetLineItemValue(type, fldname, linenum)
• nlapiGetLineItemText(type, fldnam, linenum)
• nlapiFindLineItemValue(type, fldnam, val)
• nlapiGetCurrentLineItemText(type, fldnam)
• nlapiGetCurrentLineItemValue(type, fldnam)
• nlapiGetFieldValue()
• nlapiGetFieldText()
•
When using the Assembly Build record as a parent record, be aware that this record
has two inventorydetail fields: one on the body of the record and the other as a field on
the Components sublist. When creating/assessing a subrecord from the body field, use
inventorydetail as the internal ID for the fldname parameter. When creating/
accessing a subrecord from the sublist field on the Components sublist, use
componentinventorydetail as the internal ID for the fldname parameter. To see an
example, see the code sample provided in Setting Values on Subrecord Sublists.
Related Topics
•
•
•
•
What is a Subrecord?
Creating and Accessing Subrecords from a Body Field
Creating and Accessing Subrecords from a Sublist Field
Setting Values on Subrecord Sublists
SuiteScript Developer and Reference Guide
Working with Records and Subrecords in SuiteScript
Working with Records in Dynamic Mode
109
Working with Records in Dynamic Mode
When creating, copying, loading, or transforming records in SuiteScript, you have the choice of
working with records in dynamic mode. When scripting in dynamic mode, you are working
with a record in a way that emulates the behaviors of the UI. For example, in the UI, if you
create a new sales order, select a custom form, and specify a customer, various field values
throughout the new record are sourced (see figure).
When you programmatically create a new sales order in dynamic mode, all of the same
sourcing behaviors that occur in the UI also occur in your script as each line is executed. As a
result, you can obtain sourced, validated, and recalculated field values in “real-time” without
first having to submit the record.
When working with records in standard mode, you must submit and then load the record to
obtain these same values. In standard mode, all business logic is executed on only after data is
submitted.
Note: User event script that are triggered through the UI will, by default, execute in the
standard mode. They will not execute in dynamic mode.
Do I have to enable dynamic mode?
You must use the optional initializeValues parameter in the following APIs to control whether
a record is processed in dynamic mode.
•
nlapiCopyRecord(type, id, initializeValues)
•
nlapiCreateRecord(type, initializeValues)
•
nlapiLoadRecord(type, id, initializeValues)
SuiteScript Developer and Reference Guide
Working with Records and Subrecords in SuiteScript
Working with Records in Dynamic Mode
110
In nlapiTransformRecord(type, id, transformType, transformValues), use the transformValues
parameter to control whether one record will be transformed into another in dynamic mode.
Important: 1. If you provide no value for the initializeValues parameter, records will copy,
create, load, and transform in the standard mode of execution, where
sourcing, validation, and recalculations occur only after a record is
submitted.
2. Dynamic processing of a record is not currently supported in user event
scripts. For example, even if you were to call nlapiCreateRecord('salesorder',
{recordmode: 'dynamic'}) in a user event script, the fields in the new sales
order will not be processed dynamically.
The initializeValues parameter is an Object that can contain an array of name/value pairs of
defaults to be used during record initialization. To initialize a record in dynamic mode, you set
the recordmode initialization type to dynamic. For example:
•
var record = nlapiCopyRecord('salesorder', 55, {recordmode: 'dynamic'});
•
var record = nlapiCreateRecord'salesorder', {recordmode: 'dynamic'});
•
var record = nlapiLoadRecord('salesorder', 111, {recordmode: 'dynamic'});
•
var transformRecord = nlapiTransformRecord('salesorder', 111, 'itemfulfillment',
{recordmode: 'dynamic'});
Note: For a list of additional initialization types that can be specified for the
initializeValues parameter, see Record Initialization Defaults in the NetSuite Help
Center. Note that you do not need to run scripts in dynamic mode to use these
other initialization types.
Is dynamic mode better than standard mode?
Yes and no. There are obvious benefits to getting / setting field values in real-time. When
working with records in dynamic mode, you do not need to submit the record for all business
logic to be executed. In dynamic mode you can get field values and write logic around these
values without having to submit a record and wonder what will be returned when the record is
reloaded.
Note, however, when scripting in dynamic mode, the order in which you set field values
matters. For some developers, this aspect might feel constraining. It is likely that scripting in
dynamic mode will require you to refer back to the UI often. For example, on an invoice in the
UI, you would not set the Terms field before setting the Customer field (see figure). The reason
is that as soon as you set the Customer field, the value of Terms will be overridden. On an
invoice, the value of Terms is sourced from the terms specified on the Customer record. The
same behavior will happen in dynamic scripting. In your scripts, if you do not correctly set
field values in the order that they are sourced in the UI, some of the values you set could be
overridden.
SuiteScript Developer and Reference Guide
Working with Records and Subrecords in SuiteScript
Working with Records in Dynamic Mode
111
In non-dynamic mode, you do not have to worry about the order in which you set field values.
For some developers, this fact alone will make scripting in non-dynamic mode preferable.
Can I change existing code to run in dynamic mode?
Yes. If you decide to convert an existing script to one that runs dynamically, you will need to do
the following:
1.
Set the new initializeValues parameter to {recordmode: 'dynamic'} - for example:
var recDynamic = nlapiCreateRecord('salesorder', {recordmode: 'dynamic'});
2.
Ensure that the field values you have set in your scripts are set in the correct order.
As the second example Field Ordering shows, if you do not set your fields in the right
order, you may end up overriding certain field values.
3.
Update any code that uses either the nlapiSetLineItemValue(...) function or the
nlobjRecord.setLineItemValue(...) method.
Neither of these APIs will execute in dynamic mode. For details, see Working with
Sublists in Dynamic Mode and Client SuiteScript in the NetSuite Help Center.
Standard vs. Dynamic Mode Code Samples
This section uses code snippets to further demonstrate some of the differences between
scripting in standard mode and dynamic mode. The areas covered are field sourcing, field
ordering, and field calculation.
Sourcing
Example 1: Standard mode (sourcing does not occur real-time)
This sample shows a script executing in standard (non-dynamic) mode. In standard mode, no
real-time sourcing occurs. You cannot get values that you have not already set in your script.
SuiteScript Developer and Reference Guide
Working with Records and Subrecords in SuiteScript
Working with Records in Dynamic Mode
112
// Create a new sales order and set the customer
var record = nlapiCreateRecord('salesorder');
record.setFieldValue('entity', 343);
// Try to get the value of salesrep. Note that null is returned because the value
// of salesrep is not sourced as you step through the code
var sr = record.getFieldValue('salesrep');
Example 2: Dynamic mode (sourcing occurs as each line executes)
This sample shows the same script, but running in dynamic mode. In this script, the value of
salesrep is sourced after the entity is set. Ultimately this allows you to write fewer lines of code,
as you are able to get many field values without first having to set them.
// Create a new sales order and set the customer
var record = nlapiCreateRecord('salesorder', {recordmode: 'dynamic'});
record.setFieldValue('entity', 343);
// Get the value of salesrep. Note that John Smith will be returned. The value of the salesrep
// field is sourced from the salesrep value specified on the customer record
var sr = record.getFieldValue('salesrep');
Field Ordering
Example 1: Standard mode (field ordering does not matter)
This sample shows that the order in which you set values does not matter in standard mode. In
this sample, you can set a sales rep before setting the entity, even though in the UI there is a
sourcing relationship between these two fields. In the UI, once you set the entity, the value of
salesrep is automatically sourced. In standard mode, field sourcing relationships are not
respected.
// Create a sales order. First set salesrep, then set the customer (entity). When the
// record is submitted, salesrep remains as 88, the internal ID for sales rep Bud Johnson.
var record = nlapiCreateRecord('salesorder');
record.setFieldValue('salesrep', 88);
record.setFieldValue('entity', 343);
Example 2: Dynamic mode (field ordering matters)
In dynamic mode, if you write the same script, the value of salesrep will be overridden when
the next line of code is executed. In this example, when you submit the record the value of
salesrep will change from 88 to 333 (the value of the salesrep specified on the customer record).
var record = nlapiCreateRecord('salesorder', {recordmode: 'dynamic'});
record.setFieldValue('salesrep', 88);
record.setFieldValue('entity', 343);
In dynamic mode, if you want salesrep to remain as 88, you must write:
SuiteScript Developer and Reference Guide
Working with Records and Subrecords in SuiteScript
Working with Records in Dynamic Mode
var record = nlapiCreateRecord('salesorder', {recordmode: 'dynamic'});
record.setFieldValue('entity', 343);
record.setFieldValue('salesrep', 88);
SuiteScript Developer and Reference Guide
113
Working with Records and Subrecords in SuiteScript
Working with Records in Dynamic Mode
114
Field Calculation
Example 1: Standard mode (field totals are not calculated in real-time)
In this beforeSubmit user event script, if a line is added to a sales order, the totals are not
recalculated until you submit the line. The following sample shows a new line being added in a
beforeSubmit script, however, the total is not recalculated.
function beforesubmit(type)
{
var record = nlapiGetNewRecord();
record.selectNewLineItem('item');
record.setCurrentLineItemValue('item', 'item', 441);
record.setCurrentLineItemValue('item', 'quantity', '2');
record.commitLineItem('item');
}
Example 2: Dynamic mode (field totals are calculated real-time)
In dynamic mode, you can add a line to a sublist (the Items sublist in this example) and not
worry about recalculating the amount and subtotal fields. Even before the record is submitted,
you can get accurate data in a beforeSubmit event.
function beforesubmit(type)
{
var record = nlapiGetNewRecord();
record.selectNewLineItem('item');
record.setCurrentLineItemValue('item', 'item', 441);
record.setCurrentLineItemValue('item', 'quantity', '2');
record.commitLineItem('item');
}
Client Scripting and Dynamic Mode
Generally speaking, the concept of dynamic mode does not apply to client scripting. The only
exception is on the pageInit client event. Scripting in a “current record context” is always in
dynamic mode.
Note that client (remote object) scripting does not support dynamic scripting. In a client script,
if you attempt to copy, create, load, or transform a remote record object (an object on the
NetSuite server), you will not be able to work with the record in dynamic mode.
The following is an example of a client (remote object) script. On the saveRecord client event,
an estimate record is created. If you attempt to create the record in dynamic mode, an error is
thrown. For example:
function onSave()
{
var rec = nlapiCreateRecord('estimate', {recordmode: 'dynamic'}); // this will not work
rec.setFieldValue('entity','846');
rec.insertLineItem('item',1);
rec.setLineItemValue('item','item', 1, '30');
rec.setLineItemValue('item','quantity', 1, '500');
var id = nlapiSubmitRecord(rec, true);
return true;
}
SuiteScript Developer and Reference Guide
Working with Records and Subrecords in SuiteScript
Working with Records in Dynamic Mode
SuiteScript Developer and Reference Guide
115
Chapter 13 Working with Fields
The following topics are covered in this section. If you are new to SuiteScript, they should be
read in order:
•
Working with Fields Overview
•
Referencing Fields in SuiteScript
•
Working with Custom Fields in SuiteScript
Working with Fields Overview
The SuiteScript API includes several Field APIs you can use to set and get values for built-in
NetSuite standard fields, as well as for custom fields. Standard fields are those that come with
NetSuite. Custom fields are those that have been created by NetSuite users to customize their
accounts. Custom fields are created using SuiteBuilder point-and-click customization tools.
Note: For information on working with nlobjField objects that you can add dynamically to
NetSuite records at runtime, see nlobjField in the NetSuite Help Center. These are
the only type of fields you can programmatically add to a record. There are no
SuiteScript APIs available for creating custom fields that are akin to the kinds of
custom field created using SuiteBuilder point-and-click functionality.
The following figure shows a combination of standard and custom fields appearing in the body
sections of a record. The body sections of a record include the top (header) portion and nonsublist-fields that sometimes appear on the top area of a subtab.
Body fields that appear under a subtab should not be confused with fields that appear on a
sublist. Fields that appear on a sublist are typically referred to as “line items” or sublist fields
and are accessed using Sublist APIs.
On the figure below:
1.
Body fields - can be a mix of standard and custom fields.
2.
Body fields - directly below a subtab, can be a mix of standard and custom fields
3.
Sublist fields - not to be confused with body fields. See Working with Subtabs and
Sublists for more information.
SuiteScript Developer and Reference Guide
Working with Fields
Referencing Fields in SuiteScript
117
Note: Getting and setting fields and sublists should be accomplished using SuiteScript
APIs instead of directly accessing the DOM. SuiteScript APIs provide a consistent
coding interface across NetSuite versions, hence the scripts that use them are fully
supported.
Referencing Fields in SuiteScript
Many SuiteScript APIs allow you to get, set, or search for the value of a particular field.
Whether you are referencing a standard field or a custom field, when you reference the field in
SuiteScript, you will use the field’s internal ID. To obtain field internal IDs, see How do I find a
field’s internal ID? in the NetSuite Help Center.
Important: Be aware that not every field that appears in your NetSuite account officially
supports SuiteScript. To write scripts that include only supported, officially
SuiteScript Developer and Reference Guide
Working with Fields
Working with Custom Fields in SuiteScript
118
tested NetSuite fields, it is recommended you refer to the SuiteScript Records
Browser to verify a field’s official support. See SuiteScript Reference for more
details.
Getting Field Values in SuiteScript
If you are using SuiteScript to process record data in standard mode (as opposed to dynamic
mode), be aware of the following when using “getter” APIs to get the value of a field:
Note: If you are not familiar with standard mode and dynamic mode scripting, see
Working with Records and Subrecords in SuiteScript in the NetSuite Help Center.
To check if a field has a non-empty value, NetSuite recommends that you write code which
checks for null and empty when using any of the following APIs:
•
nlapiGetFieldValue(fldnam)
•
nlapiGetLineItemValue(type, fldnam, linenum)
•
nlobjRecord.getFieldValue(name)
•
nlobjRecord.getLineItemValue(group, name, linenum)
Important: Note that this inconsistency in field return values does NOT exist when
scripting records in dynamic mode.
The following snippet provides an example of how you might want to write your code to catch
any null vs. empty string return value inconsistencies:
if (value)
{
// handle case where value is not empty
}
-orif (!value)
// handle case where value is empty (or null)
}
Working with Custom Fields in SuiteScript
You can use SuiteScript APIs to get, set, and search the values of custom fields that have been
created using SuiteBuilder. Note, however, you can only set the value of custom fields that have
a stored value. This follows the behavior of the UI.
SuiteScript Developer and Reference Guide
Working with Fields
Working with Custom Fields in SuiteScript
119
The following figure shows a custom entity field. The field’s UI label is Contact Source and its
internal ID is custentity11. In this figure, the Store Value check box is selected, which means
that you can use SuiteScript to get and set the value of this custom entity field.
When a custom field does not contain a stored value (the Store Value check box is not selected),
you can reference this field in a SuiteScript search to return the current value of the field.
However, non-stored custom fields are considered to have dynamic values, so in a search, the
value of a non-stored custom field might be 10 one day and 12 the next day when the same
search is executed.
Note: If you are not familiar with creating custom fields in NetSuite, see Custom Fields in
the NetSuite Help Center.
Providing Internal IDs for Custom Fields
If you are using SuiteBuilder to create a custom field, and you plan to reference the field in your
scripts, NetSuite recommends you create an internal ID that includes an underscore ( _ ) after
the custom field’s prefix. You should then add a meaningful name after the underscore. This
will enhance readability in your SuiteScript code.
For example, if you are using SuiteBuilder to create a custom transaction body field with the UI
label Contact Fax, the field’s internal ID should be something equivalent to _contactfax. Note
that you do not need to write the custom field’s prefix in the ID field (see figure below). Once
the custom field definition is saved, the prefix for that custom field type is automatically added
to the ID. When the custom transaction body field (below) is saved, its internal ID will appear
as custbody_contactfax. This is the ID you will reference in your scripts.
SuiteScript Developer and Reference Guide
Working with Fields
Working with Custom Fields in SuiteScript
120
Understanding Custom Field Prefixes
As a reference, the following table provides the prefixes for each custom field type. You do not
need to type these prefixes when you assign an internal ID to a custom field. This table is
provided only for convenience to SuiteScript developers who may be working with different
custom field types and are not sure how to identify the field type using the prefix.
Custom field type
Custom field prefix
Entity field
custentity
Item field
custitem
CRM field
custevent
Transaction body field
custbody
Transaction column field
custcol
Transaction item options
custcol
Item number fields
custitemnumber
Other custom fields
custrecord
SuiteScript Developer and Reference Guide
Chapter 14 Working with Subtabs and
Sublists
Subtabs and Sublists Overview
When using SuiteScript on subtabs and sublists, you should be aware of the following:
1.
The distinction between subtabs and sublists (see Subtabs and Sublists - What’s the
Difference?)
2.
Sublist types (see Sublist Types)
3.
Adding subtabs with SuiteScript (Adding Subtabs with SuiteScript)
4.
Adding sublists with SuiteScript (Adding Sublists with SuiteScript)
5.
Manipulating sublist with SuiteScript (Working with Sublist Line Items)
6.
Sublist scripting when a record is in dynamic mode (Working with Sublists in
Dynamic Mode and Client SuiteScript)
Important: For a list of all sublists that support SuiteScript, see Scriptable Sublists in the
NetSuite Help Center. To see all sublist-related APIs, see Sublist APIs.
Subtabs and Sublists - What’s the Difference?
Subtabs and sublists both look like tabs in the UI (see figure). However, functionally they serve
very different purposes. See these sections to learn about the differences between subtabs and
sublists:
•
What is a Subtab?
•
What is a Sublist?
SuiteScript Developer and Reference Guide
Working with Subtabs and Sublists
Subtabs and Sublists - What’s the Difference?
SuiteScript Developer and Reference Guide
122
Working with Subtabs and Sublists
Subtabs and Sublists - What’s the Difference?
123
What is a Subtab?
Subtabs contain body fields, other subtabs, and sublists. Unlike sublists, subtabs do not contain
references to other records. Subtabs are used mainly for organizational purposes.
The figure below shows the Sales subtab on a Customer record. Notice that the Sales tab
contains body fields that hold data specific to the Customer. The primary purpose of the Sales
subtab is to organize all of the sales-related sublists (Sales Team, Opportunities, Transactions,
and so on).
To compare what you see on the Sales subtab, the Sales Team sublist contains data that link to
other records—in this case, the employee records for the sales people associated with this
customer (see figure).
The next figure shows the Financial subtab, also on the Customer record. Notice that the
information on this subtab is simply additional field-level information related to this particular
customer. None of the information applies to or references data that exists on another record.
SuiteScript Developer and Reference Guide
Working with Subtabs and Sublists
Subtabs and Sublists - What’s the Difference?
124
In SuiteScript you can access fields that appear on a subtab using Field APIs. Field APIs are also
used on regular body fields that appear on the top portion of records.
Related Topics
•
•
•
Adding Subtabs with SuiteScript
Subtabs and Sublists - What’s the Difference?
Sublist APIs
What is a Sublist?
Sublists contain a list of references to other records. Note that the list of record references are
referred to as line items. Within NetSuite there are four types of sublists: editor, inline editor,
list, and static list (see Sublist Types for details on each type).
Important: Static list sublists do not support SuiteScript. For a list of all editor, inline
editor, and list sublists that support SuiteScript, see Scriptable Sublists in the
NetSuite Help Center.
The following figure shows the Item Pricing Sublist on the Customer record. This is an inline
editor sublist that appears on a subtab, in this case the Financial subtab. Whereas the field-level
data captured on the Financial subtab applies specifically to this customer, the data on the Item
Pricing sublist references data contained on other records.
SuiteScript Developer and Reference Guide
Working with Subtabs and Sublists
Sublist Types
125
In the UI, you can add/insert/remove lines items to this sublist using the Add, Insert, and
Remove buttons. In SuiteScript, you can perform the same actions using Sublist APIs such as
nlapiInsertLineItem(type, line) and nlapiRemoveLineItem(type, line).
Related Topics
•
•
•
Sublist Types
Adding Sublists with SuiteScript
Subtabs and Sublists - What’s the Difference?
Sublist Types
There are four types of sublists in NetSuite:
•
Editor Sublists
•
Inline Editor Sublists
•
List Sublists
•
Static List Sublists
SuiteScript Developer and Reference Guide
Working with Subtabs and Sublists
Sublist Types
126
Important: Static list sublists do not support SuiteScript. Scripts written against static list
sublists will either not run or will return a system error. All other sublist types
support both client and server SuiteScript.
Note: If you are building your own custom form and are adding a sublist object to that
form through nlobjForm.addSubList(name, type, label, tab), you can set the sublist
type to any of the four sublist types. You can then write scripts against your custom
sublist. Note that sorting (in the UI) is not supported on static sublists created using
the addSubList(...) method if the row count exceeds 25.
Related Topics
•
•
Adding Sublists with SuiteScript
Subtabs and Sublists - What’s the Difference?
Editor Sublists
The editor sublist allows users to insert/edit/remove lines dynamically prior to submitting the
form. On an editor sublist, editing sublists lines (referred to as line items) is done in fields
directly above the line items. In the UI, changes you make when you add/edit/remove lines are
not committed to the database until you save the entire record. Similarly, in SuiteScript add/
edit/remove functions provided in Sublist APIs are not persisted in the NetSuite database until
the change is committed to the NetSuite database.
When writing client scripts, you must call nlapiCommitLineItem(type) after each sublist line
change. Otherwise your changes will not be committed to NetSuite.
When writing server scripts, you must call nlobjRecord.commitLineItem(group) to commit
sublist updates. Note that you must do this in addition to calling nlapiSubmitRecord(record,
doSourcing, ignoreMandatoryFields), which commits the entire record object to the database.
Note: Server scripts are considered to be Suitelets, user event scripts, scheduled scripts,
and portlet scripts. If you are not familiar with the differences between client and
server scripting.
The following figure shows the Address Sublist, which is currently the only editor sublist in
NetSuite that supports SuiteScript. In this figure, two line items exist on the Address sublist.
SuiteScript Developer and Reference Guide
Working with Subtabs and Sublists
Sublist Types
127
Related Topics
•
•
•
•
Sublist Types
Subtabs and Sublists - What’s the Difference?
Working with Sublist Line Items
Scriptable Sublists
Inline Editor Sublists
Inline editor sublists are similar to Editor Sublists in these ways:
•
you can add/edit/remove lines dynamically prior to submitting the form
•
you can add/edit/remove lines using the UI or SuiteScript
•
when writing client scripts, you must call nlapiCommitLineItem(type) after each
sublist line change. Otherwise your changes will not be committed to NetSuite.
When writing server scripts, you must call nlobjRecord.commitLineItem(group) to
commit sublist updates. Note that you must do this in addition to calling
nlapiSubmitRecord(record, doSourcing, ignoreMandatoryFields), which commits the
entire record object to the database.
Note: Server scripts are considered to be Suitelets, user event scripts, scheduled scripts,
and portlet scripts.
SuiteScript Developer and Reference Guide
Working with Subtabs and Sublists
Sublist Types
128
The only difference between an inline editor sublist and an editor sublist is UI appearance.
Inline editor sublists do not contain a line item edit area directly above the line items. The line
items on an inline editor sublist are edited “inline” directly on the lines on which they appear.
The following figure shows the Items Sublist on the Estimate record. The field-level data that
appears directly above the line items are not used for adding, editing, or removing line items
that appear below it.
In SuiteScript, fields above the line items are accessed using Field APIs. Sublist line items are
accessed using Sublist APIs.
The next figure shows the Sales Team Sublist. This sublist appears on the Sales subtab of a
Customer record. Any changes you make to the sublist line items are made inline.
Note: To see the Sales Team sublist you must have the Team Selling feature enabled.
SuiteScript Developer and Reference Guide
Working with Subtabs and Sublists
Sublist Types
129
Related Topics
•
•
•
•
Sublist Types
Subtabs and Sublists - What’s the Difference?
Working with Sublist Line Items
Scriptable Sublists
List Sublists
Unlike Editor Sublists and Inline Editor Sublists, list sublists are not dynamic. The number of
line items are fixed and cannot be removed or added on-the-fly though UI customziation or
through SuiteScript.
Changes you make to existing line items on list sublists are submitted along with the main
record and do not take effect until after the record has been saved. Note that even though you
cannot add or remove lines on a list sublist, you can use the UI to change values or SuiteScript
to get/set values on lines that currently exist.
In SuiteScript you would not use Sublist APIs such as nlapiSelectNewLineItem(type),
nlapiInsertLineItem(type, line), or nlapiRemoveLineItem(type, line) to add or remove line
items. Neither will you use the nlapiCommitLineItem(type) or nlapiRefreshLineItems(type)
APIs in the context of a list sublist.
Also note that in SuiteScript, client lineInit and validateLine functions will not execute, since
they have no context in a list sublist. (For information on client event functions, see Client
Event Functions.)
The following figure shows the Subscriptions sublist on the Customer record. Although you
cannot add/remove lines, you can edit the lines that are there (in this case, you can select or deselect the check boxes).
The next figure shows the Apply sublist on the Accept Customer Payments record. Similar to
the Subscriptions sublist, you can manipulate the line items that appear, but you cannot
dynamically add or remove additional lines.
SuiteScript Developer and Reference Guide
Working with Subtabs and Sublists
Sublist Types
130
The last figure provides another example of a list sublist—the Billable Expenses Sublist sublist
on the Invoice record. Again, you can only manipulate the line item data provided. You cannot
dynamically add or remove items. Any changes you make to the data on this sublist will not be
committed to the database until you call nlapiSubmitRecord(record, doSourcing,
ignoreMandatoryFields) in your script.
Related Topics
•
•
•
•
Sublist Types
Working with Sublist Line Items
Subtabs and Sublists - What’s the Difference?
Scriptable Sublists
Static List Sublists
Important: SuiteScript is not currently supported on static list sublists.
Static list sublists, also referred to as read-only sublists, contain static data. These sublists are
typically used for displaying associated records/data rather than child records/data.
Technically, this means that the data on a static list sublist is not actually part of the record (and
SuiteScript Developer and Reference Guide
Working with Subtabs and Sublists
Sublist Types
131
therefore not accessible to SuiteScript), and is not submitted with the record when the record is
saved.
The following figure shows the System Notes sublist, which is accessed through the System
Information subtab on many records. Note that all data in the System Notes sublist is read-only
and is not even settable through the UI.
The next figure shows the Files sublist, which is accessed from the Communications subtab on
many records. In this case you can attach/detach a file to this sublist, but the file is maintained
entirely as a separate document. The data in this document (in this case a .txt file), is not
considered to be part of Customer record, which can be manipulated through the UI or
through SuiteScript.
The last figure shows the User Notes sublist, also accessed through the Communication subtab.
Although you can add a new Note to this sublist, the data you define on the actual Note record
is not available to this Customer record. Therefore, the User Notes sublist is considered to hold
static/read-only data.
SuiteScript Developer and Reference Guide
Working with Subtabs and Sublists
Sublist Types
132
Note: In some cases you can use search joins in SuiteScript to search the data on a static
list sublist (for example, data related to notes, contacts, messages, or files that
appear on a particular record). In the previous example, you could use the file
search join to search for all files associated with this particular Customer record.
Related Topics
•
•
•
•
Sublist Types
Subtabs and Sublists - What’s the Difference?
Working with Sublist Line Items
Scriptable Sublists
SuiteScript Developer and Reference Guide
Working with Subtabs and Sublists
Adding Subtabs with SuiteScript
133
Adding Subtabs with SuiteScript
You can add subtabs to custom forms through UI point-and-click customization and through
SuiteScript. In scripting, you must use either of the following two nlobjForm methods,
depending on your use case:
•
addTab(name, label) — to add a top-level tab
•
addSubTab(name, label, tab) — to create a nested subtab
Important: You must define two subtabs for subtab UI labels to appear. If you define
only one subtab in your script, the UI label you provide for the subtab will not
actually appear in the UI.
Both methods return an nlobjTab object, through which you can further define the properties
of your tab.
Note: To add subtabs using UI customization, in the NetSuite Help Center, see Adding
Subtabs to a Custom Record and Configuring Subtabs for Custom Entry and
Transaction Forms.
SuiteScript Developer and Reference Guide
Working with Subtabs and Sublists
Adding Subtabs with SuiteScript
134
Example
The following example shows how to use SuiteScript to add subtabs to a custom NetSuite form.
This script is a beforeLoad user event script that is deployed to the Sales Order. Note that if you
add only one subtab, the UI label you define for the subtab will not appear in the UI. You must
define two subtabs for subtab UI labels to appear.
When you are adding UI Objects to an existing form, be sure to prefix the internal IDs for all
elements with custpage, for example 'custpage_sample_tab' and 'custpage_field_email' (see
sample). In the sample below, the nlobjTab and nlobjField UI objects are being added to a
custom transaction form on a Sales Order. (See Custom Transaction Forms in the NetSuite
Help Center if you are not familar with this form type.)
Also note that element internal IDs must be in all lowercase.
//Define the user event beforeLoad function
function tabsToSalesOrder(type, form)
{
//Define the values of the beforeLoad type argument
if (type == 'edit' || type == 'view')
{
//Add a new tab to the form
var sampleTab = form.addTab('custpage_sample_tab', 'Sample Tab');
//Add a field to the new tab
var newFieldEmail = form.addField('custpage_field_email', 'email', 'Alt Email', null,
'custpage_sample_tab');
//Add a second field to the new tab
var newFieldText = form.addField('custpage_field_text', 'textarea', 'Details', null,
'custpage_sample_tab');
//Add a subtab to the first tab
var sampleSubTab = form.addSubTab('custpage_sample_subtab', 'Sample Subtab',
'custpage_sample_tab');
//Add a select field to the subtab
var newSubField = form.addField('custpage_sample_field', 'select', 'My Customers', 'customer',
'custpage_sample_subtab');
//Add a second subtab to the first tab
var sampleSubTab = form.addSubTab('custpage_sample_subtab2', 'Second Sample Subtab',
'custpage_sample_tab');
//Add a field to the second subtab
var newSubField = form.addField('custpage_sample_field2', 'select', 'My Employees', 'employee',
'custpage_sample_subtab2');
}
}
SuiteScript Developer and Reference Guide
Working with Subtabs and Sublists
Adding Sublists with SuiteScript
135
Related Topics
•
•
•
Subtabs and Sublists - What’s the Difference?
Adding Sublists with SuiteScript
Working with Sublist Line Items
Adding Sublists with SuiteScript
You can add sublists to custom forms through UI point-and-click customization and through
SuiteScript. In scripting, you must use the nlobjForm.addSubList(name, type, label, tab)
method to add a sublist. This method returns an nlobjSubList object, through which you can
further define the properties of your sublist.
Important: The internal ID for all custom sublists, subtabs, and fields must be prefixed
with custpage. The rest of the ID name must be in lowercase.
When adding a sublist through scripting you must define:
1.
The custom sublist internal ID.
Example: 'custpage_contacts'
2.
The sublist type you are defining.
Example: 'editor', 'inlineeditor', 'list', or 'staticlist'
3.
The UI label for the sublist.
Example: 'Custom Contacts'
4.
The subtab on which the sublist will appear.
Example: 'general' or 'custpage_mynewsubtab'
Important:
To add sublists through point-and-click customization, see Custom Sublists
in the NetSuite Help Center. When adding a sublist through UI customization,
you are essentially just adding the data from a saved search, the results of
which are only associated with the record. This is the equivalent of a static list
sublist. The results are not considered to be part of the actual record.
SuiteScript Developer and Reference Guide
Working with Subtabs and Sublists
Adding Sublists with SuiteScript
136
Example 1
This sample shows how to create a custom sublist and run a search every time the form is
loaded, edited, or viewed. This is a beforeLoad user event script.
function beforeLoadSublist(type, form)
{
if (type=='edit' || 'view')
{
// add a sublist to the form. Specify an internal ID for the sublist,
//a sublist type, sublist UI label, and the tab the sublist will appear on
var contacts = form.addSubList('custpage_contacts', 'staticlist', 'Custom Contacts', 'general');
// add fields to the sublist
contacts.addField('entityid', 'text', 'Name');
contacts.addField('phone', 'phone', 'Phone');
contacts.addField('email', 'email', 'Email');
// perform a Contact record search. Set search filters and return columns for
// the Contact search
var contactdata = nlapiSearchRecord('contact', null, new
nlobjSearchFilter('company', null, 'anyOf ', nlapiGetRecordId()),
[new nlobjSearchColumn('entityid'), new nlobjSearchColumn('phone'),
new nlobjSearchColumn('email')])
// display the search results on the Custom Contact sublist
contacts.setLineItemValues(contactdata)
}
}
Example 2
The following example shows how to add an inline editor sublist to a Suitelet by instantiating
the nlobForm object (using nlapiCreateForm(title, hideNavbar)) and then calling
nlobjForm.addSubList(name, type, label, tab). Note that because you are not adding field or
sublist elements to an existing NetSuite form, you do not need to prefix the element internal
IDs with custpage.
Script:
function demoSuiteletSublist(request, response)
{
if ( request.getMethod() == 'GET' )
{
// create the form
var form = nlapiCreateForm('Simple Form');
// add fields to the form
var field = form.addField('textfield','text', 'Text');
field.setLayoutType('normal','startcol')
form.addField('datefield','date', 'Date');
form.addField('currencyfield','currency', 'Currency');
form.addField('textareafield','textarea', 'Textarea');
// add a select field and then add the select options that will appear in the dropdown
SuiteScript Developer and Reference Guide
Working with Subtabs and Sublists
Adding Sublists with SuiteScript
137
var select = form.addField('selectfield','select','Custom');
select.addSelectOption('','');
select.addSelectOption('a','Albert');
select.addSelectOption('b','Baron');
select.addSelectOption('c','Chris');
select.addSelectOption('d','Drake');
select.addSelectOption('e','Edgar');
// add a sublist to the form
var sublist = form.addSubList('sublist','inlineeditor','Inline Editor Sublist', 'tab1');
// add fields to the sublist
sublist.addField('sublist1','date', 'Date');
sublist.addField('sublist2','text', 'Name');
sublist.addField('sublist3','currency', 'Currency');
sublist.addField('sublist4','textarea', 'Large Text');
sublist.addField('sublist5','float', 'Float');
// make the Name field unique. Users cannot provide the same value for the Name field.
sublist.setUniqueField('sublist2');
form.addSubmitButton('Submit');
response.writePage( form );
}
}
Note: The nlapiRefreshLineItems(type) API can be used to refresh static list sublists that
have been added using nlobjSubList. This API implements the behavior of the
Refresh button on the UI.
SuiteScript Developer and Reference Guide
Working with Subtabs and Sublists
Working with Sublist Line Items
138
Related Topics
•
•
•
•
•
Subtabs and Sublists - What’s the Difference?
Sublist Types
Adding Sublists with SuiteScript
Working with Sublist Line Items
Scriptable Sublists
Working with Sublist Line Items
NetSuite provides several Sublist APIs to manipulate sublist line items. You can use these APIs
to add or remove line items, update multiple line items when a body field is changed, or
automate the population of line items when certain conditions exist on the form.
When scripting with sublists, you should know if you are scripting an Editor Sublists, Inline
Editor Sublists, or List Sublists sublist. Because List Sublists sublists are not dynamic, you
cannot add/remove lines. You can only get/set values that currently exist on the sublist.
Note, however, whether you are scripting an editor, inline editor, or list sublist, generally you
will specify one or more of the following in the sublist API:
1.
The sublist internal ID
Example: 'salesteam' (appears in the UI as the Sales Team sublist)
2.
The sublist line item (field) ID.
Example: 'isprimary' (appears in the UI as Primary)
3.
The sublist line number — doing so enables you to specify where on the sublist you
want to change, add, or remove a line. Note that first line on a sublist is 1 (not 0).
4.
The value of the line item.
Example: The value can be defined directly in the API or it can be a passed in value
that was defined elsewhere in the script.
Example
// On the Sales Team sublist, the Primary checkbox appearing on
// line 2 will be set to true - or T in the case of check boxes in NetSuite
nlapiSetLineItemValue('salesteam', 'isprimary', 2, 'T');
SuiteScript Developer and Reference Guide
Working with Subtabs and Sublists
Working with Sublist Line Items
139
Related Topics
•
•
•
•
•
Adding and Removing Line Items
Getting and Setting Line Item Values
Sublist Types
Adding Sublists with SuiteScript
Scriptable Sublists
Adding and Removing Line Items
To add/remove sublist line items, follow the general guidelines provided below. The approach
you follow depends on whether you are writing a client script to attach to a record, or a server
script that loads a record from the database. (In this context, scripts that are considered to be
server scripts are Suitelets, user event scripts, and scheduled scripts. Scripts considered to be
client scripts are form- and record-level client scripts.)
Important: This section does not apply to List Sublists. List sublists contain information
that cannot be dynamically added or removed in either the UI or in
SuiteScript. For information on getting/setting existing values on a list
sublist, see Getting and Setting Line Item Values.
Client Scripts
1.
(Optionally) Call nlapiGetLineItemCount(type) to get the number of lines in the
sublist. Alternatively you can call nlapiGetCurrentLineItemIndex(type) to return the
number of the currently select line item.
2.
Call either nlapiInsertLineItem(type, line) or nlapiRemoveLineItem(type, line) to add/
remove a line. In the line argument you will specify the line number of the line you
want to add/remove.
3.
If adding a line:
a.
Call nlapiSelectNewLineItem(type) to select and insert a new line (as you would in
the UI).
b.
Call nlapiSetCurrentLineItemValue(type, fldnam, value, firefieldchanged,
synchronous) to set the value of the line.
SuiteScript Developer and Reference Guide
Working with Subtabs and Sublists
Working with Sublist Line Items
4.
Call nlapiCommitLineItem(type) to commit/save the changes to the sublist.
5.
Perform steps 3 and 4 as many times as necessary to add all line items.
140
Server Scripts
1.
Load the record object — for example using nlapiLoadRecord(type, id,
initializeValues).
2.
(Optionally) Call nlobjRecord.getLineItemCount(group) to get the number of lines in
the sublist.
3.
Call either nlobjRecord.insertLineItem(group, linenum) or
nlobjRecord.removeLineItem(group, linenum) to add/remove a line. In the group
argument specify by line number where to add/remove the line. Line numbering
begins with 1, not 0.
4.
If adding a line:
a.
Call nlobjRecord.selectNewLineItem(group) to select and insert a new line (as you
would in the UI).
b.
Call nlobjRecord.setCurrentLineItemValue(group, name, value) to set the value of
the line.
5.
Call nlobjRecord.commitLineItem(group) to commit/save the changes to the sublist.
6.
Submit the record using nlapiSubmitRecord(record, doSourcing,
ignoreMandatoryFields).
Example 1 (Server Script)
This sample shows how to create a new Vendor Bill record and then add items to the Item
sublist and expenses to the Expenses sublist. Note that because you are adding new lines to
each sublist, you must call the nlobjRecord.selectNewLineItem(...) method. You then set all
values for the new lines using the nlobjRecord.setCurrentLineItemValue(...) method. When
you are finished adding values to each line in the sublist, you must commit each line to the
database. You will call the nlobjRecord.commitLineItem(...) method to commit each line.
var record = nlapiCreateRecord('vendorbill');
record.setFieldValue('entity', 196);
record.setFieldValue('department', 3);
record.selectNewLineItem('item');
record.setCurrentLineItemValue('item','item',380);
record.setCurrentLineItemValue('item', 'location', 102);
record.setCurrentLineItemValue('item', 'amount', '2');
record.setCurrentLineItemValue('item', 'customer',294);
record.setCurrentLineItemValue('item','isbillable','T');
record.commitLineItem('item');
record.selectNewLineItem('expense');
record.setCurrentLineItemValue('expense','category',3);
record.setCurrentLineItemValue('expense', 'account', 11);
SuiteScript Developer and Reference Guide
Working with Subtabs and Sublists
Working with Sublist Line Items
141
record.setCurrentLineItemValue('expense', 'amount','10');
record.setCurrentLineItemValue('expense','customer',294);
record.setCurrentLineItemValue('expense','isbillable','T');
record.commitLineItem('expense');
var id = nlapiSubmitRecord(record, true);
Example 2 (Server Script)
This sample shows how to use nlobjRecord.getLineItemCount(group), which is used to
determine the number of lines in a sublist. In this sample, a line item is added to the end of the
Items sublist. When the record is saved, the updates to the sublist are committed to the
database.
//Get the new record
var rec = nlapiGetNewRecord();
//Determine the number of lines on the Item sublist
var intCount = rec.getLineItemCount('item');
//Insert a line after the line that already exists
rec.insertLineItem('item', intCount + 1);
//Set the value of the line item
rec.setCurrentLineItemValue('item', 'quantity', intCount + 1, 10);
// Commit the sublist line changes
rec.commitLineItem('item');
// Submit the record to commit all change to the database
var id = nlapiSubmitRecord(rec, true);
Example 3 (Client Script)
This sample shows how to add a line item to a transaction using a client script. Be aware that in
client scripting you must always use nlapiCommitLineItem(type) to commit any line item
changes to the sublist.
In this example you first insert the line and then commit the line. If you set the item field using
nlapiSetCurrentLineItemValue(type, fldnam, value, firefieldchanged, synchronous), you
cannot 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 post-sourcing function that
sets a flag.
For example, suppose you want to insert a shipping line when a user clicks a button. You can
attach a function such as insertShippingRate() to that button, which adds an item named
“Shipping”, sets its rate, and then commits the line.
SuiteScript Developer and Reference Guide
Working with Subtabs and Sublists
Working with Sublist Line Items
142
function insertShippingRate()
{
nlapiSelectNewLineItem('item');
/* important so that you know that the script was called from insertShippingRate() */
nlapiSetCurrentLineItemValue('item', 'custcolinsertshippingrate', true);
nlapiSetCurrentLineItemText('item', 'item', 'Shipping');
}
function doPostSourcing(type, fldname)
{
if ( type == 'item' && fldname == 'item' && nlapiGetCurrentLineItemValue
('item', 'custcolinsertshippingrate') == true )
{
nlapiSetCurrentLineItemValue('item', 'custcolinsertshippingrate', false);
nlapiSetCurrentLineItemValue('item', 'rate', '7.50');
nlapiCommitLineItem('item');
}
}
Related Topics
•
•
•
•
Getting and Setting Line Item Values
Adding Sublists with SuiteScript
Subtabs and Sublists - What’s the Difference?
Sublist APIs
Getting and Setting Line Item Values
You can use both client and server scripts to get/set line item values. The set/get guidelines
provided here can be used on Editor Sublists, Inline Editor Sublists, and List Sublists sublists.
Example 1
The following sample includes several Sublist APIs. This sample copies sales reps from the
Sales Team sublist of one sales order to another sales order, ignoring those on the Sales Team
sublist who are not sales reps.
// Copy all the reps from the original order to the adjusting order
var iRep = 1;
var reps = originalSo.getLineItemCount('salesteam');
for (var rep = 1; rep <= reps; rep++)
{
// If the role is not sales rep, ignore it
if (originalSo.getLineItemValue('salesteam', 'salesrole', rep) != '-2')
continue;
var reppct = originalSo.getLineItemValue('salesteam', 'contribution', rep);
if (reppct != '0.0%')
{
SuiteScript Developer and Reference Guide
Working with Subtabs and Sublists
Working with Sublist Line Items
var repId = originalSo.getLineItemValue('salesteam', 'employee', rep);
// keep the percent the same
if (reppct.substring(reppct.length-1) == '%')
{
//remove the percent sign % from the end
reppct = reppct.substring(0, reppct.length-1);
}
so.insertLineItem('salesteam', iRep);
so.setCurrentLineItemValue('salesteam', 'contribution', iRep, reppct);
so.setCurrentLineItemValue('salesteam', 'employee', iRep, repId);
// copy the role
so.setCurrentLineItemValue('salesteam','salesrole',iRep,originalSo.getLineItemValue
('salesteam','salesrole', rep));
// If primary rep on original order make it primary on the new sales order
var primary = originalSo.getLineItemValue('salesteam', 'isprimary', rep);
so.setCurrentLineItemValue('salesteam', 'isprimary', iRep, primary);
iRep++
so.commitLineItem('salesteam');
}
}
// save the new order and return the ID
var soId = nlapiSubmitRecord(so, true);
SuiteScript Developer and Reference Guide
143
Working with Subtabs and Sublists
Working with Sublist Line Items
144
Example 2
This sample shows how to get the values of the line items on the Address (addressbook) sublist.
function getCustomerAddressBook()
{
var record = nlapiLoadRecord('customer', 87);
var numberOfAddresses = record.getLineItemCount('addressbook');
nlapiLogExecution('DEBUG', 'numberOfAddresses', numberOfAddresses);
for (var i=1; i <= numberOfAddresses; i++)
{
var internalid = record.getLineItemValue('addressbook','internalid',i);
var defaultshipping = record.getLineItemValue('addressbook','defaultshipping',i);
var defaultbilling = record.getLineItemValue('addressbook','defaultbilling',i);
var label = record.getLineItemValue('addressbook','label',i);
var address = record.getLineItemValue('addressbook','addrtext',i);
nlapiLogExecution('DEBUG', 'Address Info',
'internalid='+internalid+'\ndefaultshipping='+
defaultshipping+'\ndefaultbilling='+defaultbilling+'\naddress='+address);
}
}
This figure shows field values as they appear in the Execution Log of the Script Deployment
page.
The following figure shows field values for this script if you are running it in the SuiteScript
Debugger. Note that when running a script in the Debugger, script execution details appear on
the Execution Log tab in the Debugger, not on the Execution Log tab on the Script
Deployment page.
SuiteScript Developer and Reference Guide
Working with Subtabs and Sublists
Working with Item Groups in a Sublist
145
Example 3
The following sample is a validateLine client script which uses nlapiGetLineItemValue(type,
fldnam, linenum) to prevent the addition of Sales Order item lines with an amount greater than
10000.
function validateLine(group)
{
var newType = nlapiGetRecordType();
if ( newType == 'salesorder' && group == 'item' &&
parseFloat(nlapiGetCurrentLineItemValue('item','amount')) > 10000 )
{
alert('You cannot add an item with amount greater than 10000.')
return false;
}
return true;
}
Working with Item Groups in a Sublist
NetSuite item groups are stocked and sold as single units, even though they consist of several
individual items. Item groups are used to sell vendor-specific objective evidence (VSOE) item
group bundles, which can contain both taxable and nontaxable items.
You can use SuiteScript to interact with item groups in the same way you use the UI. Item
Group type items are added to transactions as other line items are. In the case of an Item Group
item, the item group expands to its member items. Item groups can optionally include start and
end lines. The SuiteScript behavior emulates the behavior of how you would add an item group
in the UI.
Example
In this example, an Item Group item is added to a transaction, and the tax code propagates to
the members of the group.
var rec = nlapiCreateRecord( 'cashsale' );
SuiteScript Developer and Reference Guide
Working with Subtabs and Sublists
Working with Sublists in Dynamic Mode and Client
146
rec.setFieldValue( 'entity', '76' ); //set the customer
rec.selectNewLineItem( 'item' );
rec.setCurrentLineItemValue( 'item', 'item', '66'); //item group item
rec.setCurrentLineItemValue( 'item', ‘quantity', 1);
rec.setCurrentLineItemValue( ‘item’, ‘taxcode’, -7 ); //set to non-taxable
rec.commitLineItem( 'item' );
var id = nlapiSubmitRecord( rec ); //on submit the item group expands
Working with Sublists in Dynamic Mode and Client
SuiteScript
When you copy, create, load, or transform a record in dynamic mode, you are also interacting
with all of the record’s elements in dynamic mode; this includes a record’s sublists.
Note: When using client SuiteScript on a sublist, you must also script in a way that
emulates the behaviors of the UI. Consequently, an API such as
nlapiSetLineItemValue(type, fldnam, linenum, value) will generally not supported
in client scripts. Read the rest of this section for more details.
Note: If you are unfamiliar with the concept of dynamic scripting, see Working with
Records in Dynamic Mode for details.
When scripting against a sublist that is in dynamic mode, the following APIs will NOT work
when adding a line or changing the values of an existing line:
•
nlapiSetLineItemValue(type, fldnam, linenum, value) - used when scripting in a
“current record” context, for example in user event scripts.
•
nlobjRecord.setLineItemValue(group, name, linenum, value) - used when scripting the
nlobjRecord object itself, as it exists on the server.
These APIs will not work in dynamic mode or in client SuiteScript because they have no UI
correlation. One of the primary components of dynamic and client scripting is that they
emulate the behaviors of the UI.
When users interact with sublists in the UI, they first select the sublist they want to work with,
then they select the line they want to add or change, and finally they click the Add button to
commit the line to the database. When you are scripting a sublist in dynamic mode or in client
SuiteScript, simply calling nlapiSetLineItemValue(type, fldnam, linenum, value) does not
provide enough context for the script to execute. Instead, you will follow one of these two
patterns when adding or changing a line:
To add a new line:
1.
nlapiSelectNewLineItem(type) - to specify the sublist you want to work with.
2.
nlapiSetCurrentLineItemValue(type, fldnam, value, firefieldchanged, synchronous) to set values on the current line.
3.
nlapiCommitLineItem(type) - to commit the line to the database.
SuiteScript Developer and Reference Guide
Working with Subtabs and Sublists
Working with Sublists in Dynamic Mode and Client
147
Example:
This sample creates a new sales order in dynamic mode, and then adds to new items to the
Items sublist.
var record = nlapiCreateRecord('salesorder', {recordmode: 'dynamic'});
// add the first item
record.selectNewLineItem('item');
record.setCurrentLineItemValue('item', 'item', 556);
record.setCurrentLineItemValue('item', 'quantity', 2);
record.commitLineItem('item');
// add the second item
record.selectNewLineItem('item');
record.setCurrentLineItemValue('item', 'item', 380);
record.setCurrentLineItemValue('item', 'quantity', '2');
record.setCurrentLineItemValue('item', 'amount', '0.1');
record.commitLineItem('item');
To change values on an existing line:
1.
nlapiSelectLineItem(type, linenum) - to specify the sublist you want to work with and
the existing line you want to change.
2.
nlapiSetCurrentLineItemValue(type, fldnam, value, firefieldchanged, synchronous) to set values on the current line.
3.
nlapiCommitLineItem(type) - to commit the line to the database.
Example:
This sample loads a sales order in dynamic mode, and then modifies a line that already exists.
var record = nlapiLoadRecord('salesorder', 55, {recordmode: 'dynamic'});
// modify an existing line
record.selectLineItem('item', 1);
record.setCurrentLineItemValue('item', 'item', 556);
record.setCurrentLineItemValue('item', 'quantity', 2);
record.commitLineItem('item');
Sublist Errors
You can only set line items that are valid. If you attempt to set a line that does not exist, you will
receive an “Invalid Sublist Operation” out-of-bounds error. The exception to this is on Suitelets.
Because Suitelets contain only your data, you will not receive a NetSuite error.
SuiteScript Developer and Reference Guide
Working with Subtabs and Sublists
Working with Sublists in Dynamic Mode and Client
Related Topics
•
•
•
•
Adding and Removing Line Items
Adding Sublists with SuiteScript
Subtabs and Sublists - What’s the Difference?
Sublist APIs
SuiteScript Developer and Reference Guide
148
Chapter 15 Working with Online Forms
Only the APIs listed in the following table are supported on online forms.
Important: These are also the only APIs supported in the offline client and on externally
available Suitelets (Suitelets set to Available Without Login on the Script
Deployment page). For more information on externally available Suitelets,
see SuiteScript and Externally Available Suitelets.
SuiteScript APIs available on online forms and externally available Suitelets
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
nlapiAddDays(d, days)
nlapiAddMonths(d, months)
nlapiCancelLineItem(type)
nlapiDateToString(d, format)
nlapiDisableField(fldnam, val)
nlapiDisableLineItemField(type, fldnam, val)
nlapiEncrypt(s, algorithm, key)
nlapiEscapeXML(text)
nlapiFormatCurrency(str)
nlapiGetCurrentLineItemIndex(type)
nlapiGetCurrentLineItemText(type, fldnam)
nlapiGetCurrentLineItemValue(type, fldnam)
nlapiGetFieldText(fldnam)
nlapiGetLineItemText(type, fldnam, linenum)
nlapiIsLineItemChanged(type)
nlapiRefreshLineItems(type)
nlapiRemoveLineItemOption(type, fldnam, value)
nlapiRemoveSelectOption(fldnam, value)
nlapiSelectLineItem(type, linenum)
•
•
•
nlapiGetLineItemCount(type)
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
nlapiGetLineItemValue(type, fldnam, linenum)
nlapiGetFieldValue(fldnam)
nlapiSetFieldValue(fldnam, value, firefieldchanged,
synchronous)
nlapiSelectNode(node, xpath)
nlapiSelectNodes(node, xpath)
nlapiSelectValue(node, xpath)
nlapiSelectValues(node, path)
nlapiStringToDate(str, format)
nlapiStringToXML(text)
nlapiXMLToString(xml)
nlapiSetLineItemValue(type, fldnam, linenum, value)
nlapiInsertLineItem(type, line)
nlapiRemoveLineItem(type, line)
nlapiGetRecordType()
nlapiGetRecordId()
nlapiGetRole()
nlapiGetUser()
nlapiSelectNewLineItem(type)
Note: See also Client SuiteScript and Online Forms, which discusses the Available Without
Login deployment preference as it applies to client SuiteScript.
SuiteScript Developer and Reference Guide
Working with Online Forms
150
Why are only certain APIs supported on online forms?
For security reasons, many SuiteScript APIs are not supported on online forms or externally
available (Available Without Login) Suitelets. Online forms and externally available Suitelets
are used for generating stateless pages that access or manipulate account information that is not
considered to be confidential. Therefore, scripts running on these pages cannot be used to
access information on the server because that would require a valid NetSuite session (through
user authentication).
Note that server-side SuiteScript execution for such pages (for example, user events and/or
Suitelet page generation or backend code) have no such restrictions.
Note: nlapiGetRole() always returns -31 (the online form user role) when used in this
context; nlapiGetUser() returns -4 (the return value for a “backdoor” entity).
The APIs listed in the previous section all operate on the current page and will run as expected
without a valid NetSuite session. Note that both types of pages (online forms and externally
available Suitelets) are hosted on a NetSuite domain called forms.netsuite.com. Having a
separate domain for online forms and externally available Suitelets prevents secure NetSuite
sessions established on system.netsuite.com from carrying over to these pages.
The following figure uses a Suitelet Script Deployment page to show the two domains types. In
this case, the Available Without Login preference is selected. When this Suitelet is called, it will
be called from the forms.netsuite.com domain. So long as only the APIs listed in the table
SuiteScript APIs available on online forms and externally available Suitelets have been used (in
addition to any UI Objects), this externally available Suitelet will load and run as intended.
If the Available Without Login preference is not set, the Suitelet will be called from the login
domain system.netsuite.com.
SuiteScript and the Offline Client
Only a subset of the SuiteScript API is supported in the offline client. A list of these APIs are
provided in the topic Working with Online Forms.
If you use SuiteScript APIs that are are not supported in the offline client, end users will receive
the following error message when they save a record:
SuiteScript Developer and Reference Guide
Working with Online Forms
“You cannot submit this form due to an unexpected error.”
SuiteScript Developer and Reference Guide
151
Chapter 16 Inline Editing and SuiteScript
The following topics are covered in this section:
•
Inline Editing and SuiteScript Overview
•
Why Inline Edit in SuiteScript?
•
Inline Editing Using nlapiSubmitField
•
Consequences of Using nlapiSubmitField on Non Inline Editable Fields
•
Inline Editing (xedit) as a User Event Type
•
What’s the Difference Between xedit and edit User Event Types?
•
Inline Editing and nlapiGetNewRecord()
•
Inline Editing and nlapiGetOldRecord()
Inline Editing and SuiteScript Overview
In the NetSuite UI, inline editing lets you edit fields directly from a record list or from a set of
search results. (See Using Inline Editing in the NetSuite Help Center for general information on
inline editing not related to SuiteScript.)
In SuiteScript, the equivalent of inline editing is changing the value of a field without loading
and submitting the entire record the field appears on. This is done using
nlapiSubmitField(type, id, fields, values, doSourcing). See Inline Editing Using
nlapiSubmitField for details.
Be aware that in SuiteScript, inline editing and mass updating are considered to be event types
that can trigger user event scripts. When users inline edit a field in the UI, or when they
perform a mass update, these two event contexts can trigger the execution of a user event script
if the script’s context type has been set to xedit. See Inline Editing (xedit) as a User Event Type.
Important: When using SuiteScript to inline edit a field on a record, note the following:
•
In the UI and in SuiteScript, you can only perform inline editing on body fields. You
cannot inline edit sublist fields. If you do not know the distinction between body and
sublist fields, see Working with Fields Overview in the NetSuite Help Center.
•
In SuiteScript, you cannot inline edit select fields. In other words, you cannot call
nlapiSubmitField on a select field.
•
In the NetSuite UI, users cannot set fields that are not inline editable. SuiteScript,
however, does let you set non inline editable fields using nlapiSubmitField, but this is
NOT the intended use for this API. See Consequences of Using nlapiSubmitField on
SuiteScript Developer and Reference Guide
Inline Editing and SuiteScript
Why Inline Edit in SuiteScript?
153
Non Inline Editable Fields to learn about the increased governance cost of using this
API on non inline editable fields.
•
You can use the nlapiSubmitField function to inline edit inline-editable body fields on
SuiteScript-supported records only. Do not use nlapiSubmitField (or any other
SuiteScript API) on a record that does not officially support SuiteScript. For a list of
records that officially support SuiteScript, see SuiteScript Supported Records in the
NetSuite Help Center.
Note: •If you want to perform inline editing through the UI or through SuiteScript, you
must first enable the Inline Edit feature in your account. Enable this feature by
going to Setup > Company > Enable Features. In the Data Management section,
click the Inline Editing check box.
Why Inline Edit in SuiteScript?
To change values on a record you can either load and submit the entire record, or you can
simply call nlapiSubmitField(type, id, fields, values, doSourcing) on a specified body field or
fields. Calling the nlapiSubmitField function, which is the programmatic equivalent of inline
editing, requires less database processing since the entire record object is not being loaded to
make a single field update. Note that in the UI and in SuiteScript, not all fields are inline
editable.
Important: In the NetSuite UI, users cannot set fields that are not inline editable.
SuiteScript, however, does let you set non inline editable fields using
nlapiSubmitField, but this is NOT the intended use for this API. See
Consequences of Using nlapiSubmitField on Non Inline Editable Fields to
learn about the increased governance cost of using this API on non inline
editable fields.
Related Topics
•
•
Inline Editing and SuiteScript Overview
Inline Editing Using nlapiSubmitField
Inline Editing Using nlapiSubmitField
The SuiteScript equivalent of inline editing a single field or multiple fields on a record is calling
the nlapiSubmitField(type, id, fields, values, doSourcing) function. After updating a field’s
value using nlapiSubmitField, you do not need to then call nlapiSubmitRecord to commit the
change to the database.
The following figure shows that the Phone field on a customer record is being inline edited in
the UI. To save the change, a user simply needs to click away from the field.
SuiteScript Developer and Reference Guide
Inline Editing and SuiteScript
Inline Editing Using nlapiSubmitField
154
In SuiteScript, the programmatic equivalent of inline editing the Phone field on customer
record 140 is:
var updatefield = nlapiSubmitField('customer', '149', 'phone', '800-555-1234');
In one call, you can reference a specific record and field, and then set a new value for that field.
The entire process consumes only 10 units, which, in many cases, makes updating fields
through nlapiSubmitField preferable to loading a record, referencing the field on the record,
setting a value for the field, and then submitting the entire record to the database. For example,
the following script consumes 30 units to accomplish the same thing as the previous inline
editing sample:
var rec = nlapiLoadRecord('customer', '149'); // 10 units
rec.setFieldValue('phone', '800-555-1234');
var id = nlapiSubmitRecord() // 20 units
Note that with inline editing in SuiteScript you can update multiple fields on a record, and the
unit count remains as 10. In this example, three fields are updated, however, there is still only
one call to nlapiSubmitField. For example:
var fields = new Array();
var values = new Array();
fields[0]='phone';
values[0] = "800-555-1234";
fields[1] = 'url';
values[1] = "www.goodtimeswithsuitescript.com";
fields[2] = 'billpay';
values[2] = "T";
var updatefields = nlapiSubmitField('customer', '149', fields, values);
Important: If you are initiating a scheduled script from a user event script, and the user
event type is set to xedit, no call to nlapiSubmitField within that scheduled
script will actually save the field specified in nlapiSubmitField.
SuiteScript Developer and Reference Guide
Inline Editing and SuiteScript
Consequences of Using nlapiSubmitField on Non Inline
155
Important: In the NetSuite UI, users cannot set fields that are not inline editable.
SuiteScript, however, does let you set non inline editable fields using
nlapiSubmitField, but this is NOT the intended use for this API. See
Consequences of Using nlapiSubmitField on Non Inline Editable Fields to
learn about the increased governance cost of using this API on non inline
editable fields.
Related Topics
•
•
Inline Editing and SuiteScript Overview
Why Inline Edit in SuiteScript?
Consequences of Using nlapiSubmitField on Non Inline
Editable Fields
In the NetSuite UI, only certain fields are inline editable. These are fields that have no slaving
relationship to other fields. When users update a field that is inline editable, only the data for
that field is updated; there is no cascading effect on other data contained in the record.
Although nlapiSubmitField(...) is the programmatic equivalent of inline editing, it is possible to
use this API to update fields that are not inline editable in the UI. If a non inline editable field is
submitted for update, all the data on the record will be updated appropriately. However, to
support this, when a non inline editable field is submitted, the NetSuite backend must load the
record, set the field(s), and then submit the record. Completing the “load record, set field,
submit record” lifecycle for a record allows all slaving and validation logic on the record to
execute.
Note: If an array of fields is submitted using nlapiSubmitField(...), and one field in the array
is non inline editable, NetSuite also applies the same solution: the record is loaded
in the backend, all fields are set, and the record is submitted.
Governance Implications
When you use nlapiSubmitField(...) as it is intended to be used (to set one or more fields that
are inline editable in the UI), the SuiteScript governance cost is 10 units.
However, when you use nlapiSubmitField(...) to update fields that are NOT inline editable in
the UI, the unit cost for nlapiSubmitField(...) is higher. Your script is charged the units it takes
to load and submit a record.
For example, the unit cost of nlapiSubmitField(...) to set a non inline editable field on a
transaction is:
1.
load the record (nlapiLoadRecord) = 10 units
2.
set the field = no units
3.
submit the record (nlapiSubmitRecord) = 20 units
SuiteScript Developer and Reference Guide
Inline Editing and SuiteScript
Inline Editing (xedit) as a User Event Type
156
Total = 30 units
It is best practice to use nlapiSubmitField(...) as it is intended to be used: to set fields that are
inline editable in the UI. To help you know which fields are inline editable, you can refer to the
UI.
Inline Editing (xedit) as a User Event Type
To set a user event script to execute in response to an inline edit field change or a mass update,
specify xedit as the type argument in your script. The xedit type can be specified in
beforeSubmit or afterSubmit user event scripts.
The following sample shows a user event script that will execute when a user inline edits a
record, or the record is updated in a mass update. This script shows how to get all fields that
were inline edited on the record or during the mass update.
function getUpdatedFields(type)
{
// if the record is inline edited or mass updated, run the script
if (type == 'xedit')
{
// call nlapiGetNewRecord to get the fields that were inline edited/mass updated
var fields = nlapiGetNewRecord().getAllFields()
// loop through the returned fields
for (var i = 0; i < fields.length; i++)
{
if (fields[i] == 'phone')
nlapiSetFieldValue('phone', nlapiGetFieldValue('phone'))
}
}
}
Note: User event scripts are not executed upon mass updates of child matrix items from
their parent items.
Related Topics
•
•
•
•
•
Inline Editing and SuiteScript Overview
What’s the Difference Between xedit and edit User Event Types?
Inline Editing and nlapiGetNewRecord()
Inline Editing and nlapiGetOldRecord()
User Event Scripts
SuiteScript Developer and Reference Guide
Inline Editing and SuiteScript
What’s the Difference Between xedit and edit User Event
157
What’s the Difference Between xedit and edit User Event
Types?
When the user event type argument is set to xedit, it means that the execution context for the
script is inline edit or mass update. In other words, if a user has inline edited a field on a record
(or if the record has been part of a mass update), the user event script will execute. In contrast,
user event scripts set to execute when the type argument is set to edit will execute when the
record is edited in all other contexts. The script will not execute as a result of an inline edit or
mass update.
Related Topics
•
•
•
Inline Editing and SuiteScript Overview
Inline Editing (xedit) as a User Event Type
User Event Scripts
Inline Editing and nlapiGetNewRecord()
In a user event script, if you have set the user event type argument to xedit, and you are using
nlapiGetNewRecord() to return all the newly updated fields, be aware that only the fields
which have been updated through an xedit event (inline edited or mass updated) will be
returned. In many cases, this is only one or two fields.
In contrast, if the user event type argument is set to edit, and you call nlapiGetNewRecord in a
beforeSubmit, you will get back all the fields on the record.
For xedit user events, you should call nlapiGetNewRecord().getAllFields() to return an array of
all the fields being changed in the inline edit, mass update, or nlapiSubmitField() operation.
Note: If you call getFieldValue() on a field that is not in that array, null is returned.
Related Topics
•
•
•
•
Inline Editing and SuiteScript Overview
Inline Editing (xedit) as a User Event Type
Inline Editing and nlapiGetOldRecord()
User Event Scripts
Inline Editing and nlapiGetOldRecord()
Although calling nlapiGetOldRecord() in an inline editing context requires more processing
from the NetSuite database (and therefore may add to the user response time), there is less
ambiguity when calling this method in an inline editing context than when calling
nlapiGetNewRecord().
SuiteScript Developer and Reference Guide
Inline Editing and SuiteScript
Inline Editing and nlapiGetOldRecord()
158
The following sample shows how to use nlapiGetOldRecord() in a user event script that will
execute in the context of an inline edit or mass update. This scripts returns all the fields on the
record prior to the field updates being committed to the database.
function getUpdatedFields(type)
{
// if the record is inline edited or mass updated, run this script
if (type == 'xedit')
{
// call nlapiGetOldRecord to get all field values on the current record
// prior to the write operation
var fields = nlapiGetOldRecord().getAllFields()
// loop through all the returned fields
for (var i = 0; i < fields.length; i++)
{
if (fields[i] == 'phone')
nlapiSetFieldValue('phone', nlapiGetFieldValue('phone'))
}
}
}
Related Topics
•
•
•
•
Inline Editing and SuiteScript Overview
Inline Editing (xedit) as a User Event Type
Inline Editing and nlapiGetNewRecord()
User Event Scripts
SuiteScript Developer and Reference Guide
Part 4 Understanding
NetSuite Script Types
Chapter 17 Script Types Overview
Script types are organized primarily by where they run (on the client or on the server). They
are also organized by the types of tasks you are trying to complete or the data you want to
capture.
Use the SuiteScript API to create the following types of scripts.
•
User Event Scripts: User Event scripts are triggered when users work with records and
data changes in NetSuite as they create, open, update, or save records. User Event
scripts are useful for customizing the workflow and association between your NetSuite
entry forms. These scripts can also be used for doing additional processing before
records are entered or for validating entries based on other data in the system.
•
Suitelets: Suitelets enable the creation of dynamic web content. Suitelets can be used to
implement custom front and backends. Through API support for scripting forms and
lists, these Suitelets can also be used to build NetSuite-looking pages. NetSuite
tasklinks can be created to launch a Suitelet. These tasklinks can be used to customize
existing centers.
•
RESTlets: RESTlets are server-side scripts that can be used to define custom, RESTful
integrations to NetSuite. RESTlets follow the principles of the REST architectural style
and use HTTP verbs, HTTP headers, HTTP status codes, URLs, and standard data
formats. They operate in a request-response model, and an HTTP request to a systemgenerated URL invokes each RESTlet.
•
Scheduled Scripts: Scheduled scripts are executed on-demand in real-time or via a
user-configurable schedule. Scheduled scripts are useful for batch processing of
records.
•
Client Scripts: Client scripts are executed on the client. These scripts can be attached to
and run on individual forms, or they can be deployed globally and executed on entity
and transaction record types. Global client scripts enable centralized management of
scripts that can be applied to an entire record type.
•
Portlet Scripts: Portlet scripts are used to create custom dashboard portlets. For
example, you can use SuiteScript to create a portlet that is populated on-the-fly with
company messages based on data within the system.
•
Mass Update Scripts: Mass update scripts allows you to programmatically perform
custom mass updates to update fields that are not available through general mass
updates. You can also use action scripts to run complex calculations, as defined in your
script, across many records.
SuiteScript Developer and Reference Guide
Script Types Overview
161
•
Workflow Action Scripts: Workflow action scripts allow you to create custom actions
that are defined on a record in a workflow.
•
Bundle Installation Scripts: Bundle installation scripts fire triggers that execute as part
of bundle installation, update, or uninstall. Trigger execution can occur either before
install, after install, before update, after update, or before uninstall. These triggers
automatically complete required setup, configuration, and data management tasks for
the bundle.
Note that when you create a SuiteScript file, you will need to designate the type of script you
want to write. You will do this by going to Setup > Customization > Scripts > New > [type],
where type is one of the types shown below:
To actually run a script in NetSuite, see Running a Script in NetSuite.
Related Topics
•
•
•
What is SuiteScript?
SuiteScript Execution Diagram
SuiteScript API Overview
SuiteScript Developer and Reference Guide
Chapter 18 SuiteScript Execution Diagram
When writing your scripts, it is important to understand where the scripts will run (client-side
or server-side) and when the scripts will run (before data loads into a page loads, after an
update is made to the data, or after the data has been saved and committed to the database).
Understanding the basic concepts of where and when scripts will run will help you understand
the SuiteScript API. It will also help you when debugging your code should you encounter
problems.
The following diagram provides an overview showing where script types run. For an overview
on each script type, see Script Types Overview.
SuiteScript Developer and Reference Guide
SuiteScript Execution Diagram
SuiteScript Developer and Reference Guide
163
Chapter 19 Client Scripts
The following topics are covered in this section. If you are new to SuiteScript, these topics
should be read in order.
•
What is Client SuiteScript?
•
Client Script Execution
•
Client Event Functions
•
Form-level and Record-level Client Scripts
•
Client Script Metering
•
Role Restrictions in Client SuiteScript
•
How Many Client Events Can I Execute on One Form?
•
Error Handling and Debugging Client SuiteScript
•
Client SuiteScript and Online Forms
•
Running a Client Script in NetSuite
•
Client SuiteScript Samples
What is Client SuiteScript?
Client scripts are SuiteScripts executed in the browser. They can run on most standard records,
custom record types, and custom NetSuite pages (for example, Suitelets).
Note: To know which standard record types support client SuiteScript, see SuiteScript
Supported Records in the NetSuite Help Center. If a record supports client scripts,
an X will appear in the column called “Scriptable in Client SuiteScript”.
Generally, client scripts are used to validate user-entered data and to auto-populate fields or
sublists at various form events. Such events can include loading or initializing a form, changing
a field, or saving a record. Another use case for client scripts is to source data from an external
data source to a field. This is accomplished using the API nlapiRequestURL(url, postdata,
headers, callback, httpMethod).
Client scripts are executed by pre-defined event “triggers.” These triggering event types types
are discussed in the section Client Event Functions. These events include:
•
Initializing forms
•
Entering or changing a value in a field (before and after it is entered)
SuiteScript Developer and Reference Guide
Client Scripts
Client Script Execution
•
Entering or changing a value in a field that sources another field
•
Selecting a line item on a sublist
•
Adding a line item (before and after it is entered)
•
Saving a form
•
Searching for another record
•
Loading, saving or deleting a record
165
Once you have created your client script, you can attach your .js script file to the form you are
customizing.
If you have created a client script that you want to execute across an entire record type (for
example, all Customer records in the system), then you can deploy the script to the specified
record type. Client scripts deployed globally affect the behavior of all the records they are
deployed to, rather than just a specific form on a single record.
Related Topics
•
•
•
•
Client Event Functions
Form-level and Record-level Client Scripts
Role Restrictions in Client SuiteScript
Client SuiteScript Samples
Client Script Execution
Client scripts are executed within a browser. Whether they are client scripts attached to
individual forms, or client script deployed globally to an entire record type, all execution
occurs in the browser.
Record-level (globally deployed) client scripts are executed after any existing form-based client
scripts are run, and before any user event scripts. This means that record-level client scripts
can run on both built-in and custom forms.
Note that there are some scripts that are considered to be client scripts, yet they make calls back
to a NetSuite database. In this case you are working with records as “remote objects” on the
client.
The following sample is a client script that has been attached to a Sales Order form. (For
information on attaching client scripts to forms, see Step 3: Attach Script to Form.) When the
user saves the Sales Order, the script gets the value of the item field on the Item sublist, then
loads a specific Inventory Item record based on the value of the item in the Item sublist. The
script then sets a value on the Inventory Item record and submits the record. Although there is
backend activity being executed in this script, the script’s initial execution is based on the
saveRecord client event trigger (see Client Event Functions), therefore it is still considered to be
a client script.
SuiteScript Developer and Reference Guide
Client Scripts
Client Event Functions
166
// Client side script on sales order, on save
// Load the 1st item and mark it inactive
function onSave()
{
var id = nlapiGetLineItemValue('item', 'item', 1);
var record = nlapiLoadRecord('inventoryitem', id);
record.setFieldValue('isinactive', 'T');
nlapiSubmitRecord(record);
return true;
}
Related Topics
•
•
•
Form-level and Record-level Client Scripts
Client SuiteScript Samples
Client Event Functions
Client Event Functions
In NetSuite, client scripts can be executed on 10 different client-side events. These client events
can occur when a user loads a NetSuite form into the browser, or when a user selects a field or
a field is updated. Field updates can occur when a user updates a field, or when a field is autoupdated through a sourcing relationship with another field. A client event can also occur when
a user clicks the Submit or Save button on a NetSuite page.
The following table describes each client event type and the actions associated with the event.
Note that the functions that are called on each event type do not have to be written as
pageInit() or fieldChanged(), and so on. However, when writing your client script, it is best
practice to indicate the event type in the function name, for example: pageInit_alertSalesRep(),
or validateField_department(), or saveRecordCustomer().
SuiteScript Developer and Reference Guide
Client Scripts
Client Event Functions
Client Event Type
(and sample function
name)
pageInit
Parameters
Returns
Description
This client event occurs when the page completes
loading or when the form is reset. This function is
automatically passed the type argument from the
system.
type: the mode in which the
record is being accessed.
These modes can be set to:
•
•
•
167
create
This is similar to an onLoad JavaScript client-side event.
copy
See Page Init Sample.
edit
saveRecord
Boolean
This client event occurs when the submit button is
pressed but prior to the form being submitted. You
should always return either true or false from a
saveRecord event. A return value of false suppresses
submission of the form.
See Save Record Sample.
validateField
type: the sublist internal ID
name: the field internal ID
linenum: line number if this is
a sublist. Line numbers start
at 1, not 0.
Boolean
This client event occurs whenever a field is about to be
changed by the user or by a client side call. Returning
false from this function prevents the field's value from
changing.
This function is automatically passed up to three
arguments by the system: type, name, linenum.
This event type is similar to an onBlur JavaScript clientside event.
In NetSuite, validateField events execute on fields
added in beforeLoad user event scripts.
Note: This event type does NOT apply to drop-down
select or check box fields.
See Validate Field Sample.
fieldChanged
type: the sublist internal ID
name: the field internal ID
linenum: line number if this is
a sublist. Line numbers start
at 1, not 0.
This client event occurs whenever a field is changed by
the user or by a client side call. This event can also occur
directly through beforeLoad user event scripts.
This function is automatically passed up to three
arguments by the system: type, name, linenum.
This event type is similar to an onChange JavaScript
client-side event.
See Field Changed Sample.
postSourcing
type: the sublist internal ID
name: the field internal ID
This client event occurs following a field change once
all the field's child field values are sourced from the
server. Enables fieldChange style functionality to occur
once all dependent field values have been set.
This function is automatically passed up to two
arguments from the system: type, name.
See Post Sourcing Sample.
SuiteScript Developer and Reference Guide
Client Scripts
Form-level and Record-level Client Scripts
Client Event Type
(and sample function
name)
Parameters
lineInit
type: the sublist internal ID
validateLine
type: the sublist internal ID
Returns
168
Description
This client event occurs when an existing line is
selected. It can be thought of as the pageInit function
for sublist line items (inlineeditor and editor sublists
only). This function is automatically passed the type
argument from the system.
Boolean
This client event occurs prior to a line being added to a
sublist (inlineeditor or editor sublists only). It can be
thought of as the saveRecord equivalent for sublist line
items (inlineeditor and editor).
Returns false to reject the operation. References to
fields should be done using nlapiGetCurrent***
functions.
This function is automatically passed the type
argument from the system.
recalc
type: the sublist internal ID
Event occurs after a line has been added to a sublist.
This allows for any global actions that change
whenever the contents of the sublist change.
Notes:
validateInsert
type: the sublist internal ID
Boolean
•
Recalc functions will not execute when the Add
Multiple button is used to add multiple line items.
•
Scripts that execute on recalc events do not need
to include a call to nlapiCommitLineItem(type)
since recalculation occurs automatically. Calling
nlapiCommitLineItem will end up calculating the
line twice.
The validateInsert event occurs when you insert a line
into an edit sublist. For information on the edit sublist
type, see Editor Sublists in the NetSuite Help Center.
The UI equivalent of this event is when a user selects an
existing line in a sublist and then clicks the Insert
button. In SuiteScript, the equivalent action is calling
nlobjRecord.insertLineItem(...). Note that returning
false on a validateInsert blocks the insert.
validateDelete
type: the sublist internal ID
Boolean
The validateDelete event occurs when you try to
remove an existing line from an edit sublist. Returning
false blocks the removal.
For information on the edit sublist type, see Editor
Sublists in the NetSuite Help Center.
*The ValidateField and FieldChanged scripts require a null line item for body fields.
Form-level and Record-level Client Scripts
SuiteScript Developer and Reference Guide
Client Scripts
Client Script Metering
169
Form-based client scripts run against specific fields and forms. Record-level client scripts,
similar to user event scripts, are deployed globally and run against an entire record type. For
example, record-level client scripts can be deployed to run against all Invoice records or all
Customer records in the system.
Record-level client scripts run independent of any client scripts already attached to a specific
form on the record. Record-level client scripts can also be used on forms and lists that have
been generated through UI Objects during Suitelets development. Form-based client scripts
cannot be used by Suitelets.
Additionally, record-level clients scripts allow you to set audience definitions on the Script
Deployment page. Defining an audience for the script deployment allows you to specify which
members of your company, which departments, and which roles will be able to see the recordlevel customizations that have been implemented.
To deploy record-level client scripts into your account, you must follow the deployment model
used for Suitelet, user event, scheduled, and portlet scripts. (See Running Scripts in NetSuite
Overview to learn how to run a record-level script in NetSuite.)
Form-level client scripts, however, require only that the client script is attached to the
individual form it is running against. For details on attaching client scripts to forms, see Step 3:
Attach Script to Form.
Note: You can deploy up to five record-level client script to any record types that are
already supported in the existing form-based model. For information on records
supported in client scripting, see SuiteScript Supported Records in the NetSuite
Help Center.
Related Topics
•
•
•
What is Client SuiteScript?
Client Script Execution
Client SuiteScript Samples
Client Script Metering
Client scripts are metered or governed on a per-script basis. For example, if an account has one
form-level client script attached to a form, and one record-level client script deployed to the
record (which contains the form), each client script can total 1000 units. Units are not shared
among the client scripts that are associated with a form or record.
Note: For information on script metering and the SuiteScript governance model, see
SuiteScript Governance.
SuiteScript Developer and Reference Guide
Client Scripts
Role Restrictions in Client SuiteScript
170
Role Restrictions in Client SuiteScript
Running a client script to access a record will result in an error if the role used does not have
permission to view/edit that record. Client SuiteScript respects the role permissions specified
in the user’s NetSuite account.
Example
The following is a client script, which you can attach to a custom sales order form and set to
execute on the field change client event.
function email(){
var salesRep = nlapiGetFieldValue('salesrep');
var salesRepEmail = nlapiLookupField('employee', salesRep, 'email');
alert(salesRepEmail);
}
If you are logged in as admin, when you load the sales order with this form, and then select the
Sales Rep field, you will receive the alert. However, if you log in using a non-admin role (such
as Sales Manager), or a role that does not have permission to view/edit Employee records, you
will receive an error when you select the Sales Rep field.
To work around this issue, as the script developer you must consider the types of users who
may be using your custom form and running the script. Consider which record types they do
and do not have access to. If it is vital that all who run the script have access to the records in
the script, you may need to redefine the permissions of the users (if your role is as an admin).
Or you may need to rewrite your script so that it references only those record types that all
users have access to.
Another consideration is to write the script as a server-side user event script and set the
“Execute As Admin” preference on the script’s Script Deployment page. Note that in the sample
script above, you would not be able to run the script as a user event script and throw an alert, as
alerts are a function of client scripts only. However, you could rewrite the script so that it emails
the user the sales rep’s email address (instead of throwing an alert).
Note: For information on user event scripts, see User Event Scripts. For information on
executing scripts as admin, see Executing Scripts as Admin.
How Many Client Events Can I Execute on One Form?
Client scripts have a limit of eight client events per form. The following figure shows a Custom
Entry Form for a Customer record. If you choose, you can run a script that contains client
event functions for all eight available event types. This figure shows only five client event
functions are specified within this script, but all eight in one script file is supported.
For information on client event functions, see Client Event Functions.
SuiteScript Developer and Reference Guide
Client Scripts
Error Handling and Debugging Client SuiteScript
171
Note: For information on attaching a client script to a form and running the script in your
account, see Step 3: Attach Script to Form.
Error Handling and Debugging Client SuiteScript
Important: You cannot debug form- or record-level client scripts in the SuiteScript
Debugger. To debug client scripts, NetSuite recommends using either the
Firebug debugger, which integrates with Firefox, or the Microsoft Script
Debugger, which integrates with Internet Explorer. For instructions on
working with either of these debuggers, please see the documentation
provided with each product.
Regarding error handling in client SuiteScript, NetSuite catches and throws alerts for all
unhandled SuiteScript errors that occur in both form- and record-level client scripts.
The following figure shows an alert that is thrown because the function specified in the
pageInit event is not properly defined. When the logged-in users receive this alert, they can
contact their NetSuite administrators for further instruction.
Note that alerts provide the scriptId (in this case customscript28) of the Script record. This is
information that will help NetSuite administrators locate the specific SuiteScript file that is
throwing the error.
SuiteScript Developer and Reference Guide
Client Scripts
Client SuiteScript and Online Forms
172
Also note that like other script types, the Script record page for record-level client scripts
includes an Unhandled Errors subtab. NetSuite administrators can use this tab to specify who,
if anyone, they want to receive emailed messages when script errors occur. (Go to Setup >
Customization > Scripts > New > Client to access the Script record page for record-level client
scripts.)
Additionally, the Script Deployment page for record-level client scripts includes an Execution
Log subtab, on which all script errors are logged. (Go to Setup > Customization > Script
Deployments > to select your deployment.)
Related Topics
•
•
•
What is Client SuiteScript?
Form-level and Record-level Client Scripts
Client SuiteScript Samples
Client SuiteScript and Online Forms
When running client scripts in online forms, you must select the Available Without Login
check box to ensure that the script will run on the form (see figure). If the Available Without
SuiteScript Developer and Reference Guide
Client Scripts
Running a Client Script in NetSuite
173
Login check box is not selected, users will still have access to the form, however, the client
script will not run.
Additionally, when working with online forms you can only use the APIs listed in the table
called SuiteScript APIs available on online forms and externally available Suitelets.
To access the Available without Login preference for client scripts:
1.
Navigate to your form and click the Custom Code tab.
2.
In the Script File field, click the + (New) option.
The File popup appears.
3.
Select the Available without Login check box.
4.
Load your client script into the Select File field, and click Save.
Related Topics
•
•
•
What is Client SuiteScript?
Client Script Execution
Client SuiteScript Samples
Running a Client Script in NetSuite
To run a client script in NetSuite, you must:
1.
Create a JavaScript file for your client script.
2.
Load the file into NetSuite.
3.
Attach your script file to a custom form (if you have written a form-level client script).
4.
Create a Script record (if you have written a record-level client script).
5.
Define all runtime options on the Script Deployment page (if you have written a
record-level client script).
SuiteScript Developer and Reference Guide
Client Scripts
Client SuiteScript Samples
174
If you are new to SuiteScript and need information on each of these steps, see Running Scripts
in NetSuite Overview.
Client SuiteScript Samples
The following samples are covered in this section. They illustrate how client event functions are
used to interact with the form.
•
Writing Your First Client Script
•
Page Init Sample
•
Save Record Sample
•
Post Sourcing Sample
•
Validate Field Sample
•
Field Changed Sample
Writing Your First Client Script
A great way to get started with client scripts is to deploy a simple script that has a function on
every exposed event. Consider the following client script:
function myPageInit(type)
{
alert('myPageInit');
alert('type=' + type);
}
function mySaveRecord()
{
alert('mySaveRecord');
return true;
}
function myValidateField(type, name, linenum)
{
if(name == 'custentity_my_custom_field')
{
alert('myValidateField');
alert('type=' + type);
alert('name=' + name);
alert('linenum=' + linenum);
}
return true;
}
function myFieldChanged(type, name, linenum)
{
alert('myFieldChanged');
SuiteScript Developer and Reference Guide
Client Scripts
Client SuiteScript Samples
175
alert('type=' + type);
alert('name=' + name);
alert('linenum=' + linenum);
}
function myPostSourcing(type, name)
{
alert('myPostSourcing');
alert('type=' + type);
alert('name=' + name);
}
function myLineInit(type)
{
alert('myLineInit');
alert('type=' + type);
}
function myValidateLine(type)
{
alert('myValidateLine');
alert('type=' + type);
}
function myValidateInsert(type)
{
alert('myValidateInsert');
alert('type=' + type);
}
function myValidateDelete(type)
{
alert('myValidateDelete');
alert('type=' + type);
}
function myRecalc(type)
{
alert('myRecalc');
alert('type=' + type);
}
This sample displays all the available arguments for every script-triggered event. Notice that
some functions return a Boolean while some do not. Also note that some functions have
linenum as one of the arguments. Sublist functions do not have a linenum argument because
the event is confined to the specific line that triggered it.
The function myValidateField has an additional if block to check whether the event was
invoked by a custom field with the id custentity_my_custom_field . This ensures the logic is
executed only under the correct circumstances.
Note: It is important to check the argument values to branch execution logic. This
improves performance and avoids logic executed indiscriminately.
SuiteScript Developer and Reference Guide
Client Scripts
Client SuiteScript Samples
176
To obtain a better understanding on when these client script events are triggered and what the
arguments contain, upload the JavaScript file to the SuiteScript folder in the NetSuite file
cabinet, and deploy the script by specifying the functions in a script record (see figure).
Note: When saved the Script record is saved, the system will automatically prefix the
script ID with customscript. In the figure above, the final unique ID for this client
script will be customscript_wlf_my_client_script. This custom script record
identifier can be passed as a value to the scriptId parameter that is included in
several SuiteScript APIs.
The previous screenshot demonstrates the definition of a record-level client script. This script
is deployed globally to any records specified in the Deployments tab (see figure). In this case,
this script will be deployed to all Case records in the system.
SuiteScript Developer and Reference Guide
Client Scripts
Client SuiteScript Samples
177
When a person opens any Case record, the following alerts are thrown right way on the
pageInit (page load) trigger:
When you click OK to begin editing the record, the type=edit alert is thrown.
Page Init Sample
The Page Init function is called when the form is first loaded. Some of the 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
SuiteScript Developer and Reference Guide
Client Scripts
Client SuiteScript Samples
Examples
Set Default Field Values for a Field
function pageInit()
{
// if 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'));
}
}
SuiteScript Developer and Reference Guide
178
Client Scripts
Client SuiteScript Samples
179
Disable a Field
function pageInit()
{
//On init, disable two optional Other fields: fieldA and fieldB.
nlapiDisableField('custrecord_other_fieldA', true);
nlapiDisableField('custrecord_other_fieldB', true);
}
Display User Profile Information
function pageInit()
{
//On page init display the currently logged in User's profile information.
// Set variables
var userName = nlapiGetUser();
// entity id of the current user
var userRole = nlapiGetRole();
// id of the current user's role
var userDept = nlapiGetDepartment(); // id of the current user's department
var userLoc = nlapiGetLocation(); // id of the current user's location
// Display information
alert("Current User Information" + "\n\n" +
"Name: " + userName + "\n" +
"Role: " + userRole + "\n" +
"Dept: " + userDept + "\n" +
"Loc: " + userLoc
);
}
Save Record Sample
The Save Record function is called when the user requests the form to be saved. This function
returns false to reject the operation. Use the Save Record function to provide alerts to the user
before committing the data. If it is necessary for the user to make changes before committing
the data, return false — otherwise display the alert, return true and allow the user to commit
the data.
You can also use the Save Record 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;
}
SuiteScript Developer and Reference Guide
Client Scripts
Client SuiteScript Samples
180
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;
}
Post Sourcing Sample
(Transaction Forms Only)
The Post Sourcing 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 Post Sourcing rather than from Field Changed.
Example
On Sales order – Post sourcing
// Wait for all sourcing to complete from item field, get the rate field. If rate < 10, set it to 20.
// Execute this post sourcing function
function postSourcing(type, name)
{
// Execute this code when all the fields from item are sourced on the sales order.
if(type =='item' && name =='item')
{
// Once all the fields from item are sourced
var rate = nlapiGetCurrentLineItemValue('item', 'rate');
var line = nlapiGetCurrentLineItemIndex(type);
if(rate < 10)
{
nlapiSetCurrentLineItemValue('item', 'rate', 20);
}
}
}
Validate Field Sample
The ValidateField function is called whenever the user changes the value of a field. This
function returns false to reject the value.
SuiteScript Developer and Reference Guide
Client Scripts
Client SuiteScript Samples
181
Note: This event type does not apply to drop-down or check box fields.
Use the Validate Field 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;
}
Validate Field is Uppercase
This sample uses a validate field function that ensure the value in the field with ID
custrecord_mustbe_uppercase is always set to uppercase.
function validateFieldForceUppercase(type, name)
{
if(name == 'custrecord_mustbe_uppercase')
{
//obtain the upper case value
var upperCase = nlapiGetFieldValue('custrecord_mustbe_uppercase').toUpperCase();
//make sure it hasn't been set
if(upperCase != nlapiGetFieldValue('custrecord_mustbe_uppercase'))
{
nlapiSetFieldValue('custrecord_mustbe_uppercase', upperCase, false);
}
return true;
}
}
Since this function is invoked every time there is an attempt to move the focus way from a field,
the first if block ensures the uppercase logic is executed only for the correct field. Since using
the API nlapiSetFieldValue would also trigger events, the second if block is put in place to
ensure the code will not get into an infinite loop. The final return true statement ensures
the focus can be successfully taken away from the field.
SuiteScript Developer and Reference Guide
Client Scripts
Client SuiteScript Samples
182
Field Changed Sample
The Field Changed function is called when a new value for a field is accepted. Use the Field
Changed 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.");
}
}
SuiteScript Developer and Reference Guide
Chapter 20 User Event Scripts
The following topics are covered in this section. If you are new to user event script, these topics
should be read in order:
•
What Are User Event Scripts?
•
User Event Script Execution
•
Setting the User Event type Argument
•
User Event Script Execution Types
•
How Many User Events Can I Have on One Record?
•
Running a User Event Script in NetSuite
•
User Event Script Samples
What Are User Event Scripts?
User event scripts are executed on the NetSuite server. They are executed when users perform
certain actions on records, such as create, load, update, copy, delete, or submit. Most standard
NetSuite records and custom record types support user event scripts.
Important: User event scripts cannot be triggered to run by other user event scripts. You
can, however, execute a user event script from a call within a scheduled,
portlet, or Suitelet script.
With user event scripts you can do such things as:
•
Implement custom validation on records
•
Enforce user-defined data integrity and business rules
•
Perform user-defined permission checking and record restrictions
•
Implement real-time data synchronization
•
Define custom workflows (redirection and follow-up actions)
•
Implement custom form customizations
Note: To know which standard record types support user event scripts, see SuiteScript
Supported Records in the NetSuite Help Center. If a record supports user event
scripts, an X will appear in the column called “Scriptable in Server SuiteScript”.
SuiteScript Developer and Reference Guide
User Event Scripts
User Event Script Execution
184
Which User Event Types are Available in SuiteScript?
The user events types that are available in scripting are:
•
Before Load – event occurs when a read operation on a record takes place
•
Before Submit – event occurs when a record is submitted, but before the changes are
committed to the database
•
After Submit – event occurs after the changes are committed to the database
See User Event Script Execution Types or specific details on these event types.
Related Topics
•
•
•
•
User Event Script Execution
Setting the User Event type Argument
User Event Script Samples
User Event Best Practices
User Event Script Execution
User events scripts are executed based on operations types defined as: before load, before
submit, and after submit. See the following sections for details:
•
User Event beforeLoad Operations
•
User Event beforeSubmit and afterSubmit Operations
For information on the arguments each user event function takes, see Setting the User Event
type Argument.
User Event beforeLoad Operations
The following steps and diagram provide an overview of what occurs during a before load
operation:
1.
The client sends a read operation request for record data. (The client request can come
from the user interface, Web services or Server SuiteScript calls, CSV imports, or
XML.)
2.
Upon receiving the request, the application server performs basic permission checks
on the client.
3.
The database loads the requested information into the application server for
processing. This is where the before load operation occurs – before the requested data
is returned to the client.
4.
The client receives the now validated/processed before load data.
SuiteScript Developer and Reference Guide
User Event Scripts
User Event Script Execution
185
User Event beforeSubmit and afterSubmit Operations
The following steps and diagram provide an overview of what occurs on submit (after submit
and before submit) operations:
1.
The client performs a write operation by submitting data to the application server.
(The client request can come from the user interface, Web services or Server
SuiteScript calls, CSV imports, or XML.) The application server:
a.
performs basic permission checks on the client
b.
processes the submitted data and performs specified validation checks during a
before submit operation
The submitted data has NOT yet been committed to the database.
2.
Once data has been validated, it is committed to the database.
3.
If this (newly committed) data is then called by an after submit operation, the data is
taken from the database and is sent to the application server for additional processing.
Examples of after submit operations on data that are already committed to the
database include, but are not limited to:
a.
sending email notifications (regarding the data that was committed to the
database)
b.
creating child records (based on the data that was committed to the database)
c.
assigning tasks to employees (based on data that was committed to the database)
SuiteScript Developer and Reference Guide
User Event Scripts
Setting the User Event type Argument
186
Related Topics
•
•
•
•
Setting the User Event type Argument
User Event Script Samples
SuiteScript Functions
Enabling SuiteScript
Setting the User Event type Argument
For User Event scripts, you can associate a script execution context with the type argument of
the script’s function. For example, if you have a script associated with a before load operation
for a given record, and you would like to cause an action only when the record is initially
created, specify create as the script execution type.
Important: The type argument is an auto-generated argument passed by the system.
You can NOT set this as a parameter for a specific deployment like other
function arguments.
//Define the User Event function for a beforeLoad operation.
function beforeLoadSalesOrder(type)
{
var newRecord = nlapiGetNewRecord();
SuiteScript Developer and Reference Guide
User Event Scripts
Setting the User Event type Argument
187
var cutoffRate = custscript_maximumdiscountlevel;
var discountRate = newRecord.getFieldValue('discountrate');
//Define the value of the type argument.
if ( type == 'create' && discountRate != null && discountRate.length > 0
&& cutoffRate != null && cutoffRate.length > 0 )
{
discountRate = Math.abs( parseFloat( discountRate ) );
...remainder of code...
Event type arguments vary depending on whether the event will occur on beforeLoad,
beforeSubmit, or afterSubmit operations. The following table lists the script execution event
types you can use with each operation.
Note: When deploying user event scripts in NetSuite, you can also define a script
execution event type using the Event Type drop-down list on the Script
Deployment page. Be aware that the event type you choose from the drop-down
list will override the type(s) specified in the actual script. For details, see Setting
Script Execution Event Type from the UI. For general information on defining other
deployment parameters for User Event scripts, see Steps for Defining a Script
Deployment.
All of the events have the common type argument which indicates the type of operation that
invoked the event. This argument allows the script code to branch out to different logic
depending on the operation type. For example, a script with “deltree” logic that deletes a record
and all of its child records should only be invoked when type equals to “delete”. It is very
important that user event scripts check the value of the type argument to avoid
indiscriminate execution.
The following sample demonstrates how to check the value of the type argument for each
event. Event types include beforeLoad, beforeSubmit, afterSubmit. (See User Event Script
Execution Types for more details.)
function myBeforeLoadUE(type)
{
if(type == 'create')
{
nlapiLogExecution('DEBUG', 'type argument', 'type is create');
}
if(type == 'view')
{
nlapiLogExecution('DEBUG', 'type argument', 'type is view');
}
if(type == 'edit')
{
nlapiLogExecution('DEBUG', 'type argument', 'type is edit');
SuiteScript Developer and Reference Guide
User Event Scripts
Setting the User Event type Argument
}
}
function myBeforeSubmitUE(type)
{
if(type == 'create')
{
nlapiLogExecution('DEBUG', 'type argument', 'type is create');
}
if(type == 'delete')
{
nlapiLogExecution('DEBUG', 'type argument', 'type is delete');
}
if(type == 'edit')
{
nlapiLogExecution('DEBUG', 'type argument', 'type is edit');
}
if(type == 'cancel')
{
nlapiLogExecution('DEBUG', 'type argument', 'type is cancel');
}
}
function myAfterSubmitUE(type)
{
if(type == 'create')
{
nlapiLogExecution('DEBUG', 'type argument', 'type is create');
}
if(type == 'delete')
{
nlapiLogExecution('DEBUG', 'type argument', 'type is delete');
}
if(type == 'edit')
{
nlapiLogExecution('DEBUG', 'type argument', 'type is edit');
}
if(type == 'approve')
{
nlapiLogExecution('DEBUG', 'type argument', 'type is approve');
}
SuiteScript Developer and Reference Guide
188
User Event Scripts
User Event Script Execution Types
189
}
Note: Logging done with nlapiLogExecution may be classified into 4 types: DEBUG,
AUDIT, ERROR, and EMERGENCY. The source code should correctly set the logging
type. Log type filtering may be set during runtime to give concise and useful
logged information.
After uploading the source code file to the SuiteScript folder in the File Cabinet, a user event
script record is defined by going to Set Up > Customization > Scripts > New > User Event. The
following shows the script record definition page.
User Event Script Execution Types
The following table lists all the execution context types that are supported in each user event
type:
SuiteScript Developer and Reference Guide
User Event Scripts
User Event Script Execution Types
SuiteScript Developer and Reference Guide
190
User Event Scripts
User Event Script Execution Types
191
Operation Type
Execution Event Type
Notes
beforeLoad
type: the read operation type
Event occurs whenever a read operation on a record
occurs. These operations include navigating to a record
in the UI, reading a record in web services, or calling
nlapiLoadRecord.
•
•
•
•
•
•
create
edit
view
copy
print
email
The user-defined function is executed prior to returning
the record or page. The function is passed either the type,
form, or request arguments by the system.
Note: beforeLoad user events cannot be triggered when
you load/access an online form.
form: an nlobjForm object representing
the current form
request: an nlobjRequest object
representing the GET request (Only
available for browser requests.)
SuiteScript Developer and Reference Guide
User Event Scripts
User Event Script Execution Types
Operation Type
Execution Event Type
Notes
beforeSubmit
type: the write operation type
Events on a beforeSubmit operation occur prior to any
write operation on the record. Changes to the current
record at this stage will be persisted during the write
operation.
•
•
•
•
create
•
approve - (only available for certain
record types)
•
reject - (only available for certain
record types)
•
cancel - (only available for certain
record types)
edit
delete
xedit - (see Inline Editing and
SuiteScript)
•
pack- (only available for certain
record types, for example Item
Fulfillment records)
•
ship - (only available for certain
record types, for example Item
Fulfillment records)
•
markcomplete (specify this type for
a beforeSubmit script to execcute
when users click the Mark
Complete link on call and task
records)
•
reassign (specify this type for a
beforeSubmit script to execute
when users click the Grab link on
case records)
•
editforecast (specify this type for a
beforeSubmit script to execute
when users update opportunity
and estimate records using the
Forecast Editor)
192
The beforeSubmit operation is useful for validating the
submitted record, performing any restriction and
permission checks, and performing any last-minute
changes to the current record.
Notes:
•
The approve, cancel, and reject argument types are
only available for record types such as sales orders,
expense reports, timebills, purchase orders, and
return authorizations.
•
Only beforeLoad and afterSubmit user event scripts
will execute on the Message record type when a
message is created by an inbound email case
capture. Scripts set to execute on a beforeSubmit
event will not execute.
Best practices: To set a field on a record or make ANY
changes to a record that is being submitted, do so on a
beforeSubmit operation, NOT an afterSubmit operation.
If you set a field on an afterSubmit, you will be
duplicating a record whose data has already been
committed to the database.
SuiteScript Developer and Reference Guide
User Event Scripts
How Many User Events Can I Have on One Record?
193
Operation Type
Execution Event Type
Notes
afterSubmit
type: the write operation type
Events on an afterSubmit operation occur immediately
following any write operation on a record.
•
•
•
•
create
•
approve - (only available for certain
record types)
•
cancel - (only available for certain
record types)
•
reject - (only available for certain
record types)
Use Case:
•
pack - (only available for certain
record types, for example Item
Fulfillment records)
•
ship - (only available for certain
record types, for example Item
Fulfillment records)
1. Load the record you want to make changes to by
calling the nlapiLoadRecord API. Do NOT load the record
object by using nlapiGetRecord, as this API returns the
record in READ ONLY mode; therefore, changes made to
the record cannot be accepted and an error is thrown.
edit
delete
xedit - (see Inline Editing and
SuiteScript)
•
dropship - (for purchase orders
with items specified as “drop ship”)
•
specialorder - (for purchase orders
with items specified as “special
order”)
•
orderitems - (for purchase orders
with items specified as “order
item”)
•
paybills - (use this type to trigger
afterSubmit user events for Vendor
Payments from the Pay Bill page.
Note that no sublist line item
information will be available . Users
must do a lookup/search to access
line item values.)
The afterSubmit operation is useful for performing any
actions that need to occur following a write operation on
a record. Examples of these actions include email
notification, browser redirect, creation of dependent
records, and synchronization with an external system.
Note: The approve, cancel, and reject argument types are
only available for record types such as sales orders,
expense reports, timebills, purchase orders, and return
authorizations.
Best Practices: Users should be doing post-processing
of the current record on an afterSubmit.
2. After using nlapiLoadRecord to load the record, make
the changes to the record, and submit the record.
For example, if you have a sales order that you want tied
to an estimate, load the sales order record, update it with
any information, and submit it again.
How Many User Events Can I Have on One Record?
There is no limit to the number of user event scripts you can execute on a particular record
type. For example, you could have 10 beforeLoad, 9 beforeSubmit, and 15 afterSubmit
executing functions on a Customer record. However, assigning this many executable functions
to one record type is highly discouraged, as this could negatively affect user experience with
that record type. In other words, if you have 10 beforeLoad scripts that must complete their
execution before a record loads into the browser for the user, this may significantly increase the
time it takes for the record to load. As a consequence, the user’s experience working with the
record will be negatively affected.
SuiteScript Developer and Reference Guide
User Event Scripts
Running a User Event Script in NetSuite
194
Developers who include scripts in their bundles should also be aware of the number of user
events scripts that might already be deployed to records types in the target account. For
example, if 8 beforeSubmit user event scripts are deployed to the Sales Order record in the
target account, and your bundle includes another 7 beforeSubmit user event scripts on the Sales
Order record type, this is 15 beforeSubmit scripts running every time a user clicks Save on the
record. Although all of the scripts will run, the time it takes for the record to actually save may
be significantly increased, again, negatively affecting user experience with the record.
Related Topics
•
•
•
User Event Script Execution
Setting the User Event type Argument
User Event Script Samples
Running a User Event Script in NetSuite
To run a user event script in NetSuite, you must:
1.
Create a JavaScript file for your user event script.
2.
Load the file into NetSuite.
3.
Create a Script record.
4.
Define all runtime options on the Script Deployment page.
If you are new to SuiteScript and need information on each of these steps, see Running Scripts
in NetSuite Overview.
Related Topics
•
•
What Are User Event Scripts?
User Event Script Samples
User Event Script Samples
The following samples are provided in this section:
•
Generating a Record Log
•
Creating Follow-up Phone Call Records for New Customers
•
Enhancing NetSuite Forms with User Event Scripts
SuiteScript Developer and Reference Guide
User Event Scripts
User Event Script Samples
195
Generating a Record Log
This user event script creates an execution log entry containing the type, record type, and
internalId of the current record.
Script:
function beforeLoad(type,form)
{
var newId = nlapiGetRecordId();
var newType = nlapiGetRecordType();
nlapiLogExecution('DEBUG','<Before Load Script> type:'+type+', RecordType: '+newType+', Id:'+newId);
}
function beforeSubmit(type)
{
var newId = nlapiGetRecordId();
var newType = nlapiGetRecordType();
nlapiLogExecution('DEBUG','<Before Submit Script> type:'+type+', RecordType: '+newType+', Id:'+newId);
}
function afterSubmit(type)
{
var newId = nlapiGetRecordId();
var newType = nlapiGetRecordType();
nlapiLogExecution('DEBUG','<After Submit Script> type:'+type+', RecordType: '+newType+', Id:'+newId);
}
Creating Follow-up Phone Call Records for New Customers
A simple CRM use case that could be addressed with user event scripts is creating a follow-up
phone call record for every newly created customer record. The solution is to deploy a script
on the customer record’s after submit event that will create the phone call record. See the
following sample code:
function followUpCall_CustomerAfterSubmit(type)
{
//Only execute the logic if a new customer is created
if(type == 'create')
{
//Obtain a handle to the newly created customer record
var custRec = nlapiGetNewRecord();
if(custRec.getFieldValue('salesrep') != null)
{
//Create a new blank instance of a PhoneCall
var call = nlapiCreateRecord("phonecall");
//Setting the title field on the PhoneCall record
call.setFieldValue('title', 'Make follow-up call to new customer');
//Setting the assigned field to the sales rep of the
//new customer
SuiteScript Developer and Reference Guide
User Event Scripts
User Event Script Samples
196
call.setFieldValue('assigned', custRec.getFieldValue('salesrep'));
//Use the library function to obtain a date object
//that represents tomorrow
var today = new Date();
var tomorrow = nlapiAddDays(today, 1);
call.setFieldValue('startdate', nlapiDateToString(tomorrow));
//Setting the phone field to the phone of the
//new customer
call.setFieldValue('phone', custRec.getFieldValue('phone'));
try
{
//committing the phone call record to the database
var callId = nlapiSubmitRecord(call, true);
nlapiLogExecution('DEBUG', 'call record created successfully', 'ID = ' + callId);
}
catch(e)
{
nlapiLogExecution('ERROR', e.getCode(), e.getDetails());
}
}
}
}
Note: APIs such as nlapiSubmitRecord that access the database should be wrapped
in try-catch blocks.
In the above use case, after submit is a better event to handle the logic than before submit. In
the before submit event, the customer data has not yet been committed to the database. Hence,
putting the phone call logic in the after submit event guarantees there will not be an orphan
phone call record.
Note: During design time, developers should carefully consider in which event to
implement their server logic.
The phone call use case may be further enhanced by redirecting the user to the Phone Call
page once it is created. This is accomplished by putting in redirect logic after the phone call
record is submitted.
try
{
//committing the phone call record to the database
var callId = nlapiSubmitRecord(call, true);
nlapiLogExecution('DEBUG', 'call record created successfully', 'ID = ' + callId);
SuiteScript Developer and Reference Guide
User Event Scripts
User Event Script Samples
197
//Redirect the user to the newly created phone call
nlapiSetRedirectURL('RECORD', 'phonecall', callId, false, null);
}
catch(e)
{
nlapiLogExecution('ERROR', e.getCode(), e.getDetails());
}
User event scripts are not only triggered as a result of user actions carried out through the
browser, they are also triggered by other means as well (for example, CSV, Web Services, offline
client).
Examples:
•
Using CSV to import records triggers before submit and after submit events
•
Using the SuiteTalk “GET” operation to retrieve an existing record would trigger its
before load event.
Sometimes these events invoke scripts not designed to be executed in that manner and create
undesirable results. To prevent a script from getting executed by the wrong execution context,
use the nlobjContext object as a filter.
For example, in order to ensure a before load user event script is executed only when a record is
created using the browser interface, the script must check both the type argument and the
execution context as (as shown below):
function myBeforeLoadUE(type)
{
//obtain the context object
var context = nlapiGetContext();
if(type == 'create' && context.getExecutionContext == 'userinterface')
{
Note that the API nlapiGetContext() is not exclusive to user event scripts. It can also be used in
Client Scripts and Suitelets.
Note: The nlobjContext object provides metadata of the script’s context. Use this
information to help implement fine-grained control logic in SuiteScript.
Enhancing NetSuite Forms with User Event Scripts
Another common use of user event scripts is to dynamically customize or enhance entry forms
and transactions forms. This approach gives NetSuite forms the ability to customize themselves
in runtime – something that cannot be done with pre-configured, roles-based forms.
SuiteScript Developer and Reference Guide
User Event Scripts
User Event Script Samples
198
In NetSuite, entry forms and transaction forms are customized by administrators. The
placement of UI elements (fields, tabs, sublists) on a form can be arranged, or be made inline or
hidden depending on the business needs of the end users. Multiple forms can be created for a
record type and assigned to specific roles. Typically this kind of customization is done during
design time. Custom forms are confined to specific roles and do not allow for a lot of runtime
customization. A user event script on a record’s before load event can provide flexibility to
runtime customization.
Note: For more specific information about NetSuite entry forms and transaction forms,
see Custom Forms in the NetSuite Help Center.
The key to using user event scripts to customize a form during runtime is a second argument
named form in the before load event. This optional argument is the reference to the entry/
transaction form. Developers can use this to dynamically change existing UI elements, or add
new ones. The UI elements are added using the UI Objects API.
A use case for this scripting capability could be the following:
To improve month-end sales, a company introduces an end-of-month promotion that is only
active for the last five days of the month. All sales order forms must have a custom field called
“Eligible EOM Promotion” on the last five days of the month.
The following is a sample user event script that is meant to be deployed on the before load
event of the sales order record.
/*****************************************************
* This function is a module to implement at end of
* month (last 5 days of month) promotion for sales
* orders. It is meant to be deployed on the before
* load event of the sales order record.
*/
function customizeUI_SalesOrderBeforeLoad(type, form)
{
var currentContext = nlapiGetContext();
//Execute the logic only when creating a sales order with the browser UI
if(type == 'create' && currentContext.getExecutionContext() == 'userinterface')
{
var fieldId = 'custpage_eom_promotion';
var fieldLabel = 'Eligible EOM promotion';
var today = new Date();
var month = today.getMonth();
var date = today.getDate();
nlapiLogExecution('DEBUG', 'month date', month + ' ' + date);
//February
if(month==1)
{
if( date==24 | date==25 | date==26 | date==27 | date==28 | date==29)
form.addField(fieldId, 'checkbox', fieldLabel);
}
//31-day months
else if(month==0 | month==2 | month ==4 | month==6 | month==7 | month==9 | month==11)
SuiteScript Developer and Reference Guide
User Event Scripts
User Event Script Samples
199
{
if( date==27 | date==28 | date==29 | date==30 | date==31)
form.addField(fieldId, 'checkbox', fieldLabel);
}
//30-day months
else
{
if( date==26 | date==27 | date==28 | date==29 | date==30)
form.addField(fieldId, 'checkbox', fieldLabel);
}
}
}
When the script is deployed, all sales order forms will have the Eligible EOM Promotion
checkbox only during the last five days of the month as shown below.
Note that since these UI elements are created dynamically, they are superficial and do not have
supporting backend data models. There is a disconnect between the UI and backend data,
hence the script-created fields’ values will not be saved.
UI elements (such as the Eligible EOM promotion field) created with user event scripts and
SuiteScript Objects are scriptable by client script APIs. A remedy to the disconnect problem is
linking the script-created field to a real field (with backend data support) via a client script. The
value of the real field, which might be made hidden or inline on the form definition, is driven
by the value entered in the script-created field. As a result, the real fields are populated and the
data is saved.
SuiteScript Developer and Reference Guide
User Event Scripts
User Event Script Samples
Related Topics
•
•
•
What Are User Event Scripts?
User Event Script Execution
Setting the User Event type Argument
SuiteScript Developer and Reference Guide
200
Chapter 21 Suitelets
The following topics are covered in this section. If you are not familiar with Suitelets, these
topics should be read in order.
•
What Are Suitelets?
•
Suitelet Script Execution
•
Building Custom Workflows with Suitelets
•
Building Suitelets with UI Objects
•
Backend Suitelets
•
Restricted Parameters in Suitelet URLs
•
SuiteScript and Externally Available Suitelets
•
Running a Suitelet in NetSuite
•
Suitelets Samples
SuiteScript Developer and Reference Guide
Suitelets
What Are Suitelets?
202
What Are Suitelets?
Suitelets are extensions of the SuiteScript API that give developers the ability to build custom
NetSuite pages and backend logic. Suitelets are server-side scripts that operate in a requestresponse model. They are invoked by HTTP GET or POST requests to system generated URLs.
Shown below are screenshots of a simple Suitelet with a few fields. The Suitelet is invoked by
making a GET request from the browser. Notice that this Suitelet is built with SuiteScript UI
Objects, which encapsulate scriptable interface components that have a NetSuite look-and-feel.
Once a Suitelet has been deployed, developers can create NetSuite tasklinks to these scripts,
which can then be used to customize existing NetSuite centers.
When the Submit button is clicked, the same Suitelet is invoked again with a HTTP POST
event. The values entered in the previous screen are displayed in inline (read-only) mode.
Below is the source code for this Suitelet. It is executed on the server, which generates HTML
and sends it to the browser.
function gettingStartedSuitelet(request, response)
{
if(request.getMethod() == 'GET')
{
//Create the form and add fields to it
var form = nlapiCreateForm("Suitelet - GET call");
form.addField('custpage_field1', 'text', 'Text Field').setDefaultValue('This is a text field');
form.addField('custpage_field2', 'integer', 'Integer Field').setDefaultValue(10);
SuiteScript Developer and Reference Guide
Suitelets
Suitelet Script Execution
203
form.addField('custpage_field3', 'select', 'Select Field', 'customer');
form.addSubmitButton('Submit');
response.writePage(form);
}
//POST call
else
{
var form = nlapiCreateForm("Suitelet - POST call");
//create the fields on the form and populate them with values from the previous screen
var resultField1 = form.addField('custpage_res1', 'text', 'Text Field value entered: ');
resultField1.setDefaultValue(request.getParameter('custpage_field1'));
resultField1.setDisplayType('inline');
var resultField2 = form.addField('custpage_res2', 'integer', 'Integer Field value entered: ');
resultField2.setDefaultValue(request.getParameter('custpage_field2'));
resultField2.setDisplayType('inline');
var resultField3 = form.addField('custpage_res3', 'select', 'Select Field value entered: ', 'customer');
resultField3.setDefaultValue(request.getParameter('custpage_field3'));
resultField3.setDisplayType('inline');
response.writePage(form);
}
}
The entry point of the function has two mandatory arguments: request and response.
These arguments are instances of nlobjRequest and nlobjResponse, respectively.
Typically, invoking a Suitelet via a browser would make a HTTP GET call. The type of HTTP
call is determined by the nlobjRequest.getMethod() API. The code creates an nlobjForm
object and populates it with SuiteScript UI Objects. The populated form is sent to the
response object via the nlobjResponse.writePage(pageobject) API.
When the user clicks the Submit button, an HTTP POST call is made. The code’s else block
obtains the values entered in the first page from the request object and populates them into
another nlobjForm object and sends it to response.writePage(pageobject).
Note: Client side alerts are not supported in Suitelets, as Suitelets are considered to be
“server side” SuiteScripts. The following snippet will run in client SuiteScripts,
however, it will not run if the script is a Suitelet:
function alert_test ()
{
alert('Hello World');
}
Suitelet Script Execution
SuiteScript Developer and Reference Guide
Suitelets
Suitelet Script Execution
204
The following steps and diagram provide an overview of the Suitelet execution process:
1.
Client initiates an HTTP GET or POST request (typically from a browser) for a
system-generated URL. A web request object (nlobjRequest) contains the data from
the client's request.
2.
The user's script is invoked, which gives the user access to the entire Server SuiteScript
API as well as a web request and web response object.
3.
NetSuite processes the user's script and returns a web response object (nlobjResponse)
to the client. The response can be in following forms:
• Free-form text
• HTML
• RSS
• XML
• A browser redirect to another page on the Internet
Important: You can only redirect to external URLs from Suitelets that are accessed
externally (in other words, the Suitelet has been designated as “Available Without
Login” and is accessed from its external URL).
• A browser redirect to an internal NetSuite page. The NetSuite page can be either a
standard page or custom page that has been dynamically generated using UI
Objects.
4.
The data renders in the user’s browser.
Note: Suitelets can support up to 50 concurrent connections from a single user login.
Note that any concurrent RESTlet connections also count towards this limit.
SuiteScript Developer and Reference Guide
Suitelets
Building Custom Workflows with Suitelets
205
Building Custom Workflows with Suitelets
With the user event scripts, Suitelets, and UI Objects, SuiteScript developers can create custom
workflows by chaining together standard and/or custom NetSuite pages. These workflows may
be complemented by custom backend logic.
The following diagram shows how a SuiteScript developer can potentially create a workflow
that starts of with either a standard or custom NetSuite record, then redirects to a Suitelet, then
redirects to either another Suitelet or standard/custom NetSuite record, all depending on the
logic of the developer’s application.
Related Topics
•
•
•
Suitelet Script Execution
Suitelets Samples
UI Objects
Building Suitelets with UI Objects
When building Suitelets, developers can use SuiteScript UI Objects to create custom pages that
look like NetSuite pages. SuiteScript UI objects encapsulate the elements for building NetSuitelooking portlets, forms, fields, sublists, tabs, lists, and columns.
When developing a Suitelet with UI objects, you can also add custom fields with inline HTML.
Important: When adding UI elements to an existing NetSuite page, you must prefix the
object name with custpage. This minimizes the occurrence of field/object
name conflicts. For example, when adding a custom tab to an entry form, the
name should follow a convention similar to custpagecustomtab or
custpagemytab.
The figure below shows a custom interface that has been built with the following SuiteScript UI
objects:
•
nlobjForm
SuiteScript Developer and Reference Guide
Suitelets
Backend Suitelets
•
nlobjTab
•
nlobjSubList
•
nlobjField
206
Note that a custom menu link was created to access the Suitelet. In this figure, the Configure
System Suitelet can be accessed by going to Customers > Custom > Configure System. For
information on creating menu links for Suitelets, see Running a Suitelet in NetSuite.
Related Topics
•
•
•
Suitelet Script Execution
Suitelets Samples
UI Objects
Backend Suitelets
Suitelets give developers the ability to build custom NetSuite pages. However, developers can
create Suitelets that do not generate any UI elements. These kinds of Suitelets are referred to as
backend Suitelets. Their sole purpose is to execute backend logic, which can then be parsed by
other parts of a custom application.
Just like a Suitelet that builds NetSuite pages, a backend Suitelet is invoked by making HTTP
GET or POST calls to a NetSuite-generated Suitelet URL.
SuiteScript Developer and Reference Guide
Suitelets
Backend Suitelets
207
The following are good uses of backend Suitelets:
•
Providing a service for backend logic to other SuiteScripts, or to other external hosts
outside of NetSuite
•
Offloading server logic from client scripts to a backend Suitelet shipped without
source code to protect sensitive intellectual property
Important: RESTlets can provide an alternative to backend Suitelets. For general
information about this type of script, see RESTlets. For a comparison, see
RESTlets Compared to Suitelets.
A use case of a backend Suitelet is a service that provides customer information based on a
phone number. The following is the code for a Suitelet that returns customer entity IDs (for
records with matching phone numbers) separated by the | character.
/***********************************************
* This function searches for customer records
* that match a supplied parameter custparam_phone
* and return the results in a string separated
* by the | character.
*/
function lookupPhoneBackendSuitelet(request, response)
{
if(request.getMethod() == 'GET')
{
//null check on the required parameter
if(request.getParameter('custparam_phone') != null)
{
//Setting up the filters and columns
var filters = new Array();
var columns = new Array();
//Use the supplied custparam_phone value as filter
filters[0] = new nlobjSearchFilter('phone', null, 'is', request.getParameter('custparam_phone'));
columns[0] = new nlobjSearchColumn('entityid', null, null);
//Search for customer records that match the filters
var results = nlapiSearchRecord('customer', null, filters, columns);
if(results != null)
{
var resultString = '';
//Loop through the results
for(var i = 0; i < results.length; i++)
{
//constructing the result string
var result = results[i];
resultString = resultString + result.getValue('entityid');
//adding the | seperator
if (i != parseInt(results.length - 1))
{
resultString = resultString + '|';
SuiteScript Developer and Reference Guide
Suitelets
Restricted Parameters in Suitelet URLs
208
}
nlapiLogExecution('DEBUG', 'resultString', resultString);
}
response.write(resultString);
}
else
{
response.write('none found');
}
}
}
}
Notice that this Suitelet does not use any UI Object APIs. Communication with the Suitelet is
done strictly with the request and response objects. NetSuite generates a URL to invoke
this Suitelet. To correctly invoke it, the custparam_phone value (bold) needs to be appended at
the end of the invoking URL:
https://system.netsuite.com/app/site/hosting/
scriptlet.nl?script=6&deploy=1&custparam_phone=(123)-456-7890
The code that calls this backend Suitelet needs to do the following:
1.
Use nlapiResolveURL to dynamically obtain the invoking URL
2.
Supply required parameters
3.
Process the returned results
Note: Backend Suitelets should not be used to get around SuiteScript usage governance.
Suitelets designed with this intention are considered abusive by NetSuite.
Related Topics
•
•
•
Suitelet Script Execution
Suitelets Samples
UI Objects
Restricted Parameters in Suitelet URLs
There are cetain URL parameters that are reserved, and users should not use them when
creating custom parameters for their Suitelet URLs. For example, the following URL includes a
custom parameter called id.
https://.../site/hosting/scriptlet.nl?script=44&deploy=3&id=500
In this case, accessing a Suitelet using a URL that includes a custom id parameter throws an
error if you try to build a NetSuite entry form using the nlapiCreateForm function. The
following tables provides a list of reserved parameters:
SuiteScript Developer and Reference Guide
Suitelets
SuiteScript and Externally Available Suitelets
209
Reserved Suitelet URL Parameters
e
print
id
email
cp
q
l
si
popup
st
s
r
d
displayonly
_nodrop
nodisplay
sc
deploy
sticky
script
If you include any of these URL parameters you may get an error saying "There are no records
of this type." To avoid naming conflicts, NetSuite recommends that all custom URL parameters
are prefixed with custom (for example custom_id).
SuiteScript and Externally Available Suitelets
Only a subset of the SuiteScript API is supported in externally available Suitelets (Suitelets set
to Available Without Login on the Script Deployment page). For a list of these APIs, in the
NetSuite Help Center see these topics related to online forms.
•
Working with Online Forms
•
Why are only certain APIs supported on online forms?
Note: The same concepts that apply to online forms also apply to externally available
Suitelets.
Note that if you want to use all available SuiteScript APIs in a Suitelet, your Suitelet will require
a valid NetSuite session. (A valid session means that users have authenticated to NetSuite by
providing their email address and password.)
On the Script Deployment page, leave the Available Without Login check box unselected if you
want to deploy a Suitelet that requires a valid session. (See also Setting Available Without Login
for more information on this runtime option.)
SuiteScript Developer and Reference Guide
Suitelets
Running a Suitelet in NetSuite
210
Important: UI Objects can be used without a valid session. Therefore, they are
supported in externally available Suitelets.
Running a Suitelet in NetSuite
To run a Suitelet in NetSuite, you must:
1.
Create a JavaScript file for your Suitelet.
2.
Load the file into NetSuite.
3.
Create a Script record.
4.
Define all runtime options on the Script Deployment page.
If you are new to SuiteScript and need information on each of these steps, see Running Scripts
in NetSuite Overview.
Note that if you want users to be able to access/launch a Suitelet from the UI, you can create a
menu item for the Suitelet.
The following figure shows the Links tab on the Script Deployment page for a Suitelet. Select
the Center where the link to the Suitelet will be accessible (for example, Customer Center,
Vendor Center, etc). Next, set the Section (top-level menu tab) in the Center, then choose a
category under the section. Finally, create a UI label for the link. Be sure to click Add when
finished.
Note: The Classic Center is a default center. It is not specific to customers, partners, or
vendors.
When the Script Deployment page is saved, a link to the Suitelet appears (see figure).
SuiteScript Developer and Reference Guide
Suitelets
Suitelets Samples
Related Topics
•
•
•
Suitelets Samples
UI Objects
Suitelets and UI Object Best Practices
Suitelets Samples
The following sample Suitelets show how to return HTML and XML documents, embed in
iFrame, as well as how to create simple forms and lists.
•
Writing Your First Suitelet
•
Return a Simple XML Document
•
Create a Simple Form
•
Create a Simple List
•
Add a Suitelet to a Tab
•
Create a Suitelet Email Form
•
Create a Form with a URL Field
•
Create a Form with Embedded Inline HTML
•
Embed a Suitelet in iFrame
SuiteScript Developer and Reference Guide
211
Suitelets
Suitelets Samples
Writing Your First Suitelet
This simple Hello World! sample shows how to return an HTML document in a Suitelet.
Script:
function demoHTML(request, response)
{
var html = '<html><body><h1>Hello World</h1></body></html>';
response.write( html );
//prefix header with Custom-Header. See nlobjResponse.setHeader(name, value)
response.setHeader('Custom-Header-Demo', 'Demo');
}
Return a Simple XML Document
Script:
function demoXML(request, response)
{
var xml = '<?xml version="1.0" encoding="utf-8" ?>'+
'<message>'+'Hello World'+'</message>';
response.write( xml );
response.setHeader('Custom-Header-Demo', 'Demo');
}
SuiteScript Developer and Reference Guide
212
Suitelets
Suitelets Samples
213
Create a Simple Form
This form is generated using the nlobjForm UI object. Note that Suitelets built with the
SuiteScript UI Objects API can be accessed without a valid session. In other words, Suitelets
using UI objects can be set to Available Without Login on the Script Deployment page. (For
information on deploying scripts, see Step 5: Define Script Deployment.)
Script:
function demoSimpleForm(request, response)
{
if ( request.getMethod() == 'GET' )
{
var form = nlapiCreateForm('Simple Form');
var field = form.addField('textfield','text', 'Text');
field.setLayoutType('normal', 'startcol')
form.addField('datefield','date', 'Date');
form.addField('currencyfield','currency', 'Currency');
form.addField('textareafield','textarea', 'Textarea');
var select = form.addField('selectfield','select', 'Select');
select.addSelectOption('','');
select.addSelectOption('a', 'Albert');
select.addSelectOption('b', 'Baron');
select.addSelectOption('c', 'Chris');
select.addSelectOption('d', 'Drake');
select.addSelectOption('e', 'Edgar');
var sublist = form.addSubList('sublist','inlineeditor', 'Inline Editor Sublist');
sublist.addField('sublist1', 'date', 'Date');
sublist.addField('sublist2', 'text', 'Text');
sublist.addField('sublist3', 'currency', 'Currency');
sublist.addField('sublist4', 'textarea', 'Large Text');
sublist.addField('sublist5', 'float', 'Float');
form.addSubmitButton('Submit');
response.writePage( form );
SuiteScript Developer and Reference Guide
Suitelets
Suitelets Samples
214
}
else
dumpResponse(request,response);
}
Create a Simple List
This list is generated using the nlobjList UI object. Note that Suitelets built with the UI Objects
API can be accessed without a valid session. In other words, Suitelets using UI objects can be
set to Available Without Login on the Script Deployment page. (For information on deploying
scripts, see Step 5: Define Script Deployment.)
Important: If your browser is inserting scroll bars in this code sample, maximize your
browser window, or expand the main frame that this sample appears in.
Script:
function demoList(request, response)
{
var list = nlapiCreateList('Simple List');
// You can set the style of the list to grid, report, plain, or normal, or you can get the
// default list style that users currently have specified in their accounts.
list.setStyle(request.getParameter('style'));
var column = list.addColumn('number', 'text', 'Number', 'left');
column.setURL(nlapiResolveURL('RECORD','salesorder'));
column.addParamToURL('id','id', true);
list.addColumn('trandate', 'date', 'Date', 'left');
list.addColumn('name_display', 'text', 'Customer', 'left');
list.addColumn('salesrep_display', 'text', 'Sales Rep', 'left');
SuiteScript Developer and Reference Guide
Suitelets
Suitelets Samples
215
list.addColumn('amount', 'currency', 'Amount', 'right');
var returncols = new Array();
returncols[0] = new nlobjSearchColumn('trandate');
returncols[1] = new nlobjSearchColumn('number');
returncols[2] = new nlobjSearchColumn('name');
returncols[3] = new nlobjSearchColumn('salesrep');
returncols[4] = new nlobjSearchColumn('amount');
var results = nlapiSearchRecord('estimate', null, new nlobjSearchFilter('mainline',null,'is','T'), returncols);
list.addRows( results );
list.addPageLink('crosslink', 'Create Phone Call', nlapiResolveURL('TASKLINK','EDIT_CALL'));
list.addPageLink('crosslink', 'Create Sales Order',
nlapiResolveURL('TASKLINK','EDIT_TRAN_SALESORD'));
list.addButton('custombutton', 'Simple Button', ''alert('Hello World')'');
response.writePage( list );
}
Add a Suitelet to a Tab
[UE=HELP_TOPIC_OUT_OF_DATE_ALERT=UE]
The following user event script shows how to add a tab to a record, and then on the tab, add a
Suitelet. In this example a tab called Sample Tab is added to a Case record. A link is added to
the Sample Tab that, when clicked, opens a Suitelet.
SuiteScript Developer and Reference Guide
Suitelets
Suitelets Samples
Important: If your browser is inserting scroll bars in this code sample, maximize your
browser window, or expand the main frame that this sample appears in.
Script:
/*Create a user event beforeLoad function that takes type and form as parameters.
*Later you will define the script execution context by providing a value for type.
*The form argument instantiates a SuiteScript nlobjForm object, which allows you
*to add fields and sublists later on in the script.
*/
function beforeLoadTab(type, form)
{
var currentContext = nlapiGetContext();
var currentUserID = currentContext.getUser();
/*Define the value of the type argument. If the Case record is edited or viewed,
*a tab called Sample Tab is added. Note that the script execution context is set to
*userinterface. This ensures that this script is ONLY invoked from a user event
*occurring through the UI.
*/
if( (currentContext.getExecutionContext() == 'userinterface') && (type == 'edit' | type == 'view'))
{
var SampleTab = form.addTab('custpage_sample_tab', 'SampleTab');
//On Sample Tab, create a field of type inlinehtml.
var createNewReqLink = form.addField('custpage_new_req_link','inlinehtml', null, null,
'custpage_sample_tab');
//Define the parameters of the Suitelet that will be executed.
var linkURL = nlapiResolveURL('SUITELET', 'customscript12','customdeploy1', null)
+ '&customerid=' + nlapiGetRecordId();
//Create a link to launch the Suitelet.
createNewReqLink.setDefaultValue('<B>Click <A HREF="' + linkURL +'">here</A> to
create a new document signature request record.</B>');
//Add a sublist to Sample Tab.
var signatureRequestSublist = form.addSubList('custpage_sig_req_sublist',
'list', 'Document Signature Requests','custpage_sample_tab');
signatureRequestSublist.addField('custpage_req_name', 'text', 'Name');
signatureRequestSublist.addField('custpage_req_status', 'text', 'Status');
signatureRequestSublist.addField('custpage_req_created', 'date', 'Date
Created');
}
}
SuiteScript Developer and Reference Guide
216
Suitelets
Suitelets Samples
Create a Suitelet Email Form
The following sample shows how to create a Suitelet form to email the results.
Script:
/**
* A simple Suitelet for building an email form and sending out an email
* from the current user to the recipient email address specified on the form.
*/
function simpleEmailForm(request, response)
{
if ( request.getMethod() == 'GET' )
{
var form = nlapiCreateForm('Email Form');
var subject = form.addField('subject','text', 'Subject');
subject.setLayoutType('normal','startcol')
subject.setMandatory( true );
var recipient = form.addField('recipient','email', 'Recipient email');
recipient.setMandatory( true );
var message = form.addField('message','textarea', 'Message');
message.setDisplaySize( 60, 10 );
form.addSubmitButton('Send Email');
}
else
{
var currentuser = nlapiGetUser();
var subject = request.getParameter('subject')
var recipient = request.getParameter('recipient')
var message = request.getParameter('message')
nlapiSendEmail(currentuser, recipient, subject, message);
SuiteScript Developer and Reference Guide
217
Suitelets
Suitelets Samples
218
}
}
Create a Form with a URL Field
This example shows how to add a URL field to a simple form. In this example, when the URL is
clicked the user will be redirected to the New Employee record.
Several methods of nlobjField are used to change the displayed field to the correct parameters.
The address called is built from the system address plus the address of the tasklink (in this case
the New Employee form) which is retrieved using nlapiResolveURL(type, identifier, id,
displayMode).
Note: You need to specify ‘https://’ if the destination link is accessible via an authenticated
NetSuite session.
Script:
function SimpleFormWithUrl(request, response)
{
if ( request.getMethod() == 'GET' )
{
var form = nlapiCreateForm('Simple Form');
var field = form.addField('textfield','text', 'Text');
field.setLayoutType('normal', 'startcol');
form.addField('datefield','date', 'Date');
form.addField('currencyfield','currency', 'Currency');
form.addField('textareafield','textarea', 'Textarea');
form.addField("enterempslink", "url", "", null, "enteremps" ).setDisplayType( "inline" ).setLinkText( "Click
Here to Enter Employee Records").setDefaultValue( "https://system.netsuite.com" + nlapiResolveURL(
'tasklink', 'EDIT_EMPLOYEE') );
form.addSubmitButton('Submit');
response.writePage( form );
}
else
dumpResponse(request,response);
}
SuiteScript Developer and Reference Guide
Suitelets
Suitelets Samples
219
Create a Form with Embedded Inline HTML
Here is another “Hello World” example, but this time using Inline HTML which is embedded
in a NetSuite form. A field is added with the nlobjForm.addField method of the type
‘inlinehtml’, and the nlobjField.setDefaultValue method is used to provide the HTML code.
Script:
function HelloWorldInlineHTML(request,response)
{
var form = nlapiCreateForm('My Form', false);
var myInlineHtml = form.addField( 'custpage_btn', 'inlinehtml');
myInlineHtml.setDefaultValue("<html><body><h1>Hello World</h1></body></html>");
response.writePage(form);
}
SuiteScript Developer and Reference Guide
Suitelets
Suitelets Samples
220
Embed a Suitelet in iFrame
This sample shows how to embed a Suitelet in iFrame, through its external URL. You need to
append ifrmcntnr=T to the external URL of your Suitelet deployment.
Note: This is the recommended approach especially when you are using Firefox as the
browser to render your HTML page.
Script:
function EmbediniFrame(request, response)
{
var form = nlapiCreateForm("", true);
var stateSelect = form.addField("custpage_state", "select", "State", null);
stateSelect.setMandatory(true);
stateSelect.addSelectOption("AL", "Alabama");
stateSelect.addSelectOption("AK", "Alaska");
var submitButton = form.addSubmitButton("Okay!");
response.writePage(form);
}
During script deployment, make sure to do the following:
SuiteScript Developer and Reference Guide
Suitelets
Suitelets Samples
•
Set the status to Released
•
Select Available Without Login
•
Set Audience to All Roles and All Employees
221
For more information about deploying a script, see Step 5: Define Script Deployment.
Next, you need to create the HTML file where you will embed your Suitelet in iFrame using the
external URL of your script deployment. Note how ifrmcntnr=T is appended to the external
URL.
HTML:
<html>
<head></head>
<body>
<iframe src="https://forms.netsuite.com/app/site/hosting/
scriptlet.nl?script=207&deploy=1&compid=563214&h=cfdf4a34a46c39a0f3d2&ifrmcntnr=T"/>
</body>
</html>
Loading the HTML file in your browser (such as Firefox) renders the following output:
SuiteScript Developer and Reference Guide
Chapter 22 RESTlets
REST is an acronym for Representational State Transfer, a style of software architecture that
focuses on representation and resources. A design that conforms to the constraints of REST is
described as RESTful. A description of these constraints and of general REST principles is
available at http://en.wikipedia.org/wiki/Representational_State_Transfer.
RESTlets, a new type of server SuiteScript, expose the power of the SuiteScript interface to
REST and allow access to a REST-based Web services API. This new API is a lightweight,
flexible, and standards-based framework that provides an alternative to SOAP-based Web
services. Developers can use RESTlets to define custom RESTful integrations with NetSuite.
RESTful Web services can support a significant expansion of supported behaviors over
NetSuite’s SOAP-based Web services, which are limited to those defined as SuiteTalk
operations. RESTful Web services also can enhance usability and performance over SuiteTalk.
In addition, RESTlets are more secure than Suitelets, which are made available to users without
login.
RESTlets provide the following additional benefits:
•
Support of stateless requests and responses between client and server
•
Built-in authentication using user credentials in HTTP header
•
Ease of adoption for developers familiar with SuiteScript
•
Control over both client and server implementation
•
Suitability for development of: mobile clients on platforms such as iPhone and
Android, integration of external Web-based applications such as Gmail or other
Google Apps, and backends for Suitelet-based user interfaces.
For details about working with RESTlets, see:
•
What Are RESTlets?
•
RESTlets vs. Other NetSuite Integration Options
•
Creating a RESTlet
•
Debugging a RESTlet
•
Sample RESTlet Code
•
Sample RESTlet Input Formats
•
RESTlet Status Codes and Error Message Formats
RESTlets Guide
RESTlets
Related Topics
•
•
•
•
Script Types Overview
Suitelets
What is SuiteScript?
SuiteTalk Platform Overview
RESTlets Guide
223
RESTlets
What Are RESTlets?
224
What Are RESTlets?
RESTlets are a form of Web services integration. Each RESTlet is a server-side script that
operates in a request-response model, and is invoked by an HTTP request to a systemgenerated URL.
RESTlets follow the principles of the REST architectural style and use HTTP. They use HTTP
verbs, HTTP headers, HTTP status codes, URLs, and standard data formats.
RESTlets support the entire SuiteScript API and general SuiteScript features such as
debugging. For general information about SuiteScript, see the SuiteScript help in the NetSuite
Help Center.
The following topics provide details specific to the RESTlet type of script:
•
RESTlet Script Execution
•
Authentication for RESTlets
•
RESTlet URL and Domain
•
Using the REST roles Service to Get User Accounts, Roles, and Domains
•
Supported Input and Output Content Types for RESTlets
•
Supported Functions for RESTlets
•
RESTlet Governance and Session Management
•
RESTlet Debugging
•
RESTlet Error Handling
Related Topics
•
•
•
•
•
•
•
•
•
•
•
RESTlets
RESTlets vs. Other NetSuite Integration Options
Creating a RESTlet
Debugging a RESTlet
Sample RESTlet Code
Sample RESTlet Input Formats
RESTlet Status Codes and Error Message Formats
SuiteScript - The Basics
SuiteScript Governance
Debugging SuiteScript
Error Handling APIs
RESTlet Script Execution
The following steps provide an overview of the RESTlet execution process:
RESTlets Guide
RESTlets
What Are RESTlets?
225
1.
A client initiates an HTTP request for a system-generated URL. This request can come
from an external client or from a client hosted by NetSuite.
2.
The sender of the HTTP request is authenticated either through request-level
credentials passed by the NetSuite-specific method NLAuth, or through a check for an
existing NetSuite session.
• For an externally hosted client, request-level credentials are required.
• For a NetSuite-hosted client, the existing NetSuite session is reused.
See Authentication for RESTlets.
3.
The RESTlet script is invoked, providing access to the server SuiteScript API.
4.
A string, or an object that has been deserialized according to a predefined
specification, is passed in to the RESTlet. See Supported Input and Output Content
Types for RESTlets.
5.
The RESTlet interrogates the string or object, and can perform any of the full range of
SuiteScript actions.
6.
The RESTlet returns results as a string or a serialized object.
Important: The URL used to invoke a RESTlet varies according to whether the RESTlet
client is externally hosted or hosted by NetSuite. See RESTlet URL and
Domain.
Related Topics
•
•
•
•
•
•
•
•
Authentication for RESTlets
RESTlet URL and Domain
Using the REST roles Service to Get User Accounts, Roles, and Domains
Supported Input and Output Content Types for RESTlets
Supported Functions for RESTlets
RESTlet Governance and Session Management
RESTlet Debugging
RESTlet Error Handling
Authentication for RESTlets
Authentication is required for RESTlets. All calls to RESTlets are processed synchronously and
RESTlets support a high number of concurrent requests, so the same credentials can be reused.
The way to provide login credentials for a RESTlet varies according to whether the RESTlet is
called from an external client or from a client hosted by NetSuite, such as a client SuiteScript.
•
For a RESTlet called from an external client, you need to use the NetSuite-specific
method NLAuth in the HTTP Authorization header to pass in NetSuite login
credentials such as company ID, user name, password, and role. See Using NLAuth in
the Authorization Header.
RESTlets Guide
RESTlets
What Are RESTlets?
•
226
For a RESTlet called from a client hosted by NetSuite, you do not need to pass
authentication information in the HTTP request. A check for a valid NetSuite session
occurs, and this existing session is reused.
Using NLAuth in the Authorization Header
NLAuth passes in the following login credentials:
•
nlauth_account - NetSuite company ID (optional)
•
nlauth_email - NetSuite user name (required)
•
nlauth_signature - NetSuite password (required)
•
nlauth_role - internal ID of the role used to log in to NetSuite (optional)
Note: If a user has a default role defined, this role can be used for login when the role
parameter is not passed in the authorization header.
Authorization Header Formatting
The Authorization header should be formatted as:
NLAuth<space><comma-separated parameters>.
For example:
Authorization: NLAuth nlauth_account=123456, nlauth_email=jsmith@ABC.com,
nlauth_signature=xxxxxxxx, nlauth_role=41
Important: NetSuite provides a REST roles service that you can use to determine a user’s
account and role. This service makes it possible to support RESTlet login
when account and role are unknown, for example, in mobile applications.
See Using the REST roles Service to Get User Accounts, Roles, and Domains.
Related Topics
•
•
•
•
•
•
•
•
RESTlet Script Execution
RESTlet URL and Domain
Using the REST roles Service to Get User Accounts, Roles, and Domains
Supported Input and Output Content Types for RESTlets
Supported Functions for RESTlets
RESTlet Governance and Session Management
RESTlet Debugging
RESTlet Error Handling
RESTlet URL and Domain
The URL used for a RESTlet HTTP request varies according to whether the RESTlet is called
from an external client or from a client hosted by NetSuite.
RESTlets Guide
RESTlets
What Are RESTlets?
•
227
For a RESTlet called from an external client, the URL needs to include the domain
https://rest.netsuite.com, which has been created to support RESTlets.
In this case, you receive an error if you attempt to use another domain.
Important: As of September 2012, NetSuite began hosting new customer accounts in
multiple data centers. As a result, the domain used for external client RESTlet
access to NetSuite may vary per customer account. Currently, this domain
could be https://rest.netsuite.com or https://rest.na1.netsuite.com. NetSuite
provides a service that you can use to dynamically discover the correct
domain. See Using the REST roles Service to Get User Accounts, Roles, and
Domains.
•
For a RESTlet called from a client hosted by NetSuite, the URL should be a relative
URL that does not include the domain.
In this case, the RESTlet uses the https://system.netsuite.com domain because that is
the domain used in the client session reused by the RESTlet.
The following RESTlet deployment record shows examples of URLs used by NetSuite-hosted
and externally hosted clients:
Note: RESTlets use the same debugging domain as other SuiteScript types, https://
debugger.netsuite.com. Whether the RESTlet client is hosted externally or by
NetSuite does not change the debugger domain used. See RESTlet Debugging.
RESTlets Guide
RESTlets
What Are RESTlets?
228
Related Topics
•
•
•
•
•
•
•
•
RESTlet Script Execution
Authentication for RESTlets
Using the REST roles Service to Get User Accounts, Roles, and Domains
Supported Input and Output Content Types for RESTlets
Supported Functions for RESTlets
RESTlet Governance and Session Management
RESTlet Debugging
RESTlet Error Handling
Using the REST roles Service to Get User Accounts, Roles, and Domains
NetSuite provides a REST roles service that returns the following data when you submit a user
email address and password:
•
account(s) and role(s) available to the user
•
REST, Web services, and general system domains to be used for external client access
to NetSuite
The roles service fills the following needs:
•
Support for RESTlet login when the user’s account and role are unknown.
•
Dynamic discovery of correct URLs for external client access to each NetSuite account.
Discovery of the following domains is supported:
• restDomain - https://rest.netsuite.com or https://rest.na1.netsuite.com
• systemDomain - https://system.netsuite.com or https://system.na1.netsuite.com
• webservicesDomain - https://webservices.netsuite.com or
https://webservices.na1.netsuite.com
This discovery is required to support the hosting of customer accounts in multiple data
centers. Each data center has a different domain, so the domain to be used for external
client access depends upon the data center hosting each NetSuite account.
Note: A Web services operation also is available, in the 2012.2 and later endpoints, to
support dynamic discovery of URLs for external client access. For details, see
getDataCenterUrls.
Sample REST roles Request
To get the available accounts, roles, and domains for a user, submit the user’s email address and
password in the authorization header, as shown in the following example:
URL: https://system.netsuite.com/rest/roles
RESTlets Guide
RESTlets
What Are RESTlets?
229
Headers:
GET /rest/roles HTTP/1.1
Accept: */*
Accept-Language: en-us
Authorization: NLAuth nlauth_email=johnsmith@xxxxx.com, nlauth_signature=****
Note: If you specify an account ID in this type of request, an error is returned.
Sample REST roles Response
The roles service returns a list of account(s) available to the user, and for each account, the
associated roles and domains, as shown in the following example:
[{"account":{"internalId":"1234567","name":"Test
Account1"},"role":{"internalId":3,"name":"Administrator"},"dataCenterURLs":{"restDomain":"https://
rest.netsuite.com","systemDomain":"https://system.netsuite.com","webservicesDomain":"https://
webservices.netsuite.com"}},
{"account":{"internalId":"1234678","name":"Test
Account2"},"role":{"internalId":3,"name":"Administrator"},"dataCenterURLs":{"restDomain":"https://
rest.netsuite.com","systemDomain":"https://system.netsuite.com","webservicesDomain":"https://
webservices.netsuite.com"}},
{"account":{"internalId":"1234789","name":"Test
Account3"},"role":{"internalId":3,"name":"Administrator"},"dataCenterURLs":{"restDomain":"https://
rest.netsuite.com","systemDomain":"https://system.netsuite.com","webservicesDomain":"https://
webservices.netsuite.com"}}]
The role to use for login can be selected from this list. And you can use this list to determine
the domains to specify in RESTlet and Web services requests.
Related Topics
•
•
•
•
•
•
•
•
•
RESTlet Script Execution
Authentication for RESTlets
RESTlet URL and Domain
getDataCenterUrls
Supported Input and Output Content Types for RESTlets
Supported Functions for RESTlets
RESTlet Governance and Session Management
RESTlet Debugging
RESTlet Error Handling
Supported Input and Output Content Types for RESTlets
RESTlets support JSON and plain text content types for input and output. For each RESTlet,
output content type is the same as input content type.
You must set the content type in the HTTP Content-Type header. You can use the following
values to specify the input/output content type for a RESTlet:
•
application/json
RESTlets Guide
RESTlets
What Are RESTlets?
•
230
text/plain
If you specify a content type other than JSON or text, a 415 error is returned with the following
message:
Invalid content type. You can only use application/json or text/plain with RESTlets.
Using JSON Objects and Arrays
JSON is an acronym for JavaScript Object Notation, which is a subset of JavaScript. This
special object notational construct is a syntax used to pass JavaScript objects containing name/
value pairs, arrays, or other objects. The following JSON formatting is used for RESTlets:
•
Each JSON object is an unordered set of name/value pairs, or members, enclosed in
curly braces.
• Each member is followed by a comma, which is called a value separator.
• Within each member, the name is separated from the value by a colon, which is
called a name separator.
• Each name and each value is enclosed in quotation marks.
•
Each JSON array is an ordered sequence of values, enclosed in square braces. Array
values are separated by commas.
For examples of how to format JSON input for restlets, see Sample RESTlet Input Formats.
Related Topics
•
•
•
•
•
•
•
•
RESTlet Script Execution
Authentication for RESTlets
RESTlet URL and Domain
Using the REST roles Service to Get User Accounts, Roles, and Domains
Supported Functions for RESTlets
RESTlet Governance and Session Management
RESTlet Debugging
RESTlet Error Handling
Supported Functions for RESTlets
RESTlets currently support a subset of HTTP methods, as shown in the following table:
HTTP Method
Input
Output
Description
GET
Parameter
Object
Object
Requests a representation of the specified resource.
POST
Object
Object
Submits data to be processed, for example from an HTML
form. Data is included in the body of the request, and can
result in creation of a new resource, updates of existing
resource(s), or both.
RESTlets Guide
RESTlets
What Are RESTlets?
HTTP Method
Input
Output
Description
DELETE
Parameter
Object
No Content
Passes in the ID and record type of the resource to be
deleted, so that nlapiDeleteRecord or other delete-related
logic can be called.
231
This method does not return anything.
PUT
Object
Object
Uploads a representation of the specified resource.
The functions that implement these methods are specified on a RESTlet’s script record. Each
RESTlet must have a function for at least one of these HTTP methods. Each HTTP method
can call any SuiteScript nlapi functions. See Create the RESTlet Script Record.
For examples of these functions in RESTlets, see Sample RESTlet Code.
Related Topics
•
•
•
•
•
•
•
•
RESTlet Script Execution
Authentication for RESTlets
RESTlet URL and Domain
Using the REST roles Service to Get User Accounts, Roles, and Domains
Supported Input and Output Content Types for RESTlets
RESTlet Governance and Session Management
RESTlet Debugging
RESTlet Error Handling
RESTlet Governance and Session Management
The SuiteScript governance model tracks usage units on two levels: API level and script level.
At the API level, RESTlets have the same usage limits as other types of SuiteScripts. At the
script level, RESTlets allow 5,000 usage units per script, a limit five times greater than Suitelets
and most other types of SuiteScripts. For more information, see SuiteScript Governance.
RESTlets can support up to 50 concurrent connections from a single user login. (Note that any
concurrent Suitelet connections also count toward this limit. ) If more than 50 concurrent
connections are made, an HTTP error code of 500 is returned, and an
ExceededRequestLimitFault is thrown. This is the same fault that is thrown when concurrent
Web services SOAP requests exceed limits.
There is a limit of 10MB per string used as RESTlet input or output.
SuiteScript currently does not support a logout operation similar to the one used to terminate a
session in SuiteTalk.
RESTlets Guide
RESTlets
What Are RESTlets?
232
Related Topics
•
•
•
•
•
•
•
•
RESTlet Script Execution
Authentication for RESTlets
RESTlet URL and Domain
Using the REST roles Service to Get User Accounts, Roles, and Domains
Supported Input and Output Content Types for RESTlets
Supported Functions for RESTlets
RESTlet Debugging
RESTlet Error Handling
RESTlet Debugging
You can use the SuiteScript Debugger to debug RESTlet scripts, in the same manner that you
use it to debug other types of server SuiteScripts. RESTlets use the same debugging domain as
other SuiteScript types, https://debugger.netsuite.com. Both ad-hoc debugging and deployed
debugging are supported for RESTlets. For general instructions for using the Debugger, see
Debugging SuiteScript.
Important: For deployed debugging of a RESTlet, you need to set the cookie of the client
application that runs the RESTlet to the same cookie listed for the RESTlet in
the Debugger. This cookie contains the NetSuite version and the
JSESSIONID. Also, you must remove the authorization header from your
RESTlet before debugging. For more details, see Debugging a RESTlet.
Related Topics
•
•
•
•
•
•
•
•
RESTlet Script Execution
Authentication for RESTlets
RESTlet URL and Domain
Using the REST roles Service to Get User Accounts, Roles, and Domains
Supported Input and Output Content Types for RESTlets
Supported Functions for RESTlets
RESTlet Governance and Session Management
RESTlet Error Handling
RESTlet Error Handling
RESTlets return standard HTTP status codes for their contained HTTP requests. A standard
success code is returned for a successful request. Standard error codes are returned for errors
due to unparsable input, authentication failure, lack of server response, use of an unsupported
method, and use of an invalid content type or data format for input. In most cases, generic
HTTP error messages are returned. The format used for error messages is the same as the
RESTlets Guide
RESTlets
What Are RESTlets?
233
specified format for input: JSON or plain text. For more details, see RESTlet Status Codes and
Error Message Formats.
RESTlets also support the SuiteScript nlapiCreateError function. You can include this API in
your code to abort script execution when an error occurs. For details, see Error Handling
APIs..
Related Topics
•
•
•
•
•
•
•
•
RESTlet Script Execution
Authentication for RESTlets
RESTlet URL and Domain
Using the REST roles Service to Get User Accounts, Roles, and Domains
Supported Input and Output Content Types for RESTlets
Supported Functions for RESTlets
RESTlet Governance and Session Management
RESTlet Debugging
RESTlets Guide
RESTlets
RESTlets vs. Other NetSuite Integration Options
234
RESTlets vs. Other NetSuite Integration Options
RESTlets provide one option for integration with NetSuite. Other options include SOAP-based
Web services through SuiteTalk, and Suitelets.
Review the following for comparisons of these integration options:
•
RESTlets Compared to SuiteTalk
•
RESTlets Compared to Suitelets
RESTlets Guide
RESTlets
RESTlets vs. Other NetSuite Integration Options
235
RESTlets Compared to SuiteTalk
The following table compares the characteristics of RESTlets with those of SuiteTalk’s SOAPbased Web services:
Attribute
RESTlets
SuiteTalk
Supported Operations
get, search, add, update
(heterogeneous)
get, search, add, update
(homogenous)
Authentication
Supported?
Yes
Yes
Supported HTTP
Methods
GET, PUT, POST, DELETE
POST
Passing of Login Details
in authorization header
in body (SOAP)
Passing of Parameters
GET parameters on URL
all parameters in body (SOAP)
Supported Content
Types
JSON, text/xml (explicit)
text/xml (explicit)
Environment
lightweight, more suitable for mobile
devices, bundleable
heavy programming and deployment
environment (C#, Java)
Supported Concurrency
up to 50 (combined with Suitelets), no
special license required
up to 10, SuiteCloud Plus license
required
URL Clarity?
Yes
No
https://rest.netsuite.com/app/site/
hosting/
restlet.nl?script=57&deploy=1&
recordtype=salesorder&id=21480
https://webservices.netsuite.com/
services/NetSuitePort_2011_1
(Note that for clients hosted by
NetSuite, use the relative URL that
does not include the domain.)
Note: SuiteTalk is recommended for system-to-system integrations.
RESTlets Guide
RESTlets
RESTlets vs. Other NetSuite Integration Options
236
RESTlets Compared to Suitelets
The following table compares the characteristics of RESTlets with those of Suitelets:
Attribute
RESTlets
Suitelets
Supported Operations
get, search, add, update
get, search, add, update
Authentication
Supported?
Yes
No , when available without login and
executed as admin programmatically
Yes, when accessed from a browser by
a logged-in NetSuite user
Script Functions and
HTTP Methods
individual script function for each
HTTP method
one script function for all HTTP
method
Content Handling
built-in handling of JSON input/
output
must write code to convert JSON
input/output
Governance
5,000 usage units per script
1,000 usage units per script
URL Clarity?
Yes
No
https://rest.netsuite.com/app/site/
hosting/
restlet.nl?script=57&deploy=1&
recordtype=salesorder&id=21480
https://forms/netsuite.com/app/site/
hosting/
scriptlet.nl?script=62&deploy=1&com
pid=824056&h=ec041b59b3075bec7
83d
(Note that for clients hosted by
NetSuite, use the relative URL that
does not include the domain.)
Related Topics
•
•
•
•
•
•
•
•
•
RESTlets
What Are RESTlets?
Creating a RESTlet
Debugging a RESTlet
Sample RESTlet Code
Sample RESTlet Input Formats
RESTlet Status Codes and Error Message Formats
Suitelets
SuiteTalk Platform Overview
RESTlets Guide
RESTlets
Creating a RESTlet
237
Creating a RESTlet
To run a RESTlet in NetSuite, you must first define your client code and behavior, then define
your RESTlet and its required functions. The client will send requests to the RESTlet URL
generated by NetSuite.
To define a RESTlet:
1.
Create a JavaScript file for your RESTlet code.
2.
Load the file into NetSuite.
3.
Create a script record where you define SuiteScript functions for one or more HTTP
methods.
4.
Define all runtime options on the Script Deployment page.
See the following for instructions for these tasks:
•
Create the RESTlet File and Add It to the File Cabinet
•
Create the RESTlet Script Record
•
Define RESTlet Deployment(s)
Create the RESTlet File and Add It to the File Cabinet
1.
Create a .js file and add your code to it, in the same manner that you create other types
of SuiteScript files, as described in Step 1: Create Your Script.
This single script file should include GET, POST, DELETE, or PUT function(s) as
necessary.
2.
Once you have created a .js file with your RESTlet code, you need to add this file to the
NetSuite file cabinet.
The following steps describe how to add the file manually. If you are using the
SuiteScript plug-in for Eclipse, this process is automated. For more information, see
Step 2: Add Script to NetSuite File Cabinet.
a.
Go to [TP=LIST_MEDIAITEMFOLDER=TP], and select the folder where you
want to add the file.
It is recommended that you add your file to the SuiteScripts folder, but it can be
added to any other folder of your choice.
b.
Click Add File, and browse to the .js file.
RESTlets Guide
RESTlets
Creating a RESTlet
238
Create the RESTlet Script Record
Once you have added a RESTlet file to the file cabinet, you can create a NetSuite script record.
To create a RESTlet script record:
1.
Go to [TP=EDIT_SCRIPT=TP], and click RESTlet.
2.
Complete fields in the script record and save.
Although you do not need to set every field on the Script record, at a minimum you
must provide a Name for the Script record, load your SuiteScript file to the record, and
specify at least one of the following executing functions in your script: GET, POST,
DELETE, or PUT.
You can specify more than one of these functions as desired. These functions should
all be in the main script file. If these functions call functions in other script files, you
need to list those files as library script files.
RESTlets Guide
RESTlets
Debugging a RESTlet
239
For more details about creating a script record, see Steps for Creating a Script Record.
Define RESTlet Deployment(s)
Once you have created a RESTlet script record, you need to define at least one deployment. For
details about defining script deployments, see Step 5: Define Script Deployment and Steps for
Defining a Script Deployment
You can define multiple deployments per RESTlet.
To define a RESTlet script deployment.
1.
Do one of the following:
• When you save your Script record, you can immediately create a Script
Deployment record by selecting Save and Deploy from the Script record Save
button.
• If you clicked Save, immediately afterwards you can click Deploy Script on the
script record.
• If you want to update a deployment that already exists, go to Setup >
Customization > Script Deployments > [deployment] > Edit.
2.
Complete fields in the script deployment record and click Save.
If you want to debug the script, set the Status to Testing.
Note: Once you have saved a RESTlet deployment, the deployment record includes the
URL used to invoke the RESTlet. For a RESTlet called from an externally hosted
client, use the External URL. For a RESTlet called from a client hosted by NetSuite,
use the URL that does not include the domain. See RESTlet URL and Domain.
Related Topics
•
•
•
•
•
•
•
•
RESTlets
What Are RESTlets?
RESTlets vs. Other NetSuite Integration Options
Debugging a RESTlet
Sample RESTlet Code
Sample RESTlet Input Formats
RESTlet Status Codes and Error Message Formats
Running Scripts in NetSuite Overview
Debugging a RESTlet
You can use the NetSuite Debugger to debug RESTlet code in the same manner that you debug
other types of SuiteScript code, as described in the NetSuite Help Center topic Debugging
SuiteScript.
RESTlets Guide
RESTlets
Debugging a RESTlet
240
•
To debug code snippets before you have a RESTlet script record that has been
deployed, called ad-hoc debugging, follow the instructions in Ad-hoc Debugging. (Be
sure not to include the RESTlet’s authorization header in the code snippets to be
debugged, as this header can prevent the debugger from working.)
•
To debug an existing script that has a defined deployment, called deployed debugging,
follow the steps below.
Important: In addition to debugging RESTlet script code, it is recommended that you
test the HTTP request to be sent to the RESTlet. Free tools are available for
this purpose. See RESTlet HTTP Testing Tools.
To debug a deployed RESTlet:
1.
Before you deploy a RESTlet to be debugged, ensure that the script does not include
the HTTP authorization header, as this header can prevent the debugger from
working.
2.
Ensure that on the script deployment record, the Status value is set to Testing.
3.
Go to Setup > Customization > Script Debugger, or log in to the debugger domain
https://debugger.netsuite.com. (See Deployed Debugging for details.)
4.
Click the Debug Existing button in the main Script Debugger page.
5.
Select the RESTlet script that you want to debug in the Script Debugger popup.
Once you click the Select option button, the RESTlet’s cookie displays in a banner.
This cookie includes the NetSuite version and the JSESSIONID.
6.
Copy the cookie and paste it into a text file so that you have it available.
7.
Click the Select and Close button in the Script Debugger popup.
The main Script Debugger page displays a message that it is waiting for user action.
8.
Set the cookie in your client application to the value you copied in step 5, and send the
RESTlet request.
The main Script Debugger page displayes the script execution as pending at the
NetSuite function restletwrapper(request).
9.
You have the following options for debugging your script code:
• Click the Step Over button to begin stepping through each line of code.
RESTlets Guide
RESTlets
Debugging a RESTlet
241
• Add watches and evaluate expressions.
• Set break points and click the Run button to run the code. The Debugger will stop
code execution at the first break point set.
• Set no break points, click the Run button, and have the Debugger execute the
entire piece of code.
See SuiteScript Debugger Interface for information on stepping into/out of functions,
adding watches, setting and removing break points, and evaluating expressions.
Debugging Timeout Errors
If a timeout error occurs during debugging, check for the following:
•
Invalid or missing NetSuite version
Ensure that you have correctly copied the cookie, as described in the steps above. This
cookie includes a valid NetSuite version.
•
Invalid JSESSIONID
Ensure that you have correctly copied the cookie, as described in the steps above. This
cookie includes a valid JSESSIONID.
•
Incorrect domain such as https://rest.netsuite.com
Ensure that you have logged in to https://debugger.netsuite.com.
Related Topics
•
•
•
•
•
•
•
•
RESTlets
What Are RESTlets?
RESTlets vs. Other NetSuite Integration Options
Creating a RESTlet
Sample RESTlet Code
Sample RESTlet Input Formats
RESTlet Status Codes and Error Message Formats
Debugging SuiteScript
RESTlet HTTP Testing Tools
You can use the tools of your choosing to test the HTTP request to be sent to a RESTlet. For
example, the following free tools are available:
•
Send HTTP Tool
This tool is a free HTTP Request builder that you can use to send an HTTP request to
the RESTlet and analyze the response.
http://soft-net.net/SendHTTPTool.aspx
•
Fiddler
RESTlets Guide
RESTlets
Sample RESTlet Code
242
This tool is a free Web debugging proxy that you can use to log HTTP traffic, and
inspect the HTTP request and response for the RESTlet.
http://www.fiddler2.com/fiddler2/
Warning: The above information is provided as a courtesy and is not intended as an
endorsement or recommendation of these tools.
Related Topics
•
•
•
What Are RESTlets?
Debugging a RESTlet
RESTlet Status Codes and Error Message Formats
Sample RESTlet Code
The following examples provide sample RESTlet code:
•
Simple Example to Get Started
•
Example Code Snippets of HTTP Methods
•
Example RESTlet Request from Android
•
Example RESTlet Request Using nlapiRequestURL
Related Topics
•
•
•
•
•
•
•
RESTlets
What Are RESTlets?
RESTlets vs. Other NetSuite Integration Options
Creating a RESTlet
Debugging a RESTlet
Sample RESTlet Input Formats
RESTlet Status Codes and Error Message Formats
Simple Example to Get Started
Use the following example as a very simple GET method test when you are getting started with
RESTlets:
function sayhi()
{
var o = new Object();
o.sayhi = 'Hello World! ';
return o;
}
RESTlets Guide
RESTlets
Sample RESTlet Code
Related Topics
•
•
•
RESTlets
Sample RESTlet Code
Sample RESTlet Input Formats
Example Code Snippets of HTTP Methods
The following code snippets provide examples of RESTlet functions.
GET Method
// Get a standard NetSuite record
function getRecord(datain)
{
return nlapiLoadRecord(datain.recordtype, datain.id); // e.g recordtype="customer", id="769"
}
Query parameters:
recordtype=customer&id=769
POST Method
// Create a standard NetSuite record
function createRecord(datain)
{
var err = new Object();
// Validate if mandatory record type is set in the request
if (!datain.recordtype)
{
err.status = "failed";
err.message= "missing recordtype";
return err;
}
var record = nlapiCreateRecord(datain.recordtype);
for (var fieldname in datain)
{
if (datain.hasOwnProperty(fieldname))
{
if (fieldname != 'recordtype' && fieldname != 'id')
{
var value = datain[fieldname];
if (value && typeof value != 'object') // ignore other type of parameters
{
record.setFieldValue(fieldname, value);
}
}
}
}
var recordId = nlapiSubmitRecord(record);
nlapiLogExecution('DEBUG','id='+recordId);
RESTlets Guide
243
RESTlets
Sample RESTlet Code
var nlobj = nlapiLoadRecord(datain.recordtype,recordId);
return nlobj;
}
Request Payload:
{"recordtype":"customer","entityid":"John Doe","companyname":"ABCTools, Inc",
"subsidiary":"1","email":jdoe@email.com}
DELETE Method
// Delete a standard NetSuite record
function deleteRecord(datain)
{
nlapiDeleteRecord(datain.recordtype, datain.id); // e.g recordtype="customer", id="769"
}
Query parameters:
recordtype=customer&id=769
Related Topics
•
•
•
RESTlets
Sample RESTlet Code
Sample RESTlet Input Formats
Example RESTlet Request from Android
HttpPost post = new HttpPost( URL + urlParams );
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout( httpParameters, 20000 );
HttpConnectionParams.setSoTimeout( httpParameters, 42000 );
String authorization = "NLAuth nlauth_account=" + account + ", nlauth_email=" + email + ",
nlauth_signature="+password+", nlauth_role="+role+"";
post.setHeader( "Authorization", authorization );
post.setHeader( "Content-Type", "application/json" );
post.setHeader( "Accept", "*/*" );
post.setEntity( new StringEntity( "{\"name\":\"John\"}" /*input data*/ ) );
HttpClient client = new DefaultHttpClient( httpParameters );
BufferedReader in = null;
HttpResponse response = client.execute( post );
in = new BufferedReader( new InputStreamReader( response.getEntity().getContent() ) );
StringBuffer sb = new StringBuffer( "" );
String line;
String NL = System.getProperty( "line.separator" );
while ( (line = in.readLine()) != null )
{
sb.append( line + NL );
}
in.close();
RESTlets Guide
244
RESTlets
Sample RESTlet Code
245
String result = sb.toString();
Related Topics
•
•
•
RESTlets
Sample RESTlet Code
Sample RESTlet Input Formats
Example RESTlet Request Using nlapiRequestURL
function credentials()
{
this.email='msmith@email.com';
this.account='1234567';
this.role='3';
this.password='*****';
}
function replacer(key, value) {
if (typeof value === 'number' && !isFinite(value)) {
return String(value);
}
return value;
}
//Setting up URL
var url = 'https://rest.netsuite.com/app/site/hosting/restlet.nl?script=260&deploy=1';
//Calling credential function
var cred = new credentials();
//Setting up Headers
var headers = new Array();
headers['User-Agent-x'] = 'SuiteScript-Call';
headers['Authorization'] = 'NLAuth nlauth_account='+cred.account+', nlauth_email='+cred.email+',
nlauth_signature='+cred.password+', nlauth_role='+cred.role;
headers['Content-Type'] = 'application/json';
//Setting up Datainput
var jsonobj={"recordtype":"customer","entityid":"John Doe","companyname":"ABC Company",
"subsidiary":"1","email":"jdoe@email.com"}
//Stringifying JSON
var myJSONText = JSON.stringify(jsonobj, replacer);
var response = nlapiRequestURL( url, myJSONText , headers );
//Bellow is been used to put breakpoint
var i=0;
****RESTLET Code****
// Create a standard NetSuite record
function createRecord(datain)
{
RESTlets Guide
RESTlets
Sample RESTlet Input Formats
246
var err = new Object();
// Validate if mandatory record type is set in the request
if (!datain.recordtype)
{
err.status = "failed";
err.message= "missing recordtype";
return err;
}
var record = nlapiCreateRecord(datain.recordtype);
for (var fieldname in datain)
{
if (datain.hasOwnProperty(fieldname))
{
if (fieldname != 'recordtype' && fieldname != 'id')
{
var value = datain[fieldname];
if (value && typeof value != 'object') // ignore other type of parameters
{
record.setFieldValue(fieldname, value);
}
}
}
}
var recordId = nlapiSubmitRecord(record);
nlapiLogExecution('DEBUG','id='+recordId);
var nlobj = nlapiLoadRecord(datain.recordtype,recordId);
return nlobj;
}
Related Topics
•
•
•
RESTlets
Sample RESTlet Code
Sample RESTlet Input Formats
Sample RESTlet Input Formats
The following examples illustrate how to format input for RESTlets for the JSON content type:
•
Customer Record Format
•
Item Record Format
•
Item Pricing Formats
•
Sales Order Record Format
For a general explanation of JSON, see Using JSON Objects and Arrays.
RESTlets Guide
RESTlets
Sample RESTlet Input Formats
247
Customer Record Format
JSON
{
"shipcomplete":false,
"giveaccess":false,
"globalsubscriptionstatus":"1",
"isperson":false,
... more body fields...,
"consoldepositbalance":0.00,
"entityid":"John Doe",
"addressbook":
[
{"zip":"94404","phone":"650-627-1000"},
{"zip":"94403","phone":"650-627-1001"}
],
"consoloverduebalance":0.00,
"overduebalance":0.00,
"creditholdoverride":"AUTO",
"resubscribelink":"Send Subscription Email"
}
Item Record Format
Note: The format for item pricing varies according to the related features that are enabled
in your account. See Item Pricing Formats for examples.
JSON
{
"salesdescription":"Cat 5 Patch Cable 10 ft",
"vendorname":"CABL0002-64",
"averagecost":3.50,
... more fields...,
“pricing”:
[
…
{
"currency":
{
"name":"British pound",
"internalid":"2"
},
“pricelist”:
[
{
"pricelevel":
{
"name":"Alternate Price 1",
"internalid":"2"
},
"price":
RESTlets Guide
RESTlets
Sample RESTlet Input Formats
[
{
"price":9.03,
"quantitylevel":"1",
"quantity":0
},
{
"price":8.55,
"quantitylevel":"2",
"quantity":10
}
],
"discount":
{
"name":"-5.0%",
"value":"-5.0%"
}
},
{
"pricelevel":
{
"name":"Alternate Price 2",
"internalid":"3"
},
"price":
[
{
"price":8.55,
"quantitylevel":"1",
"quantity":0
},
{
"price":8.10,
"quantitylevel":"2",
"quantity":10
}
],
"discount":
{
"name":"-10.0%",
"value":"-10.0%"
}
},
…
]
}
Repeat for other currencies
],
"productfeed":["FROOGLE","SHOPPING","SHOPZILLA","NEXTAG","YAHOO"],
"weight":"1",
"itemid":"Cable - Cat 5, 10 ft",
RESTlets Guide
248
RESTlets
Sample RESTlet Input Formats
249
... more fields...,
"availabletopartners":false,
"sitecategory":
[
{"categorydescription":"Cables",
"category":"12",
"isdefault":false}
],
"costingmethoddisplay":"Average",
"offersupport":true
}
Item Pricing Formats
The format for item pricing varies according to which of the following features are enabled in
your account: Multiple Prices, Quantity Pricing, and Multiple Currencies. The following
examples show the JSON format for item pricing when each combination of these features is
enabled.
•
Single Price (no additional pricing features enabled)
•
Multiple Prices Only Enabled
•
Quantity Pricing Only Enabled
•
Multiple Prices, Multiple Currencies Enabled
•
Multiple Prices, Quantity Pricing, Multiple Currencies Enabled
Single Price (no additional pricing features enabled)
"pricing":
[
{
"pricelist":
[
{
"price":
[
{"price":100.00,"quantitylevel":"1","quantity":0}
]
}
],
"currency":{"name":"USA","internalid":"1"}
}
]
Multiple Prices Only Enabled
"pricing":
[
{
"pricelist":
[
{
RESTlets Guide
RESTlets
Sample RESTlet Input Formats
"pricelevel":{"name":"Base Price","internalid":"1"},
"price":
[
{"price":100.00,"quantitylevel":"1","quantity":0}
]
},
{
"pricelevel":{"name":"Alternate Price 1","internalid":"2"},
"price":
[
{"price":99.00,"quantitylevel":"1","quantity":0}
]
},
{
"pricelevel":{"name":"Alternate Price 2","internalid":"3"},
"price":
[
{"price":98.00,"quantitylevel":"1","quantity":0}
]
},
{
"pricelevel":{"name":"Alternate Price 3","internalid":"4"},
"price":
[
{"price":97.00,"quantitylevel":"1","quantity":0}
]
},
{
"pricelevel":{"name":"Online Price","internalid":"5"},
"price":
[
{"price":96.00,"quantitylevel":"1","quantity":0}
]
}
],
"currency":{"name":"USA","internalid":"1"}
}
]
Quantity Pricing Only Enabled
"pricing":
[
{
"pricelist":
[
{
"pricelevel":{"name":"Base Price","internalid":"1"},
"price":
[
{"price":100.00,"quantitylevel":"1","quantity":0},
{"price":95.00,"quantitylevel":"2","quantity":100},
{"price":90.00,"quantitylevel":"3","quantity":150},
{"price":85.00,"quantitylevel":"4","quantity":200},
{"price":80.00,"quantitylevel":"5","quantity":250}
]
RESTlets Guide
250
RESTlets
Sample RESTlet Input Formats
},
{
"pricelevel":{"name":"Alternate Price 1","internalid":"2"},
"price":
[
{"price":99.00,"quantitylevel":"1","quantity":0},
{"price":94.00,"quantitylevel":"2","quantity":100},
{"price":89.00,"quantitylevel":"3","quantity":150},
{"price":84.00,"quantitylevel":"4","quantity":200},
{"price":79.00,"quantitylevel":"5","quantity":250}
]
},
{
"pricelevel":{"name":"Alternate Price 2","internalid":"3"},
"price":
[
{"price":98.00,"quantitylevel":"1","quantity":0},
{"price":93.00,"quantitylevel":"2","quantity":100},
{"price":88.00,"quantitylevel":"3","quantity":150},
{"price":83.00,"quantitylevel":"4","quantity":200},
{"price":78.00,"quantitylevel":"5","quantity":250}
]
},
{
"pricelevel":{"name":"Alternate Price 3","internalid":"4"},
"price":
[
{"price":97.00,"quantitylevel":"1","quantity":0},
{"price":92.00,"quantitylevel":"2","quantity":100},
{"price":87.00,"quantitylevel":"3","quantity":150},
{"price":82.00,"quantitylevel":"4","quantity":200},
{"price":77.00,"quantitylevel":"5","quantity":250}
]
},
{
"pricelevel":{"name":"Online Price","internalid":"5"},
"price":
[
{"price":96.00,"quantitylevel":"1","quantity":0},
{"price":91.00,"quantitylevel":"2","quantity":100},
{"price":86.00,"quantitylevel":"3","quantity":150},
{"price":81.00,"quantitylevel":"4","quantity":200},
{"price":76.00,"quantitylevel":"5","quantity":250}
]
}
],
"currency":{"name":"USA","internalid":"1"}
}
]
Multiple Prices, Multiple Currencies Enabled
"pricing":
[
{
"pricelist":
RESTlets Guide
251
RESTlets
Sample RESTlet Input Formats
[
{
"pricelevel":{"name":"Base Price","internalid":"1"},
"price":[{"price":110.00,"quantitylevel":"1","quantity":0}]
},
{
"pricelevel":{"name":"Alternate Price 1","internalid":"2"},
"price":[{"price":105.00,"quantitylevel":"1","quantity":0}]
},
{
"pricelevel":{"name":"Alternate Price 2","internalid":"3"},
"price":[{"price":100.00,"quantitylevel":"1","quantity":0}]
},
{
"pricelevel":{"name":"Alternate Price 3","internalid":"4"},
"price":[{"price":95.00,"quantitylevel":"1","quantity":0}]
},
{
"pricelevel":{"name":"Online Price","internalid":"5"},
"price":[{"price":90.00,"quantitylevel":"1","quantity":0}]
}
],
"currency":{"name":"British pound","internalid":"2"}
},
{
"pricelist":
[
{"pricelevel":{"name":"Base
Price","internalid":"1"},"price":[{"price":100.00,"quantitylevel":"1","quantity":0}]},
{"pricelevel":{"name":"Alternate Price
1","internalid":"2"},"price":[{"price":99.00,"quantitylevel":"1","quantity":0}]},
{"pricelevel":{"name":"Alternate Price
2","internalid":"3"},"price":[{"price":98.00,"quantitylevel":"1","quantity":0}]},
{"pricelevel":{"name":"Alternate Price
3","internalid":"4"},"price":[{"price":97.00,"quantitylevel":"1","quantity":0}]},
{"pricelevel":{"name":"Online
Price","internalid":"5"},"price":[{"price":96.00,"quantitylevel":"1","quantity":0}]}
],
"currency":{"name":"USA","internalid":"1"}
}
Multiple Prices, Quantity Pricing, Multiple Currencies Enabled
"pricing":
[
{
"pricelist":
[
{
"pricelevel":{"name":"Base Price","internalid":"1"},
"price":
[
{"price":110.00,"quantitylevel":"1","quantity":0},
{"price":105.00,"quantitylevel":"2","quantity":100},
{"price":100.00,"quantitylevel":"3","quantity":150},
{"price":95.00,"quantitylevel":"4","quantity":200},
RESTlets Guide
252
RESTlets
Sample RESTlet Input Formats
253
{"price":90.00,"quantitylevel":"5","quantity":250}
]
},
{
"pricelevel":{"name":"Alternate Price 1","internalid":"2"},
"price":
[
{"price":105.00,"quantitylevel":"1","quantity":0},
{"price":100.00,"quantitylevel":"2","quantity":100},
{"price":95.00,"quantitylevel":"3","quantity":150},
{"price":90.00,"quantitylevel":"4","quantity":200},
{"price":85.00,"quantitylevel":"5","quantity":250}
]
},
{
"pricelevel":{"name":"Alternate Price 2","internalid":"3"},
"price":[{"price":100.00,"quantitylevel":"1","quantity":0},{"price":95.00,"quantitylevel":"2","quantity":100},{"price"
:90.00,"quantitylevel":"3","quantity":150},{"price":85.00,"quantitylevel":"4","quantity":200},{"price":80.00,"quanti
tylevel":"5","quantity":250}]
},
{
"pricelevel":{"name":"Alternate Price 3","internalid":"4"},
"price":[{"price":95.00,"quantitylevel":"1","quantity":0},{"price":90.00,"quantitylevel":"2","quantity":100},{"price":
85.00,"quantitylevel":"3","quantity":150},{"price":80.00,"quantitylevel":"4","quantity":200},{"price":75.00,"quantit
ylevel":"5","quantity":250}]
},
{
"pricelevel":{"name":"Online Price","internalid":"5"},
"price":[{"price":90.00,"quantitylevel":"1","quantity":0},{"price":85.00,"quantitylevel":"2","quantity":100},{"price":
80.00,"quantitylevel":"3","quantity":150},{"price":75.00,"quantitylevel":"4","quantity":200},{"price":70.00,"quantit
ylevel":"5","quantity":250}]
}
],
"currency":{"name":"British pound","internalid":"2"}
},
{
"pricelist":
[
{
"pricelevel":{"name":"Base Price","internalid":"1"},
"price":[{"price":100.00,"quantitylevel":"1","quantity":0},{"price":95.00,"quantitylevel":"2","quantity":100},{"price"
:90.00,"quantitylevel":"3","quantity":150},{"price":85.00,"quantitylevel":"4","quantity":200},{"price":80.00,"quanti
tylevel":"5","quantity":250}]
},
{
"pricelevel":{"name":"Alternate Price 1","internalid":"2"},
"price":[{"price":99.00,"quantitylevel":"1","quantity":0},{"price":94.00,"quantitylevel":"2","quantity":100},{"price":
89.00,"quantitylevel":"3","quantity":150},{"price":84.00,"quantitylevel":"4","quantity":200},{"price":79.0","quantit
ylevel":"5","quantity":250}]
},
RESTlets Guide
RESTlets
Sample RESTlet Input Formats
254
{
"pricelevel":{"name":"Alternate Price 2","internalid":"3"},
"price":[{"price":98.0","quantitylevel":"1","quantity":0},{"price":93.00,"quantitylevel":"2","quantity":100},{"price":
88.00,"quantitylevel":"3","quantity":150},{"price":83.00,"quantitylevel":"4","quantity":200},{"price":78.00,"quantit
ylevel":"5","quantity":250}]
},
{
"pricelevel":{"name":"Alternate Price 3","internalid":"4"},
"price":[{"price":97.00,"quantitylevel":"1","quantity":0},{"price":92.00,"quantitylevel":"2","quantity":100},{"price":
87.00,"quantitylevel":"3","quantity":150},{"price":82.00,"quantitylevel":"4","quantity":200},{"price":77.00,"quantit
ylevel":"5","quantity":250}]
},
{
"pricelevel":{"name":"Online Price","internalid":"5"},
"price":[{"price":96.00,"quantitylevel":"1","quantity":0},{"price":91.00,"quantitylevel":"2","quantity":100},{"price":
86.00,"quantitylevel":"3","quantity":150},{"price":81.00,"quantitylevel":"4","quantity":200},{"price":76.00,"quantit
ylevel":"5","quantity":250}]
}
],
"currency":{"name":"USA","internalid":"1"}
}
]
Sales Order Record Format
JSON
{
"total":64.04,
"altshippingcost":5.67,
"taxtotal":4.45,
"tranid":"120",
"orderstatus":"E",
"shipcomplete":false,
"discounttotal":0.00,
"entity":"76",
"billaddress":"Doug Fabre\r\nChess\r\nChess Art Gallery\r\n150 N Ocean Dr\r\nMonterey CA 93940",
"salesrep":"-5",
"ccapproved":false,
"linkedtrackingnumbers":["1Z6753YA0394527573","1Z6753YA0394249981"],
"shipmethod":"92",
"exchangerate":1.00
"lastmodifieddate":"1/9/2011 11:34 pm",
"taxrate":"8.25%",
"id":"769",
"shipaddresslist":"55",
"istaxable":true,
"tobefaxed":false,
"altsalestotal":0.00,
"getauth":false,
"tobeprinted":false,
"shippingcost":5.67,
RESTlets Guide
RESTlets
Sample RESTlet Input Formats
"recordtype":"salesorder",
"trandate":"10/14/2006",
"fax":"831-555-5230",
"customform":"88",
"links":
[
{"trandate":"10/14/2006","tranid":"8","type":"Item Fulfillment","linktype":"Receipt/Fulfillment"}
],
"taxitem":"-112",
"custbody1":"831-555-5229",
"custbody2":"Do not leave the item outside the house",
"shipdate":"10/14/2006",
"createddate":"10/14/2006 2:58 pm",
"subtotal":53.92,
"currencyname":"USA",
"revenuestatus":"A",
"saleseffectivedate":"10/14/2006",
"email":chessart@christyscatering.com,
"item":
[
{
"isclosed":false,"fromjob":false,"amount":8.96,"rate":8.96,"price":"2",
"istaxable":"T","description":"10 ft Serial Cable DB25M DB25F",
"custcol6":429,"custcol7":2.5,
"item":"46","quantity":1,"isestimate":false,"commitinventory":"1",
"options":
{
"CUSTCOL3":792,"CUSTCOL1":4
}
},
{
"isclosed":false,"fromjob":false,"amount":44.96,"rate":44.96,"price":"2",
"istaxable":true,
"item":"80","quantity":1,"isestimate":false,"commitinventory":"1"
}
],
"excludecommission":false,
"shipaddress":"Chess\r\nChess Art Gallery\r\n150 N Ocean Dr\r\nMonterey CA
93940","tobeemailed":false
}
Related Topics
•
•
•
•
•
•
•
RESTlets
What Are RESTlets?
RESTlets vs. Other NetSuite Integration Options
Creating a RESTlet
Debugging a RESTlet
Sample RESTlet Code
RESTlet Status Codes and Error Message Formats
RESTlets Guide
255
RESTlets
RESTlet Status Codes and Error Message Formats
256
RESTlet Status Codes and Error Message Formats
For details about RESTlet errors, see:
•
Success Code
•
Error Codes
•
Notes about RESTlet Errors
•
Error Message Formatting
•
Error for Incorrect URL
Success Code
RESTlets support the following HTTP success code:
•
200 OK: The RESTlet request was executed successfully.
The actual response depends on the request method used. For a GET request, the
response contains an entity corresponding to the requested resource. For a POST
request the response contains an entity describing or containing the result of the action
Error Codes
RESTlets support the following HTTP error codes:
•
400 BAD_REQUEST: The RESTlet request failed with a user error.
•
401 UNAUTHORIZED: There is not a valid NetSuite login session for the RESTlet
calls.
•
403 FORBIDDEN: RESTlet request sent to invalid domain, meaning a domain other
than https://rest.netsuite.com.
•
404 NOT_FOUND: A RESTlet script is not defined in the RESTlet request.
•
405 METHOD_NOT_ALLOWED: The RESTlet request method is not valid.
•
415 UNSUPPORTED_MEDIA_TYPE: An unsupported content type was specified.
(Only JSON and text are allowed.)
•
500 INTERNAL_SERVER_ERROR (unexpected errors): Occurs for non-user errors
that cannot be recovered by resubmitting the same request.
If this type of error occurs, contact Customer Support to file a case.
•
503 SERVICE_UNAVAILABLE: The NetSuite database is offline or a database
connection is not available.
For more information about HTTP status codes, see http://www.w3.org/Protocols/rfc2616/
rfc2616-sec10.html.
RESTlets Guide
RESTlets
RESTlet Status Codes and Error Message Formats
257
Notes about RESTlet Errors
•
Any errors encountered at run time that are unhandled return a 400 error. If the user
code catches the error, a 200 error is returned.
•
An unexpected error is returned with an error ID, for example:
Code = UNEXPECTED_ERROR
Msg = An unexpected error occurred. Error ID: fevsjhv41tji2juy3le73
•
The DELETE method is not expected to return anything. In this case, the message is
returned:
Return was ignored in DELETE operation.
•
If users specify a content type other than JSON or TEXT, a 415 error is returned with
the following message:
Invalid content type. You can only use application/json, application/xml or text/plain with RESTlets.
•
If users provide data in a format different from specified type, the following error is
returned with one of the following messages:
Error code = INVALID_RETURN_DATA_FORMAT
Error message = Invalid data format. You should return TEXT.
Error message = Invalid data format. You should return a JavaScript object.
Error Message Formatting
The following examples show RESTlet error message formatting for JSON and text content
types.
JSON
{
"error":
{
"code":"SSS_INVALID_SCRIPTLET_ID",
"message":"That Suitelet is invalid, disabled, or no longer exists."
}
}
Text
<error code: SSS_INVALID_SCRIPTLET_ID
error message: That Suitelet is invalid, disabled, or no longer exists.
Error for Incorrect URL
If you receive the following error, make sure that the URL is correct and that it points to the
correct RESTlet script ID.
SSS_INVALID_SCRIPTLET_ID: That Suitelet is invalid, disabled, or no longer exists.
RESTlets Guide
RESTlets
RESTlet Status Codes and Error Message Formats
Related Topics
•
•
•
•
•
•
•
•
RESTlets
What Are RESTlets?
RESTlets vs. Other NetSuite Integration Options
Creating a RESTlet
Debugging a RESTlet
Sample RESTlet Code
Sample RESTlet Input Formats
Error Handling APIs
RESTlets Guide
258
Chapter 23 Scheduled Scripts
Scheduled scripts run on the NetSuite server. Compared to user event scripts, scheduled scripts
are given a higher limit of usage governance. Therefore, scheduled scripts are ideal for long
running tasks and batch jobs.
Important: All companies that run NetSuite are provided a single queue for running
their scheduled scripts. You can upgrade your number of scheduled script
queues to five by purchasing NetSuite’s SuiteCloud Plus module. See Using
Multiple Script Queues to Run Scheduled Scripts for more information.
People new to scheduled scripts should read all of the following topics. However, these topics
do not need to be read in order:
•
Understanding Scheduled Script Execution - explains how scheduled scripts execute in
NetSuite. The table in Deployment Status and Script Execution Summary provides a
succinct overview of what users can and cannot do with a scheduled script based on its
deployment status.
•
Deploying Scheduled Scripts - explains how to deploy a scheduled script either to run
immediately or to run at some scheduled future time.
•
Creating Multiple Deployments for a Scheduled Script - explains how to create
multiple deployments for the same scheduled script and why you may want to.
•
Running Scheduled Scripts Using nlapiScheduleScript - explains possible scenarios for
using nlapiScheduleScript to queue a script
•
Setting the Scheduled Script type Argument - describes how too associate an event
type with a scheduled script
•
Setting Recovery Points in Scheduled Scripts – describes the recovery point
mechanism, and why you would want to use this feature.
•
Understanding Memory Usage in Scheduled Scripts – explains how scripts consume
memory, and how to use memory more effectively.
•
Monitoring Scheduled Scripts - provides details on monitoring script activity using
both the UI and APIs
•
Scheduled Script Samples - provides scheduled script code samples
•
Using Multiple Script Queues to Run Scheduled Scripts - describes the SuiteCloud Plus
module, which is available for purchase. Adding this module to your existing account
upgrades your number of scheduled script queues from one to five.
•
Scheduled Script Best Practices
SuiteScript Developer and Reference Guide
Scheduled Scripts
Understanding Scheduled Script Execution
260
Important: Scheduled scripts that do mass modifications of data may prompt the system
to generate automatic email notifications. For example, if the data being
modified is on an Activity record that is set to automatically send an email
each time the record is updated, an email will be sent when the scheduled
script runs and data is updated.
Understanding Scheduled Script Execution
Whether a scheduled script is executed “on-demand” for immediate execution, or it scheduled
to run in the future, once a script has been placed into the NetSuite scheduling queue, it is
executed serially on a per-company basis. In other words, there is a single queue used by all
scheduled scripts in your company’s NetSuite account. As soon as one script completes, the
next script in the queue is immediately executed.
A scheduled script may not run at precisely the time it was scheduled if there are multiple longrunning scripts before it in your company’s queue. The first of your company’s scripts to be
placed in the queue will be the first script to run. Although multiple scheduled scripts can exist
in the queue, only a single script can be executed at any given time.
For example, if your company has scheduled two scripts to start at 10:00 p.m., the second script
that was also set to run at 10:00 p.m. will not start until the first script completes. Once the first
script completes, the second script will execute immediately.
Important: All companies that run NetSuite are provided a single queue for running
their scheduled scripts. You can upgrade your number of scheduled script
queues to five by purchasing NetSuite’s SuiteCloud Plus module. See Using
Multiple Script Queues to Run Scheduled Scripts for more information.
Scheduled Script Deployment Statuses
The following definitions and diagram show each of the deployment phases for a scheduled
script. These phases appear in the Status field of the Script Deployment page.
•
In Queue: The script is in the NetSuite scheduling queue and is waiting to be run.
•
In Progress: The script is currently running.
•
Completed: The script was successfully deployed and executed. The user must
manually change the script’s deployment status to either Scheduled or Not Scheduled
before the script can be run again.
Important: Scripts with a Completed deployment status CAN be put into the NetSuite
scheduling queue programmatically using nlapiScheduleScript. See Running
Scheduled Scripts Using nlapiScheduleScript for details.
•
Scheduled: If the script has been set to execute on a recurring basis, the script’s
deployment status will appear as Scheduled after it executes. The script will then be rerun at its specified time(s).
SuiteScript Developer and Reference Guide
Scheduled Scripts
Understanding Scheduled Script Execution
261
Note: Scheduled scripts called by nlapiScheduleScript(scriptId, deployId, params) may
show a NULL status if the script that was called has not yet been deployed or does
not exist in NetSuite.
SuiteScript Developer and Reference Guide
Scheduled Scripts
Understanding Scheduled Script Execution
262
These figures show an example of the Not Scheduled -> Completed execution process. Notice
the deployment status changes from Not Scheduled to Completed once it has finished its
execution.
Figure 1
Even for scripts that fail, the deployment status still changes to Completed. Note that for
another immediate (ad-hoc) execution, users must manually change the deployment status
back to Not Scheduled. Clicking Save and Execute for a script that has a Completed status will
do nothing.
Figure 2
Important: Scripts with the a Completed deployment status CAN be put into the
NetSuite scheduling queue programmatically using nlapiScheduleScript. See
Running Scheduled Scripts Using nlapiScheduleScript for details.
Deployment Status and Script Execution Summary
The following table summarizes what you can and cannot do with a scheduled script
depending on its deployment status.
The second column states whether the script can be placed into the NetSuite scheduling queue
through the UI.
The third column states whether the script can be queued using nlapiScheduleScript.
Deployment Status
UI
nlapiScheduleScript
Not Scheduled
YES. You must click the Save and Execute
button on the Script Deployment page.
YES
Scheduled
N/A. No action is required by the user. With a
deployment status set to Scheduled, the
script will just run again at the next scheduled
time.
NO
SuiteScript Developer and Reference Guide
Scheduled Scripts
Understanding Scheduled Script Execution
Deployment Status
UI
nlapiScheduleScript
Completed
NO
YES
Testing
YES. On the Script Deployment page users
must click Save and Execute if they want to
run the script for testing purposes. You cannot
schedule testing times and then click Save.
Only Save and Execute will run a script that
has a Testing status.
NO
Also note that only scheduled scripts with a
deployment status set to Testing can be
loaded into the SuiteScript Debugger.
Finally, scheduled scripts set to Testing will
run in the script owner’s account only.
SuiteScript Developer and Reference Guide
263
Scheduled Scripts
Deploying Scheduled Scripts
Deploying Scheduled Scripts
Scheduled scripts can be deployed to run immediately, or they can be scheduled to run at a
later time. You can also create multiple deployments for the same scheduled script file. See
these sections for details:
•
Scheduling a Script for Immediate Execution
•
Scheduling a Script to Run in the Future
•
Creating Multiple Deployments for a Scheduled Script
You can set deployment options for scheduled scripts on both the Script record page or the
Script Deployment page. For simplicity, all examples in the remaining sections will show
screenshots from the Script Deployment page.
SuiteScript Developer and Reference Guide
264
Scheduled Scripts
Deploying Scheduled Scripts
265
Scheduling a Script for Immediate Execution
Scheduled scripts with a deployment status of Not Scheduled or Testing can be executed
immediately.
Important: Deployments set to Not Scheduled can also be invoked on-demand using
the nlapiScheduleScript API. For details, see Running Scheduled Scripts
Using nlapiScheduleScript.
To execute a scheduled script on-demand, set the deployment status to either Not Scheduled
or Testing for the following reasons:
Deployment Status
Use Case
Testing
Set to Testing for the following reasons:
Not Scheduled
•
You want to test the script by running it immediately. The script will run
only in the script owner’s account. After setting the deployment status to
Testing, click Save and Execute on the Script Deployment page to run
the script.
•
You want to load the script into the SuiteScript Debugger. Only
scheduled scripts with the deployment status set to Testing can be
loaded into the Debugger.
Set to Not Scheduled after all of the scheduling options have been set (time,
date, frequency); however, the script is not yet ready to be executed.
Important: If you set your scheduling options, set the deployment status to
Not Scheduled, and simply click Save, the script will not run at the times you
may have specified.
Scripts with a deployment status set to Not Scheduled will only run if you click
Save and Execute (or the scripts are placed into the NetSuite scheduling
queue via nlapiScheduleScript.)
To schedule a script for immediate execution:
1.
After creating your SuiteScript JavaScript file, create a new Script record for your
script. Go to Setup > Customization > Scripts > New > Scheduled.
2.
On the Script page, provide a name for the Script record.
3.
On the Scripts tab, select your script file from the Script File drop-down and specify
the script’s executing function.
4.
Next, click Save.
5.
Click the Deploy Script button on the page that appears.
6.
When the Script Deployment page opens, click the Deployed checkbox if it is not
already checked, and select Not Scheduled from the Status drop-down (see figure).
7.
Click the Single Event radio button.
8.
Next, click Save and Execute.
SuiteScript Developer and Reference Guide
Scheduled Scripts
Deploying Scheduled Scripts
266
Notes:
•
If you set the deployment status to Not Scheduled, and then select either Daily Event,
Weekly Event (or any event type other than Single Event), and click Save and Execute,
the script will still only run once.
•
After a Not Scheduled script completes its immediate (ad-hoc) execution, NetSuite
automatically sets the deployment status to Completed. Regardless of any additional
Daily, Weekly, etc., deployment times that might have been specified, the script cannot
execute again until its deployment status is manually changed from Completed to
either Not Scheduled, Testing, or Scheduled. See the diagram in Scheduled Script
Deployment Statuses for details.
SuiteScript Developer and Reference Guide
Scheduled Scripts
Deploying Scheduled Scripts
267
Scheduling a Script to Run in the Future
Scheduled scripts with a deployment status set to Scheduled can be set to run once at a predefined time in the future, or they can be scheduled to run on a more regular daily, weekly,
monthly, or yearly basis. Note that deployment times can only be scheduled in 30 minute
intervals, for example 2:00 pm., 2:30 pm., 3:00 pm.
A scheduled script’s deployment status should be set to Scheduled for the following reasons:
•
The script was set to Testing, but is now ready for production.
•
The script does not need to be executed immediately.
•
The script must run at recurring times.
To schedule a script to run at a scheduled time or recurring times:
1.
After creating your SuiteScript JavaScript file, create a new Script record for your
script. Go to Setup > Customization > Scripts > New > Scheduled.
2.
On the Script page, provide a name for the Script record.
3.
On the Scripts tab, select your script file from the Script File drop-down, and specify
the script’s function.
4.
Next, click Save.
5.
Click the Deploy Script button on the page that appears.
6.
When the Script Deployment page opens, click the Deployed checkbox if it is not
already checked, and select Scheduled from the Status drop-down (see figure).
7.
On the Schedule tab, set all deployment options (see figure).
8.
Click Save.
SuiteScript Developer and Reference Guide
Scheduled Scripts
Creating Multiple Deployments for a Scheduled Script
268
Creating Multiple Deployments for a Scheduled Script
On either the Script record page or the Script Deployment page you can create multiple
deployments for the same script. See these sections for more information:
•
Use Cases for Creating Multiple Deployments
•
Steps for Creating Multiple Deployments
•
Multiple Deployments and nlapiScheduleScript
Use Cases for Creating Multiple Deployments
[UE=HELP_TOPIC_OUT_OF_DATE_ALERT=UE]
The following use cases describe possible scenarios in which script owners may want to create
multiple deployments for a single scheduled script.
•
Use Case 1 - Same Script Requires Different Deployment Schedules
•
Use Case 2 - Same Script Receives Multiple Requests for Execution
•
Use Case 3 - Script May Exceed Unit-based Goverance Limits
Use Case 1 - Same Script Requires Different Deployment Schedules
Create multiple deployments when you want the same script to execute according to different
deployment schedules.
For example, you might have a scheduled script that you want deployed and executed on the
last day of every month. This would be your first deployment. At the same time, you might also
want this script deployed and executed every Monday morning at 2:00 am. This would be your
second, separate deployment for this script.
Use Case 2 - Same Script Receives Multiple Requests for Execution
There may be times when you have concurrent (simultaneous) requests to kick off longrunning tasks. In situations like this, you want to be able to schedule the next available
deployment for each request that comes in. For example, if you think that at peak load you
might receive five requests in a given time frame, then you would want at least that many script
deployments available to ensure that each request gets its own dedicated script deployment.
Note that if one of the deployments already happens to be in progress or in the queue, the best
practice is to take the number of requests you expect over some time period (for example, over
a five minute period - which is more than the average script execution time) and then multiply
by two to get the number of script deployments you would need to ensure that you can handle
the load. In this case you would want to create 10 deployments for the same script.
Use Case 3 - Script May Exceed Unit-based Goverance Limits
Another reason to create multiple deployments is if you have a script you think will exceed
governance limits. After creating different deployments, you can specify a different
SuiteScript Developer and Reference Guide
Scheduled Scripts
Creating Multiple Deployments for a Scheduled Script
269
deployment through the deployId parameter in nlapiScheduleScript(scriptId, deployId,
params).
Note: See SuiteScript Governance for information on scheduled script governance limits.
Important: All companies that run NetSuite are provided a single queue for running
their scheduled scripts. You can upgrade your number of scheduled script
queues to five by purchasing NetSuite’s SuiteCloud Plus module. See Using
Multiple Script Queues to Run Scheduled Scripts for more information.
Steps for Creating Multiple Deployments
To schedule multiple deployments for the same script:
1.
On the Script record page > Deployments tab, set your deployment options (see first
figure).
2.
Click Add after setting your deployment values.
3.
Create another deployment (if necessary).
4.
Optionally, create your own unique deployment ID in the ID column. If you do not
add your own custom deployment ID (see figure), an ID is automatically generated.
5.
When finished creating all deployments, click Save.
SuiteScript Developer and Reference Guide
Scheduled Scripts
Creating Multiple Deployments for a Scheduled Script
270
To edit or access each deployment, go to Setup > Customization > Script Deployments. The
following figure shows the Script Deployments list page, which lists all deployments in your
account.
Creating additional deployments
You can easily create additional script deployments from existing deployments. This is useful
for quickly adding extra deployments for scheduled scripts.
1.
On the Script Deployments page, click View on an existing deployment
2.
From the More Actions dropdown click Make Copy
3.
Check the details for the deployment, correcting as necessary
4.
Click Save.
Note: Make Copy is only available for Scheduled scripts.
Multiple Deployments and nlapiScheduleScript
You can create multiple on-demand deployment instances and parameterize the call to
nlapiScheduleScript. Users can queue-up multiple instances of the same Not Scheduled script.
The nlapiScheduleScript API will call the first of the script deployments that is ready and in the
queue, and continue to call this same script until each instance of the script has been deployed.
This means that users can queue as many instances of the Not Scheduled script through User
Event scripts as they have deployments.
In this scenario, it is not recommended that users set the deployId parameter in
nlapiScheduleScript since the deployments are generally “ad-hoc” and created real-time.
SuiteScript Developer and Reference Guide
Scheduled Scripts
Creating Multiple Deployments for a Scheduled Script
Note: For more information on nlapiScheduleScript, see Running Scheduled Scripts
Using nlapiScheduleScript. Also see the API documentation for
nlapiScheduleScript(scriptId, deployId, params).
SuiteScript Developer and Reference Guide
271
Scheduled Scripts
Running Scheduled Scripts Using nlapiScheduleScript
272
Running Scheduled Scripts Using nlapiScheduleScript
You can programmatically place a scheduled script into your company’s scheduling queue
using the nlapiScheduleScript API. Be sure that the script’s deployment status appears as either
Not Scheduled or Completed on the Script Deployment page.
Using nlapiScheduleScript you can:
•
Place a currently executing scheduled script back into the scheduling queue
•
Call another scheduled script from within a scheduled script. When the new script is
called, it is then put into the scheduling queue.
•
Place a scheduled script into the queue from another script such as a user event script
or a suitelet.
The ability to call nlapiScheduleScript from within a scheduled script allows developers to
automatically place their currently executing script back into the scheduling queue.
Otherwise, scheduled scripts must be requeued manually through the Script Deployment page.
See Example 2 in Scheduled Script Samples for code that shows how to programmatically
requeue a scheduled script.
Developers should call nlapiScheduleScript in a scheduled script if they think the script is
coming close to exceeding the 10,000 unit limit allotted to scheduled scripts. The call to
nlapiScheduleScript will place the script back in the queue, and the script can then run to
completion without exceeding any governance limits.
Note that if nlapiScheduleScript is used in a scheduled script to call another scheduled script,
instruction count limits are applied to each script separately, since (technically) you are
running two different scheduled scripts. In other words, both “scheduled script A” and
“scheduled script B,” which was called by “scheduled script A” can each contain 10,000 units.
Note: See SuiteScript Governance for information on unit-based governance limits.
Related Topics
•
•
•
•
Understanding Scheduled Script Execution
Scheduled Script Best Practices
Setting Recovery Points in Scheduled Scripts
Understanding Memory Usage in Scheduled Scripts
Setting the Scheduled Script type Argument
When creating a scheduled script, you can associate a type argument that is passed by the
system to the script’s executing function. The type argument provides a context for when the
scheduled script is invoked.
SuiteScript Developer and Reference Guide
Scheduled Scripts
Setting Recovery Points in Scheduled Scripts
273
Important: The type argument is an auto-generated argument passed by the system.
You cannot set this as a parameter for a specific deployment like other
function arguments.
Valid values for the type argument are:
•
scheduled - normal execution according to the deployment options specified in the UI
•
ondemand - the script is executed via a call to nlapiScheduleScript
•
userinterface - the script is executed via the UI (ie., the Save & Execute button has
been clicked)
•
aborted - re-executed automatically following an aborted execution (system went
down during execution)
•
skipped - executed automatically following downtime during which the script should
have been executed
Example
function processOrdersCreatedToday( type )
{
//only execute when run from the scheduler, based on the deployment options set in the UI
if ( type != 'scheduled' && type != 'skipped' ) return;
.... //process rest of script
}
Related Topics
•
•
•
Scheduled Scripts
Understanding Scheduled Script Execution
Scheduled Script Samples
Setting Recovery Points in Scheduled Scripts
Occasionally while running a scheduled script a failure may occur. This could be due to a
major NetSuite upgrade, or simply an unexpected failure of the execution environment.
Therefore, NetSuite gives developers the ability to create recovery points in scheduled scripts.
These recovery points allow the state of the script at a certain point to be saved. In the event of
an unexpected system failure, the script can be restarted from the last successful recovery
point.
To set a script recovery point, use nlapiSetRecoveryPoint(). When the system restarts, the
script will resume where it left off.
SuiteScript Developer and Reference Guide
Scheduled Scripts
Understanding Memory Usage in Scheduled Scripts
274
Developers can also use nlapiYieldScript(). In addition to setting a recovery point, this API
places the script back into the scheduled script queue. Once the script moves to the front of the
queue for processing, it begins its execution from the specified recovery point.
Possible use cases for nlapiSetRecoveryPoint()and nlapiYieldScript() include:
•
If the script is unexpectedly aborted, it can be restarted from the last successful
recovery point.
•
Pause (yield) the execution of a script at a specified point.
•
Governance usage limits have been reached.
•
Yield a script because an external resource is temporarily unavailable.
See the API documentation on nlapiSetRecoveryPoint()and nlapiYieldScript() for more details
and example usage.
Related Topics
•
•
•
•
Scheduled Scripts
Understanding Scheduled Script Execution
Scheduled Script Samples
Understanding Memory Usage in Scheduled Scripts
Understanding Memory Usage in Scheduled Scripts
The memory limit for a scheduled script is 50 Megabytes. Therefore, if you have a longrunning scheduled script, and you are concerned the script will exceed the 50 MB memory
limit, NetSuite recommends using nlapiSetRecoveryPoint() or nlapiYieldScript() APIs to track
memory size. This is accomplished by examining the returned size property in the status object
returned by nlapiSetRecoveryPoint() and nlapiYieldScript().Note, however, calling
nlapiSetRecoveryPoint() costs 100 governance units. Therefore, you will want to use the API
only at key points in your script. The alternative approach is to use nlapiYieldScript(). If the call
is successful, the script will yield and then the size property can be examined after the script
resumes.
Important: Scripts that are resumed after an nlapiYieldScript() or nlapiSetRecoveryPoint()
call will have their governance units reset. However, this does not reset the memory footprint
of the script, which will continue to change until the script terminates. Therefore it is possible
for the script to stay under the governance limit but exceed the memory size limit, at which
point an SS_EXCESSIVE_MEMORY_FOOTPRINT error is thrown during the call to
nlapiYieldScript() or nlapiSetRecoveryPoint().
Reducing the Memory Footprint of your Scripts
The table below shows an estimation of how various parts of a script can consume memory.
SuiteScript Developer and Reference Guide
Scheduled Scripts
Understanding Memory Usage in Scheduled Scripts
Empty Function
111 bytes
Each Instruction within a function
32 bytes
Each local variable reference
32 bytes
Standard mode record (customer)
40 kilobytes (depends on record type)
Dynamic mode record (customer)
460 kilobytes (depends on record type)
Number Instance
32 bytes
String Instance
32 bytes + 4 bytes per character
Empty Object
32 bytes
275
There are several useful techniques to reduce the memory overhead of scripts. Certain
returned objects, for example nlobjRecord and nlobjSearchResult can be quite large. In order to
reduce the memory consumed by these objects, convert them to native JavaScript objects and
then operate on those objects instead.
Related Topics
•
•
•
•
Scheduled Scripts
Understanding Scheduled Script Execution
Scheduled Script Samples
Setting Recovery Points in Scheduled Scripts
SuiteScript Developer and Reference Guide
Scheduled Scripts
Monitoring Scheduled Scripts
276
Monitoring Scheduled Scripts
[UE=HELP_TOPIC_OUT_OF_DATE_ALERT=UE]
You can monitor scheduled script execution by:
•
Using the Scheduled Script Status Page
•
Using the Scheduled Scripts Calendar Page
•
Using APIs to Work with Scheduled Scripts
Using the Scheduled Script Status Page
The Scheduled Script Status page shows the current and past statuses of all scheduled scripts
that have been executed in your account. Access this page by going to Setup > Customization >
Script Deployments > Status.
Note: Script execution details are purged after 30 days.
Notice that the Status column displays values that are different from the deployment status
values. The values that appear in the Status column reflect internal NetSuite scheduled script
work queue statuses, NOT deployment statuses.
The following table provides a mapping of these status types:
Script work queue statues (as they appear on
the Scheduled Script Status page)
Script deployment statuses (as they appear on the
Script Deployment page)
Pending
In Queue
Processing
In Progress
Deferred
In Queue
Complete
Completed or Scheduled
Failed
Completed or Scheduled
Retry
In Progress
Using the Scheduled Scripts Calendar Page
The Scheduled Scripts calendar page shows you all scheduled scripts that are set to deploy (in
both Testing and Release mode) during a given day, week, or month. To access this page, go to
SuiteScript Developer and Reference Guide
Scheduled Scripts
Scheduled Script Samples
277
a schedule script’s Script page or Script Deployment page and click the Go To Calendar
crosslink (see figure).
If you are on the day view of the calendar, you can create a new scheduled script to run on that
day by clicking the New Scheduled Script button at the bottom of the page. If you are on the
week or month views, you can create a new scheduled script by clicking the plus ( + ) icon that
appears in each day field of the week or month.
Using APIs to Work with Scheduled Scripts
The following APIs are helpful when working with and monitoring scheduled scripts:
•
nlapiLogExecution(type, title, details)
•
nlobjContext methods:
• setPercentComplete(pct)
• getPercentComplete()
• getRemainingUsage()
• getScriptId()
• getDeploymentId()
Scheduled Script Samples
The following scheduled script code samples are provided in this section:
•
Example 1 - Fulfill and Bill Sales Orders on a Daily Basis
•
Example 2 - Reschedule a Script Depending on Units Remaining
•
Example 3 - Create a Drip Marketing Campaign
•
Example 4 - Automatically Send ‘Thank You’ Emails to Valued Customers
•
Example 5 - Passing Script Parameters in a Scheduled Script
SuiteScript Developer and Reference Guide
Scheduled Scripts
Scheduled Script Samples
278
Example 1 - Fulfill and Bill Sales Orders on a Daily Basis
This script fulfills and bills all sales orders created today. This is a batch operation that would
normally take a long time to execute, making it an ideal candidate for a scheduled script.
function processOrdersCreatedToday( type )
{
//only execute when run from the scheduler
if ( type != 'scheduled' && type != 'skipped' ) return;
var filters = new Array();
filters[0] = new nlobjSearchFilter( 'mainline', null, 'is', 'T' );
filters[1] = new nlobjSearchFilter( 'trandate', null, 'equalTo', 'today' );
var searchresults = nlapiSearchRecord( 'salesorder', null, filters, null, new nlobjSearchColumn('terms') );
for ( var i = 0; searchresults != null && i < searchresults.length; i++ )
{
var id = searchresults[i].getId();
var fulfillRecord = nlapiTransformRecord('salesorder', id, 'itemfulfillment');
nlapiSubmitRecord( fulfillRecord );
var billType = searchresults[i].getValue('paymentmethod') == null ? 'invoice' : 'cashsale';
var billRecord = nlapiTransformRecord('salesorder', id, billType);
nlapiSubmitRecord( billRecord );
}
}
Example 2 - Reschedule a Script Depending on Units Remaining
Use nlapiScheduleScript, nlobjContext.getScriptId(), and nlobjContext.getDeploymentId() to
reschedule the currently executing scheduled script if there are more sales orders to update
when the unit usage limit is reached.
function updateSalesOrders()
{
var context = nlapiGetContext();
var searchresults = nlapiSearchRecord('salesorder', 'customscript_orders_to_update')
if ( searchresults == null )
return;
for ( var i = 0; i < searchresults.length; i++ )
{
nlapiSubmitField('salesorder', searchresults[i].getId(), 'custbody_approved', 'T')
if ( context.getRemainingUsage() <= 0 && (i+1) < searchresults.length )
{
var status = nlapiScheduleScript(context.getScriptId(), context.getDeploymentId())
if ( status == 'QUEUED' )
break;
}
}
}
Example 3 - Create a Drip Marketing Campaign
This example illustrates a daily scheduled script for processing a simple drip marketing
campaign with two touch points and one branch point. The basic workflow involves:
SuiteScript Developer and Reference Guide
Scheduled Scripts
Scheduled Script Samples
279
•
Schedule Campaign for new leads (clone and schedule an existing campaign)
•
Schedule follow-up Campaign for leads that are seven days old but whose statuses have
not changed
•
Schedule follow-up phone calls for sales reps assigned to these leads
•
Schedule Campaign for leads that are seven days old whose statuses have since been
upgraded
Parameters & Setup
•
custscript_newleads campaign list parameter containing base campaign used for
emailing new leads
•
custscript_weekold campaign list parameter containing base campaign used for
emailing week old unchanged leads
•
custscript_converted campaign list parameter containing base campaign used for
emailing week old upgraded leads
•
custscript_leadstatus entitystatus list parameter containing the status used to define
what a "new" lead is.
function processDripMarketing( type )
{
if ( type != 'scheduled' ) return; /* script should only execute during scheduled calls. */
/* process new leads */
scheduleCampaign( custscript_newleads );
/* process one-week old unchanged leads */
scheduleCampaign( custscript_weekold );
/* process follow-up for one-week old unchanged leads */
scheduleFollowUpPhoneCall();
/* process follow-up email for one-week old converted leads. */
scheduleCampaign( custscript_converted );
}
function scheduleCampaign( base_campaign )
{
var today = nlapiDateToString( new Date() );
var campaign = nlapiCopyRecord('campaign', base_campaign);
campaign.setFieldValue('startdate', today);
campaign.setFieldValue('title',campaign.getFieldValue('title') + ' (' + today + ')');
campaign.setLineItemValue('campaignemail','status',1,'EXECUTE');
campaign.setLineItemValue('campaignemail','datescheduled',1,today);
nlapiSubmitRecord( campaign );
}
function scheduleFollowUpPhoneCall()
{
var filters = new Array();
filters[0] = new nlobjSearchFilter('datecreated',null,'on','daysago7');
SuiteScript Developer and Reference Guide
Scheduled Scripts
Scheduled Script Samples
filters[1] = new nlobjSearchFilter('status',null,'equalto', custscript_leadstatus);
var columns = new Array();
columns[0] = new nlobjSearchColumn('salesrep');
columns[1] = new nlobjSearchColumn('phone');
columns[2] = new nlobjSearchColumn('entityid');
var today = nlapiDateToString( new Date() );
var leads = nlapiSearchRecord('customer',null,filters,columns);
for ( var i = 0; leads != null && i < leads.length; i++ )
{
var leadId = leads[i].getId();
var salesrep = leads[i].getValue('salesrep');
var phonenumber = leads[i].getValue('phone');
var leadName = leads[i].getValue('entityid');
/* Schedule Phone Call only if the lead is assigned and has a number. */
if ( salesrep != null && phonenumber != null )
{
var call = nlapiCreateRecord('phonecall');
call.setFieldValue('title','Follow up Call for '+leadName);
call.setFieldValue('startdate', today );
call.setFieldValue('assigned', salesrep );
call.setFieldValue('phone', phonenumber );
call.setFieldValue('company', leadId );
call.setFieldValue('status','SCHEDULED');
nlapiSubmitRecord( call );
}
}
}
SuiteScript Developer and Reference Guide
280
Scheduled Scripts
Scheduled Script Samples
281
Example 4 - Automatically Send ‘Thank You’ Emails to Valued Customers
This sample shows how to create a scheduled script to send thank you notes to valued, repeated
customers. A scheduled script may be executed to perform daily searches for sales orders that
are placed today and within the last 30 days from the same customer. After retrieving the
results, the scheduled script then sends these customers an email on behalf of the sales rep to
thank them for their repeated business.
Notice there are a number of nlobjContext.getRemainingUsage() API calls in the sample. This
API provides the remaining SuiteScript usage to help scripts monitor how close they are to
running into SuiteScript usage governance.
/****************************************************
* This scheduled script looks for customers that
* have placed multiple orders in the last 30 days.
* It will send a thank you email to these customers
* on behalf of their sales reps.
*/
function findHotCustomerScheduled(type)
{
//Invoke only when it is scheduled
if(type == 'scheduled')
{
//Obtaining the context object and logging the remaining usage available
var context = nlapiGetContext();
nlapiLogExecution('DEBUG', 'Remaining usage at script beginning', context.getRemainingUsage());
//Setting up filters to search for sales orders
//with trandate of today.
var todaySOFilters = new Array();
todaySOFilters[0] = new nlobjSearchFilter('trandate', null, 'on', 'today');
//Setting up the columns. Note the join entity.salesrep column.
var todaySOColumns = new Array();
todaySOColumns[0] = new nlobjSearchColumn('tranid', null, null);
todaySOColumns[1] = new nlobjSearchColumn('entity', null, null);
todaySOColumns[2] = new nlobjSearchColumn('salesrep', 'entity', null);
//Search for the sales orders with trandate of today
var todaySO = nlapiSearchRecord('salesorder', null, todaySOFilters, todaySOColumns);
nlapiLogExecution('DEBUG', 'Remaining usage after searching sales orders from today',
context.getRemainingUsage());
//Looping through each result found
for(var i = 0; todaySO != null && i < todaySO.length; i++)
{
//obtain a result
var so = todaySO[i];
//Setting up the filters for another sales order search
//that are of the same customer and have trandate within
//the last 30 days
var oldSOFilters = new Array();
SuiteScript Developer and Reference Guide
Scheduled Scripts
Scheduled Script Samples
282
var thirtyDaysAgo = nlapiAddDays(new Date(), -30);
oldSOFilters[0] = new nlobjSearchFilter('trandate', null, 'onorafter', thirtyDaysAgo);
oldSOFilters[1] = new nlobjSearchFilter('entity', null, 'is', so.getValue('entity'));
oldSOFilters[2] = new nlobjSearchFilter('tranid', null, 'isnot', so.getValue('tranid'));
//Search for for the repeated sales in the last 30 days
var oldSO = nlapiSearchRecord('salesorder', null, oldSOFilters, null);
nlapiLogExecution('DEBUG', 'Remaining usage after in for loop, i=' + i, context.getRemainingUsage());
//If results are found, send a thank you email
if(oldSO != null)
{
//Setting up the subject and body of the email
var subject = 'Thank you!';
var body = 'Dear ' + so.getText('entity') + ', thank you for your repeated business in the last 30 days.';
//Sending the thank you email to the customer on behalf of the sales rep
//Note the code to obtain the join column entity.salesrep
nlapiSendEmail(so.getValue('salesrep', 'entity'), so.getValue('entity'), subject, body);
nlapiLogExecution('DEBUG', 'Remaining usage after sending thank you email',
context.getRemainingUsage());
}
}
}
}
Example 5 - Passing Script Parameters in a Scheduled Script
The following sample shows how to retrieve passed parameters (by calling the getSetting(...)
method on the nlobjContext object) within a scheduled script. It also shows how to execute a
scheduled script by passing the custom ID (scriptId) of the Script record and the custom
deployment ID (deployId) of the Script Deployment record. For details on working with script
parameters, see Creating Script Parameters Overview.
//retrieve parameters inside a scheduled script
function scheduled_main()
{
//get script parameter values
var context = nlapiGetContext();
var strStartDate = context.getSetting('SCRIPT', 'custscriptstartdate');
var subsidiary = context.getSetting('SCRIPT', 'custscriptsubsidiary');
var startDate = new Date(strStartDate);
//schedule the script execution and define script parameter values
var startDate = new Date();
var params = new Array();
params['custscriptstartdate'] = startDate.toUTCString();
params['custscriptsubsidiary'] = 42;
//so that the scheduled script API knows which script to run, set the custom ID
//specified on the Script record. Then set the custom ID on the Script Deployment
nlapiScheduleScript('customscript_audit_report', 'customdeploy_audit_report_dp', params);
}
SuiteScript Developer and Reference Guide
Scheduled Scripts
Using Multiple Script Queues to Run Scheduled Scripts
283
Note: Since scheduled scripts also trigger user event scripts, developers may need to
revisit the design of their user event scripts to ensure they will be invoked by the
correct execution contexts.
Using Multiple Script Queues to Run Scheduled Scripts
All companies that run NetSuite are provided a single queue for running their scheduled
scripts. As part of the SuiteCloud Plus offering, which is available for purchase, companies can
upgrade their number of scheduled script queues from one to five. This offering allows larger
accounts to divide their scheduled script work into categories such as script type, script length,
department, and so on.
Important: There are never more than five scheduled script queues regardless of how
many SuiteCloud Plus licenses are purchased.
When you upgrade your account to include five script queues, the scripts in each queue will
execute serially. For example, if there are two scripts in Queue 1, the first script must complete
before the second script begins. Across all five queues, the scripts will execute concurrently. For
example, if you have one script in each of the five queues, all scripts will run at the same time.
After purchasing the SuiteCloud Plus module, you will notice that a Queue dropdown field is
added to the Script Deployment record for scheduled scripts. The script author or
administrator can use this field to set the target queue of a script. Note that to process the same
script concurrently, scriptors can create multiple deployments for the same script, and then set
each deployment to a different queue.
Additionally, a Queue column will appear on the Script Deployment Status page to indicate
which queue a script has been deployed to. Users can set the Queue filter on the bottom of this
page to sort scripts based on queue number.
Should you choose to purchase SuiteCloud Plus add-on module, be aware that all of your
existing scripts will, by default, initially be put into Queue 1. You will need to go the Script
Deployment pages of each schedule script to reassign the script to another queue. Also note
that if you do not assign a queue number to a new script, the script will automatically be
assigned to Queue 1.
To learn more about SuiteCloud Plus, or to purchase this new add-on module, contact your
NetSuite account manager.
Setting the Scheduled Script queue Argument
Once you have purchased the SuiteCloud Plus add-on module, you can use the queue
argument to obtain the queue number assigned to the scheduled script. The queue argument is
the second argument passed to the launch function of a scheduled script. (The first argument is
the type argument. For details see, Setting the Scheduled Script type Argument.)
The queue argument provides the id of the queue you selected in the Queue field of the
scheduled script’s Script Deployment page.
SuiteScript Developer and Reference Guide
Scheduled Scripts
Using Multiple Script Queues to Run Scheduled Scripts
284
Important: The queue argument is an auto-generated argument passed by the system.
You cannot set this as a parameter for a specific deployment like other
function arguments.
Valid values for the queue argument are: 1, 2, 3, 4, 5, as there are five queues offered through
SuiteCloud Plus.
Example
function processOrdersCreatedToday( type, queue )
{
//only execute when run from the scheduler and the script is in queue 5,
// based on the deployment options set in the UI
if ( type != 'scheduled' && type != 'skipped' && queue == 5 ) return;
.... //process rest of script
}
Related Topics
•
•
•
Scheduled Scripts
Understanding Scheduled Script Execution
Scheduled Script Samples
SuiteScript Developer and Reference Guide
Chapter 24 Portlet Scripts
The following topics are covered in this section:
•
What Are Portlet Scripts?
•
Portlet Script Execution
•
Assigning the Portlet Preference to a Script Parameter
•
Running a Portlet Script in NetSuite
•
Displaying Portlet Scripts on the Dashboard
•
Portlet Scripts Samples
What Are Portlet Scripts?
Portlet scripts can be used to define and publish custom dashboard content. The following
portlet types can be created:
•
LIST - A standard list of user-defined column headers and rows (for example a Search
Results portlets). See List Portlet for an example of a list portlet.
•
FORM - A basic data entry form with up to one submit button embedded into a
portlet (for example a Quickadd portlet). This type of portlet supports APIs to refresh
and resize the portlet, as well as the use of record-level client-side script to implement
validation. See Form-level and Record-level Client Scripts for details about this type of
script. See Form Portlet for an example of a form portlet.
•
HTML - An HTML-based portlet, the most flexible presentation format used to
display free-form HTML (images, Flash, custom HTML). See HTML Portlet for an
example of an HTML portlet.
•
LINKS - This default portlet consists of rows of simple formatted content (for example
an RSS portlet). See Links Portlet for an example of a links portlet.
Be aware that the portlet type (LIST, FORM, HTML, LINKS) is not actually passed as a value in
the portlet script itself, rather it is defined on the portlet Script record page (see figure below).
Once you create your portlet .js file, you will load your .js file into the file cabinet, create a new
script record for your file (Setup > Customization > Scripts > New > Portlet), and then select
the portlet type from the Portlet Type drop-down menu.
SuiteScript Developer and Reference Guide
Portlet Scripts
Portlet Script Execution
286
Related Topics
•
•
•
•
Portlet Script Execution
Portlet Scripts Samples
SuiteScript Functions
Enabling SuiteScript
Portlet Script Execution
Portlet scripts run on the server and are rendered in the NetSuite dashboard. A user-defined
portlet function is executed whenever a SuiteScript-generated portlet is opened or refreshed by
the user.
When writing portlet scripts, NetSuite automatically passes two arguments to your userdefined function. These arguments are:
•
portlet - References a nlobjPortlet object
•
column - Column index for this portlet on the dashboard (valid values are: 1 = left
column, 2 = middle column, 3 = right column)
For custom portlets on Customer Dashboards, NetSuite can pass the following additional
argument:
•
entityid - References the customer ID for the selected customer.
Example
function mySamplePortlet(portlet, column)
{
remainder of portlet script...
}
SuiteScript Developer and Reference Guide
Portlet Scripts
Assigning the Portlet Preference to a Script Parameter
287
Note that column is an optional argument. If you choose not to pass a column value in your
script, you can simply write:
function mySamplePortlet(portlet)
{
remainder of portlet script...
}
Portlet scripts can only run after users have added the scripts to their dashboards. Once the
scripts have been added, users must then open their dashboards for a portlet script to execute.
Note: Note: To add portlet scripts to the dashboard, see Displaying Portlet Scripts on the
Dashboard.
Related Topics
•
•
•
Portlet Scripts Samples
Running a Portlet Script in NetSuite
SuiteScript Functions
Assigning the Portlet Preference to a Script Parameter
Portlet script parameters (custom fields) can be configured to be customizable as portlet
settings. This allows users to modify their script parameters for each portlet. For information
on setting the portlet preference on script parameters, see Setting Script Parameter Preferences.
If you are not familiar with the concept of script parameters, see Creating Script Parameters
Overview.
Related Topics
•
•
•
Portlet Scripts
Portlet Script Execution
Portlet Scripts Samples
Running a Portlet Script in NetSuite
To run a portlet script in NetSuite, you must:
1.
Create a JavaScript file for your portlet script.
2.
Load the file into NetSuite.
3.
Create a Script record.
4.
Define all runtime options on the Script Deployment page.
If you are new to SuiteScript and need information on each of these steps, see Running Scripts
in NetSuite Overview.
SuiteScript Developer and Reference Guide
Portlet Scripts
Displaying Portlet Scripts on the Dashboard
288
Important: Portlets scripts require that you reference the script from a custom portlet.
See Displaying Portlet Scripts on the Dashboard for details.
Related Topics
•
•
What Are Portlet Scripts?
Portlet Scripts Samples
Displaying Portlet Scripts on the Dashboard
If you have created a portlet using SuiteScript, use these steps to display the custom portlet on
your dashboard. Note that the following steps are to be completed only after you have
performed all steps in the section Running a Portlet Script in NetSuite.
To display portlet scripts on the dashboard:
1.
Go to your dashboard and click the Personalize Dashboard link.
2.
Click one of the Custom Portlet links under the Standard Content folder.
An empty Custom Content portlet appears on your dashboard.
3.
Hover over the Portlet Setup arrow and click Set Up.
4.
In the Set Up Scripted Content popup, select the desired portlet script from the Source
drop-down list, and then click Save.
The portlet will populate with data as defined in your portlet script.
Related Topics
•
•
Portlet Scripts
Portlet Scripts Samples
Portlet Scripts Samples
The following sample portlets are provided:
•
List Portlet
•
Form Portlet
•
HTML Portlet
SuiteScript Developer and Reference Guide
Portlet Scripts
Portlet Scripts Samples
•
Links Portlet
SuiteScript Developer and Reference Guide
289
Portlet Scripts
Portlet Scripts Samples
List Portlet
This script searches for a list of estimates and displays the results in a list format. See
nlobjPortlet for a list of portlet object methods.
Script:
function demoListPortlet(portlet, column)
{
portlet.setTitle(column != 2 ? "Estimates List" : "Estimates List Detail")
var col = portlet.addColumn('tranid','text', 'Number', 'LEFT');
col.setURL(nlapiResolveURL('RECORD','estimate'));
col.addParamToURL('id','id', true);
portlet.addColumn('trandate','date', 'Date', 'LEFT');
portlet.addColumn('entity_display','text', 'Customer', 'LEFT');
if ( column == 2 )
{
portlet.addColumn('salesrep_display','text', 'Sales Rep', 'LEFT');
portlet.addColumn('amount','currency', 'Amount', 'RIGHT');
}
var returncols = new Array();
returncols[0] = new nlobjSearchColumn('trandate');
returncols[1] = new nlobjSearchColumn('tranid');
returncols[2] = new nlobjSearchColumn('entity');
returncols[3] = new nlobjSearchColumn('salesrep');
returncols[4] = new nlobjSearchColumn('amount');
var results = nlapiSearchRecord('estimate', null, new
nlobjSearchFilter('mainline',null,'is','T'), returncols);
for ( var i = 0; i < Math.min((column != 2 ? 5 : 15 ),results.length); i++ )
portlet.addRow( results[i] )
}
SuiteScript Developer and Reference Guide
290
Portlet Scripts
Portlet Scripts Samples
291
Form Portlet
This script builds a very simple form in a portlet that POSTs data to a servlet. This form
includes one embedded Submit button.
See nlobjPortlet for a list of portlet object methods.
Note: If you are viewing this sample through the NetSuite Help Center, be sure to widen
the main frame until there is no longer a horizontal scrollbar under the sample. In
some browsers, the scrollbar may end up cutting off the last line of the sample.
Script:
function demoSimpleFormPortlet(portlet, column)
{
portlet.setTitle('Simple Form Portlet')
var fld = portlet.addField('text','text','Text');
fld.setLayoutType('normal','startcol');
portlet.addField('integer','integer','Integer');
portlet.addField('date','date','Date');
var select = portlet.addField('fruit','select','Select');
select.addSelectOption('a','Oranges');
select.addSelectOption('b','Apples');
select.addSelectOption('c','Bananas');
portlet.addField('textarea','textarea','Textarea');
portlet.setSubmitButton(nlapiResolveURL('SUITELET','customscript_simpleformbackend',
'customdeploy_simpleform'),'Submit');
SuiteScript Developer and Reference Guide
Portlet Scripts
Portlet Scripts Samples
}
SuiteScript Developer and Reference Guide
292
Portlet Scripts
Portlet Scripts Samples
293
HTML Portlet
This portlet script generates the HTML required to download and display a FLASH animation
in an HTML portlet. See nlobjPortlet for a list of portlet object methods.
Script:
function demoRichClientPortlet(portlet, column)
{
portlet.setTitle('Flash Portlet')
var content = "<table align=center border=0 cellpadding=3 cellspacing=0
width=100%><tr><td>"+
"<OBJECT CLASSID='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000'>"+
"<PARAM NAME='MOVIE' VALUE='/images/flash/tomato.swf '>"+
"<embed src='/images/flash/tomato.swf '></embed></OBJECT></td>
</tr></table>";
content = '<td><span>'+ content + '</span></td>'
portlet.setHtml( content );
}
Links Portlet
This script makes an external request to slashdot.org in order to retrieve and display an RSS
feed in a LINKS portlet. The APIs used are nlapiRequestURL(url, postdata, headers, callback,
httpMethod) to fetch the RSS feed, nlapiStringToXML(text) to convert the feed into an XML
document, and nlapiSelectNodes(node, xpath) / nlapiSelectValue(node, xpath) to query the
XML document for the RSS data.
See nlobjPortlet for a list of portlet object methods.
Script:
function demoRssPortlet(portlet)
{
portlet.setTitle('Custom RSS Feed');
SuiteScript Developer and Reference Guide
Portlet Scripts
Portlet Scripts Samples
var feeds = getRssFeed();
if ( feeds != null && feeds.length > 0 )
{
for ( var i=0; i < feeds.length ; i++ )
{
portlet.addLine('#'+(i+1)+': '+feeds[i].title, feeds[i].url, 0);
portlet.addLine(feeds[i].description, null, 1);
}
}
}
function getRssFeed()
{
var url = 'http://rss.slashdot.org/Slashdot/slashdot';
var response = nlapiRequestURL( url, null, null );
var responseXML = nlapiStringToXML( response.getBody() );
var rawfeeds = nlapiSelectNodes( responseXML, "//item" );
var feeds = new Array();
for (var i = 0; i < rawfeeds.length && i < 5 ; i++)
{
feeds[feeds.length++] = new rssfeed( nlapiSelectValue(rawfeeds[i], "title"),
nlapiSelectValue(rawfeeds[i], "link"),
nlapiSelectValue(rawfeeds[i], "description"));
}
return feeds;
}
function rssfeed(title, url, description)
{
this.title = title;
this.url = url;
this.description = description;
}
SuiteScript Developer and Reference Guide
294
Portlet Scripts
Portlet Scripts Samples
SuiteScript Developer and Reference Guide
295
Chapter 25 Mass Update Scripts
The following topics are covered in this section:
•
What Are Mass Update Scripts?
•
Mass Update Script Execution
•
Running a Mass Update Script in NetSuite
•
Mass Update Scripts Samples
What Are Mass Update Scripts?
Mass update scripts allow you to programmatically perform custom mass updates to update
fields that are not available through general mass updates. You can also use mass update scripts
to run complex calculations, as defined in your script, across many records.
Note: If you are not familiar with mass update functionality in NetSuite, see Making Mass
Changes or Updates in the NetSuite Help Center.
When a custom mass update is performed, the record type being updated is passed to a
system-defined rec_type parameter in the mass update script. Additionally, the internal ID of
each record in the custom mass update is passed to a system-defined rec_id parameter.
Whether you are using a custom mass update to update fields that are (or are not) available
through direct list editing, or you are updating fields based on the value of a SuiteScript script
parameter, the executing function in your script will include the rec_type and rec_id
parameters. For example:
function updateMemo(rec_type, rec_id)
{
nlapiSubmitField(rec_type, rec_id, 'memo', 'Premiere Customer', true);
}
Note: See Mass Update Scripts Samples for more details on working with mass update
scripts.
Like all other script types, you must create a Script record and a Script Deployment record for
mass update scripts. Once you define the deployment for a mass update script and specify
which record types the script will run against, the record type(s) will appear under the Custom
Updates dropdown, accessed by going to Lists > Mass Update > Mass Updates > Custom
Updates (see figure).
SuiteScript Developer and Reference Guide
Mass Update Scripts
What Are Mass Update Scripts?
297
Mass Update Script Metering and Governance
The SuiteScript governance limit is 1000 units per record/invocation of a mass update script.
Also note that if multiple rows are returned for the same transaction, the custom mass update
will still run only once per transaction.
Creating Script Parameters for Mass Update Scripts
The mass update script type allows you to create script parameters on the Script record page.
Script parameters will then appear as fields in the header portion of the custom Mass Update
page of the specified record type (see figure). Users executing custom mass updates can set the
value(s) of one or more script parameters on the Mass Update page before running the update.
SuiteScript Developer and Reference Guide
Mass Update Scripts
Mass Update Script Execution
298
Note that your SuiteScript code must use the nlobjContext.getSetting(type, name) method to
get the user-defined value of the script parameter. See Mass Update Scripts Samples for more
details on working with script parameters within action scripts.
When you first create your script parameter you can set a parameter value as a user or
company preference. The parameter will default to this value, but users may edit it as they run
the mass update.
When you preview a custom mass update, the selected parameters will be shown for reference
in the footer of the search results page.
Note: If you are not familiar with script parameters in SuiteScript, see Creating Script
Parameters Overview in the NetSuite Help Center.
Related Topics
•
•
•
Mass Update Script Execution
Running a Mass Update Script in NetSuite
Mass Update Scripts Samples
Mass Update Script Execution
Mass Update scripts execute on the server. They are not considered to be client scripts that run
in the browser.
Mass Update scripts are executed when users click the Perform Update button on the Mass
Update Preview Results page.
Important: Mass update scripts can only be invoked from the Mass Update page. They
cannot be invoked from another script type. For example, you cannot invoke
a mass update script by passing the script’s scriptId and deployId to the
nlapiScheduleScript(scriptId, deployId, params) function.
You have a choice of running mass update scripts as admin or as the logged-in user. As a script
owner, you must have the Mass Update permission to test and work with mass update scripts.
Users must have the Client SuiteScript and Server SuiteScript features enabled in their accounts
for the scripts to run. Also be aware that users who perform the custom mass update need the
appropriate permission (Edit or Full) for the record types they are updating.
If a mass update script encounters an error, the script execution will abort. Only the updates
that are completed prior to the error will be committed to the database.
Also note that the execution context for a mass update script is custommassupdate. This is
important if you are trying to determine the execution context of a script using
nlobjContext.getExecutionContext().
Finally, be aware that updates made to records during a custom mass update can trigger user
event scripts if there are user event scripts associated with the records being updated.
SuiteScript Developer and Reference Guide
Mass Update Scripts
Running a Mass Update Script in NetSuite
299
Related Topics
•
•
•
What Are Mass Update Scripts?
Running a Mass Update Script in NetSuite
Mass Update Scripts Samples
Running a Mass Update Script in NetSuite
To run a mass update script in NetSuite, you must:
1.
Create a JavaScript file for your action script.
2.
Load the file into NetSuite.
3.
Create a Script record.
4.
Define all runtime options on the Script Deployment page.
5.
Once you define the deployment for a mass update script and specify which record
types the script will run against, the record type(s) will appear under the Custom
Updates dropdown, accessed by going to Lists > Mass Update > Mass Updates >
Custom Updates.
If you are new to SuiteScript and need information on steps 1–4, see Running Scripts in
NetSuite Overview.
Important: When running mass update scripts in NetSuite, be aware of the following:
•
Mass update script deployments and mass updates can both be assigned an audience. It
is the script owner’s responsibility to ensure the two audiences are in sync. If the two
audiences do not match, the mass update script will not run when users click the
Perform Update button on the Mass Update page.
•
When users run custom mass updates, they must have the appropriate permission
(Edit/Full) for the record type(s) they are updating.
•
Users must also have SuiteScript enabled in their accounts. (Administrators can go to
Setup > Company > Enabled Features > SuiteFlex tab > and click the Server SuiteScript
check box and the Client SuiteScript check box.)
Related Topics
•
•
•
What Are Mass Update Scripts?
Mass Update Script Execution
Mass Update Scripts Samples
SuiteScript Developer and Reference Guide
Mass Update Scripts
Mass Update Scripts Samples
300
Mass Update Scripts Samples
The following mass update script samples are provided in this section:
•
Updating a field that is available through direct list edit
•
Updating a field that is not available through direct list edit
•
Updating a field based on a script parameter value
Updating a field that is available through direct list edit
The following sample mass update script shows that the Memo field on every record of a
certain type will be updated in a custom mass update. The record type that this script will run
against (Sales Order, for example) is defined on the action Script Deployment page. When the
custom mass update is executed by a user, the individual record IDs for each record of that type
is passed to the mass update script’s rec_id parameter.
Note that in the UI, the Memo field can be direct list editing. In SuiteScript, fields that are
direct list editable are updated using the nlapiSubmitField(type, id, fields, values, doSourcing)
function.
function updateMemo(rec_type, rec_id)
{
nlapiSubmitField(rec_type, rec_id, 'memo', 'Premiere Customer', true);
}
In the sample above, when the user clicks the Perform Update button on the Mass Update
Preview Results page, the Memo field on all specified sales orders will be updated to the text
value Premiere Customer.
Important: Be aware that if the Memo field were not direct list editable, you would have
to load and submit each record in the custom mass update. The
nlapiSubmitField function is used only on fields that can be direct list edited
through the UI. For example mass update scripts that update fields that are
not available through direct list edit, see Updating a field that is not available
through direct list edit.
Related Topics
•
•
•
What Are Mass Update Scripts?
Mass Update Script Execution
Mass Update Scripts Samples
SuiteScript Developer and Reference Guide
Mass Update Scripts
Mass Update Scripts Samples
301
Updating a field that is not available through direct list edit
The second example updates the Probability field on the Opportunity record type. The record
type is specified on the Script Deployment page for the action script.
Once all custom mass update search criteria are defined on the Mass Update page for the
Opportunity record type, this script will run on all Opportunity records that match the criteria.
The Probability field will then be updated to the new value.
function updProbability(rec_type, rec_id)
{
var recOpportunity = nlapiLoadRecord(rec_type, rec_id);
recOpportunity.setFieldValue('probability', 61);
nlapiSubmitRecord(recOpportunity);
}
Note that in this sample, you are required to load and submit the entire record in order to
change the value of the Probability field. You must do this when the field you want to change in
the custom mass update cannot be direct list edited. In other words, you cannot simply update
the field using nlapiSubmitField(type, id, fields, values, doSourcing) without first loading the
entire record object.
Related Topics
•
•
•
What Are Mass Update Scripts?
Mass Update Script Execution
Mass Update Scripts Samples
Updating a field based on a script parameter value
This sample mass update script updates the Department field on the Sales Order and Estimate
record types. The update is based on the value of a script parameter called New Department
(custscript_dept_update). Note that because the Department field is not accessible through
direct list editing, the only way to change the value of the Department field is to load and
submit each record that the custom mass update is running against.
Note: The screenshots in this section depict the NetSuite user interface prior to Version
2010 Release 2.
To perform a custom mass update that references a script parameter:
1.
Create an action script (see below for an example). The script below will update the
Department field on the record types specified in the action script’s deployment. The
update of the Department field will be based on the user-defined value specified in
Step 6.
Notice that the script’s executing function takes the rec_type and rec_id parameters.
When the custom mass update is performed, the record type defined on the
SuiteScript Developer and Reference Guide
Mass Update Scripts
Mass Update Scripts Samples
302
deployment and the internal ID of each record will get passed to the executing
function.
function updateDepartment(rec_type, rec_id)
{
var transaction = nlapiLoadRecord(rec_type, rec_id);
transaction.setFieldValue('department', nlapiGetContext().getSetting('SCRIPT',
'custscript_dept_update'));
nlapiSubmitRecord(transaction, false, true);
}
2.
Create a mass update Script record and define the new script parameter (see figure).
3.
Create a script deployment (see figure below). In this example, the Update Department
script will be deployed to Sales Order records.
4.
After deploying the mass update script, go to Lists > Mass Update > Mass Updates. All
custom mass updates referencing a mass update script will appear under the Custom
Updates dropdown. The following figure shows that the Update Department script has
been deployed to the Estimate and Sales Order record types (see figure).
SuiteScript Developer and Reference Guide
Mass Update Scripts
Mass Update Scripts Samples
303
5.
Click the custom mass update you want to execute. In this example, the Update
Department link under the Sales Order deployment is selected.
6.
On the Mass Update page for the record type, specify the value of the script parameter.
In this example, the value of the New Department script parameter is set to Retail (see
figure).
7.
Next, as with any mass update, use tabs on the Mass Update page to:
a.
Define which records the custom mass update will apply to (Criteria tab).
b.
Define which records you want to see when you preview the custom mass update
(Results tab).
c.
Define the Audience that the custom mass update will apply to (Audience tab).
Important: Be sure that the audience you define on the Mass Update page
matches the audience defined on the Script Deployment page.
SuiteScript Developer and Reference Guide
Mass Update Scripts
Mass Update Scripts Samples
304
Set the frequency with which you want the custom mass update to run (Schedule
tab).
d.
8.
Click Preview to verify which records the custom mass update will apply to.
9.
Click Perform Update to run the custom mass update.
Related Topics
•
•
•
What Are Mass Update Scripts?
Mass Update Script Execution
Mass Update Scripts Samples
SuiteScript Developer and Reference Guide
Chapter 26 Bundle Installation Scripts
The following topics are covered in this section:
•
What are Bundle Installation Scripts?
•
Setting Up a Bundle Installation Script
•
Sample Bundle Installation Script
What are Bundle Installation Scripts?
Bundle installation scripts are specialized server SuiteScripts that perform processing in target
accounts as part of bundle installation, update, or uninstall. This processing can include setup,
configuration, and data management tasks that would otherwise have to be completed by
account administrators. These scripts enhance solution providers’ ability to manage the bundle
deployment process.
Every bundle can include a bundle installation script that is automatically run when the bundle
is installed, upgraded, or uninstalled. Each bundle installation script can contain triggers to be
executed before install, after install, before update, after update, and after uninstall. All triggers
should be included in a single script file. This trigger code can ensure that bundles are
implemented correctly, and can prevent bundle installation, update, or uninstall if proper setup
has not occurred.
Bundle installation scripts have no audience because they are always executed using the
administrator role, in the context of bundle installation, update, or uninstall. Bundle
installation scripts do not have event types.
A bundle installation script can be associated with multiple bundles. Before a script can be
associated with a bundle, it must have a script record and at least one deployment. A bundle
creator associates a bundle installation script with a bundle by selecting one of its deployments
in the Bundle Builder. The script .js file and script record are automatically included in the
bundle when it is added to target accounts. Script file contents can be hidden from target
accounts based on an option set for the .js file in the file cabinet record.
Bundle Installation Script Functions
Triggered Functions
A bundle installation script’s functions are executed automatically during bundle installation,
update, or uninstall, based on one or more of the following triggers:
•
Before Install - Executed before a bundle is installed for the first time in a target
account.
•
After Install - Executed after a bundle is installed for the first time in a target account.
SuiteScript Developer and Reference Guide
Bundle Installation Scripts
What are Bundle Installation Scripts?
•
Before Update - Executed before a bundle in a target account is updated.
•
After Update - Executed after a bundle in a target account is updated.
•
Before Uninstall - Executed before a bundle is uninstalled from a target account.
306
A bundle installation script file should include a function for at least one of these triggers. If
you are using more than one of these, they should all be in the same script file.
The following are example uses for bundle installation script triggered functions:
•
Before Install: Check the existing configuration and setup in the target account prior
to bundle installation, and halt the installation with an error message if the target
account does not meet minimum requirements to run the solution.
•
After Install: Automate the setup and configuration of the bundled application after it
has been installed in the target account, eliminating manual tasks.
•
After Install or After Update: Connect to an external system to fetch some data and
complete the setup of the bundled application.
•
Before Update: Manage required data changes in the target account prior to executing
an upgrade.
•
Before Uninstall: Reset configuration settings or remove data associated with the
bundle being uninstalled.
Function Parameters
Two specialized parameters are available to functions in bundle installation scripts, to return
the version of bundles, as specified on the Bundle Basics page of the Bundle Builder.
•
The toversion parameter returns the version of the bundle that will be installed in the
target account. This parameter is available to Before Install, After Install, Before
Update, and After Update functions.
•
The fromversion parameter returns the version of the bundle that is currently
installed in the target account. This parameter is available to Before Update and After
Update functions.
Calls to Functions in Other Script Files
A bundle installation script file can include calls to functions in other script files, as long as
these files are added as library script files on the script record. Any .js files for library script
files are automatically included in the bundle when it is added to target accounts.
Bundle installation scripts can call scheduled scripts, but only in the After Install and After
Update functions. Calls to scheduled scripts are not supported in the Before Install, Before
Update, and Before Uninstall functions.
Bundle Installation Script Governance
Bundle installation scripts are governed by a maximum of 10,000 units per execution.
SuiteScript Developer and Reference Guide
Bundle Installation Scripts
Setting Up a Bundle Installation Script
307
Defining Deployments for Bundle Installation Scripts
You can create multiple deployments for each bundle installation script, with different
parameters for each, but only one deployment can be associated with each bundle. When you
associate a bundle installation script with a bundle, you select a specific script deployment.
Bundle installation scripts need to be executed with administrator privileges, so the Execute as
Admin box should be checked on the script deployment record.
Bundle installation scripts can only be run in target accounts if the Status is set to Released.
The Status should be set to Testing if you want to debug the script.
Bundle Installation Script Error Handling
Any bundle installation script failure terminates bundle installation, update, or uninstall.
Bundle installation scripts can include their own error handling, in addition to errors thrown
by SuiteBundler and the SuiteScript engine. An error thrown by a bundle installation script
returns an error code of “Installation Error”, followed by the text defined by the script author.
Related Topics
•
•
•
•
•
•
Script Types Overview
Setting Up a Bundle Installation Script
Using Bundle Installation Scripts
Sample Bundle Installation Script
Creating a Bundle
Using the Bundle Builder
Setting Up a Bundle Installation Script
Complete the following tasks to set up a bundle installation script:
•
Create the Bundle Installation Script File
•
Add the Bundle Installation Script File to the File Cabinet
•
Create the Bundle Installation Script Record
•
Define Bundle Installation Script Deployment
•
Associate the Script with a Bundle
A bundle installation script is a specialized server SuiteScript that is executed automatically in
target accounts when a bundle is installed, updated, or uninstalled. For details about how to
create a bundle, see Using the Bundle Builder and Creating a Bundle.
SuiteScript Developer and Reference Guide
Bundle Installation Scripts
Setting Up a Bundle Installation Script
308
Create the Bundle Installation Script File
You can create a bundle installation script file in the same manner that you create other types of
SuiteScript files, as described in Step 1: Create Your Script.
Bundle installation scripts support the entire SuiteScript API, including error handling and the
debugger. For details specific to bundle installation scripts, see Bundle Installation Script
Functions.
To create a bundle installation script file:
1.
Create a .js script file and add code.
This single script file should include Before Install, After Install, Before Update, After
Update, and Before Uninstall functions as necessary. It can include calls to functions
in other files, but you will need to list these files as library script files on the NetSuite
script record.
Add the Bundle Installation Script File to the File Cabinet
Once you have created a .js file with your bundle installation script code, you need to add this
file to the NetSuite file cabinet.
The following steps describe how to add the file manually. If you are using the SuiteCloud IDE
or the SuiteScript plug-in for Eclipse, this process is automated. For more information, see Step
2: Add Script to NetSuite File Cabinet.
To add a bundle installation script file to the file cabinet:
1.
Go to [TP=LIST_MEDIAITEMFOLDER=TP], and select the folder where you want
to add the file.
It is recommended that you add your file to the SuiteScripts folder, but it can be added
to any other folder of your choice.
2.
Click Add File, and browse to the .js file.
3.
In the file cabinet folder where you added the bundle installation script file, click the
Edit link next to file.
4.
Check the Available for SuiteBundles box.
5.
Optionally, you can check the Hide in SuiteBundle box.
Because this script file will be included in the bundle, by default its contents will be
accessible to users of target accounts where the bundle is installed. If you do not want
these users to see this file, you can set this option to hide it.
6.
Click Save.
Create the Bundle Installation Script Record
Once you have added a bundle installation script file to the file cabinet, you can create a
NetSuite script record.
SuiteScript Developer and Reference Guide
Bundle Installation Scripts
Setting Up a Bundle Installation Script
309
To create a bundle installation script record:
1.
Go to [TP=EDIT_SCRIPT=TP], and click Bundle Installation Script.
2.
Complete fields in the script record and save.
Although you do not need to set every field on the Script record, at a minimum you
must provide a Name for the Script record, load your SuiteScript file to the record, and
specify at least one of the following executing functions in your script: Before Install,
After Install, Before Update, After Update, or Before Uninstall.
You can specify more than one of these functions as desired. These functions should
all be in the main script file. If these functions call functions in other script files, you
need to list those files as library script files.
For more details about creating a script record, see Steps for Creating a Script Record.
SuiteScript Developer and Reference Guide
Bundle Installation Scripts
Setting Up a Bundle Installation Script
310
Define Bundle Installation Script Deployment
Once you have created a bundle installation script record, you need to define at least one
deployment. For details about defining script deployments, see Step 5: Define Script
Deployment and Steps for Defining a Script Deployment
You can define multiple deployments per bundle installation script. When you associate the
script with a bundle, you actually choose a specific deployment.
To define a bundle installation script deployment.
1.
Do one of the following:
• When you save your Script record, you can immediately create a Script
Deployment record by selecting Save and Deploy from the Script record Save
button.
• If you clicked Save, immediately afterwards you can click Deploy Script on the
script record.
• If you want to update a deployment that already exists, go to Setup >
Customization > Script Deployments > [deployment] > Edit.
2.
Complete fields in the script deployment record and click Save.
Be sure to check the Execute as Admin box.
If you want to debug the script, set the Status to Testing. To enable the script to be run
in a target account, you must set the Status to Released.
Associate the Script with a Bundle
[FD=CREATESUITEBUNDLES=FD]
Once a bundle installation script has been created and at least one deployment has been
defined for it, you can associate the script with bundles as desired.
Note: The SuiteBundler feature must be enabled in your account for you to have access to
the Bundle Builder where this task is completed.
SuiteScript Developer and Reference Guide
Bundle Installation Scripts
Setting Up a Bundle Installation Script
311
When you associate a script with a bundle, you select a specific script deployment.
To associate a script with a bundle:
1.
Start the Bundle Builder.
• If you are creating a new bundle, go to [TP=TRAN_BUNDLEBUILDER=TP].
• If you are editing an existing bundle, go to Setup > Customization > Create Bundle
> List, and select Edit from the Action menu for the desired bundle.
• For details about using the Bundle Builder, see Using the Bundle Builder.
2.
On the Bundle Basics page, select a bundle installation script deployment from the
Installation Script dropdown.
3.
Proceed through the remaining Bundle Builder steps, making definitions as necessary,
and click Save. Note the following:
• On the Select Objects page of the Bundle Builder, you do not have to explicitly add
the bundle installation script. This script record and the related .js file are
included automatically in the bundle, as are any other .js files that are listed as
library script files on the script record.
• For detailed instructions to complete all Bundle Builder steps, see Steps for
Creating a Bundle.
SuiteScript Developer and Reference Guide
Bundle Installation Scripts
Sample Bundle Installation Script
312
Once the bundle has been saved, this script record and related file(s) are listed as Bundle
Components on the Bundle Details page.
Related Topics
•
•
•
•
•
•
Script Types Overview
What are Bundle Installation Scripts?
Sample Bundle Installation Script
Creating a Bundle
Using the Bundle Builder
Using Bundle Installation Scripts
Sample Bundle Installation Script
This sample includes a bundle installation script file and a library script file. For details, see the
following:
•
Summary of Sample Script Files
•
Sample Bundle Installation Script File Code
•
Sample Library Script File Code
SuiteScript Developer and Reference Guide
Bundle Installation Scripts
Sample Bundle Installation Script
•
313
Sample Bundle Installation Script Record
Summary of Sample Script Files
The bundle installation script file includes the following:
•
Function that executes before bundle installation, ensuring that the Work Orders
feature is enabled in the target NetSuite account, and if the bundle that is being
installed is version 2.0, also ensuring that the Multiple Currencies feature is enabled
•
Function that executes after bundle installation, creating an account record in the
target account (note that accounts are not available to be included in bundles)
•
Function that executes before bundle update, ensuring that the Work Orders feature is
enabled in the target NetSuite account, and if the target account bundle is being
updated to version 2.0, also ensuring that the Multiple Currencies feature is enabled
•
Function that executes after bundle update, creating an account record in the target
account if the update changed the bundle version number
The library script file includes a function that is called by the bundle installation script
functions executed before installation and before update.
•
This function checks whether a specified feature is enabled in the target account and
returns an error if the feature is not enabled.
•
When an error is returned, bundle installation or update terminates.
Sample Bundle Installation Script File Code
The bundle installation script file SampBundInst.js contains the following code.
function beforeInstall(toversion)
{
// Always check that Workorders is enabled
checkFeatureEnabled('WORKORDERS');
// Check that Multi Currency is enabled if version 2.0 is being installed
if ( toversion.toString() == "2.0" )
checkFeatureEnabled('MULTICURRENCY');
}
function afterInstall(toversion)
{
// Create an account record
var randomnumber=Math.floor(Math.random()*10000);
var objRecord = nlapiCreateRecord('account');
objRecord.setFieldValue('accttype','Bank');
objRecord.setFieldValue('acctnumber',randomnumber);
objRecord.setFieldValue('acctname','Acct '+toversion);
nlapiSubmitRecord(objRecord, true);
}
function beforeUpdate(fromversion, toversion)
{
// Always check that Workorders is enabled
SuiteScript Developer and Reference Guide
Bundle Installation Scripts
Sample Bundle Installation Script
314
checkFeatureEnabled('WORKORDERS');
// Check that Multi Currency is enabled if version 2.0 is being installed
if ( toversion.toString() == "2.0" )
checkFeatureEnabled('MULTICURRENCY');
}
function afterUpdate(fromversion, toversion)
{
// Do not create an account if updating with the same version as the one installed
if (fromversion.toString() != toversion.toString())
{
// Create an account record
var randomnumber=Math.floor(Math.random()*10000);
var objRecord = nlapiCreateRecord('account');
objRecord.setFieldValue('accttype','Bank');
objRecord.setFieldValue('acctnumber',randomnumber);
objRecord.setFieldValue('acctname','Acct '+toversion);
nlapiSubmitRecord(objRecord, true);
}
}
Sample Library Script File Code
The library script file CheckFeat.js contains the following code.
function checkFeatureEnabled(featureId)
{
nlapiLogExecution('DEBUG','Checking Feature',featureId);
var objContext = nlapiGetContext();
var feature = objContext.getFeature(featureId);
if ( feature )
{
nlapiLogExecution('DEBUG','Feature',featureId+' enabled');
}
else
{
throw new nlobjError('INSTALLATION_ERROR','Feature '+featureId+' must be enabled. Please
enable the feature and re-try.');
}
}
Sample Bundle Installation Script Record
Once script .js files are created, they must be uploaded to the NetSuite file cabinet. For
information about this process, see Add the Bundle Installation Script File to the File Cabinet.
SuiteScript Developer and Reference Guide
Bundle Installation Scripts
Sample Bundle Installation Script
315
Then a bundle installation script record can be created. The following screenshot shows this
record. For steps to create this type of record, see Create the Bundle Installation Script Record.
Related Topics
•
•
•
•
•
•
Script Types Overview
What are Bundle Installation Scripts?
Setting Up a Bundle Installation Script
Creating a Bundle
Using the Bundle Builder
Using Bundle Installation Scripts
SuiteScript Developer and Reference Guide
Part 5 Setting Runtime
Options
Chapter 27 Setting Runtime Options
Overview
If you have not already created a Script Deployment record for your SuiteScript file, please see
Step 5: Define Script Deployment. This is the last step that is required for you to run your script
in NetSuite.
If you have created a deployment for your script and would now like to set additional
deployment options, see the following topics. These topics do not need to be read in order.
•
Setting Script Execution Event Type from the UI
•
Setting Script Execution Log Levels
•
Executing Scripts as Admin
•
Setting Available Without Login
•
Setting Script Deployment Status
•
Defining Script Audience
•
Creating Script Parameters Overview
Also see these topics for information related to script deployments, but not necessarily specific
to any deployment/runtime options.
•
Creating a Custom Script Deployment ID
•
Viewing Script Deployments
•
Using the Script Execution Log
SuiteScript Developer and Reference Guide
Chapter 28 Setting Script Execution Event
Type from the UI
In the Event Type field on the Script Deployment page, you can specify the event type that you
want to trigger the execution of the script (see figure). If Event Type is left blank, the script will
execute only on the events specified in the actual .js script file.
Note: The Event Type field appears on Suitelet, user event, and record-level client Script
Deployment pages only.
The Event Type field is useful if you want to easily specify a script execution context right at the
time of script deployment – without having to modify your .js file. Once you specify an event
type and click Save, the deployed script will execute only on that event, regardless of the event
types specified in the script file.
Be aware that event types specified in the UI take precedence over the types specified in the
script file. For example, if the create event type is specified in the script, selecting edit from the
Event Type field will restrict the script from running on any event other than edit.
The following snippet is from a user event script. Notice that the event type specified in the
code is create. If the edit event type is specified in the UI, this script will execute only when the
specified record is edited, not created:
function followUpCallAfterSubmit(type)
{
// execute the logic in this script if a new customer is created
if (type == 'create')
{
// obtain a handle to the newly created customer record
SuiteScript Developer and Reference Guide
Setting Script Execution Event Type from the UI
var custRec = nlapiGetNewRecord();
// remainder of script......
}
}
Related Topics
•
•
•
•
Steps for Defining a Script Deployment
Setting the User Event type Argument
User Event Script Execution Types
User Event Script Samples
SuiteScript Developer and Reference Guide
319
Chapter 29 Setting Script Execution Log
Levels
In the Log Level field on the Script Deployment page, specify which log entries you want to
appear on the Execution Log tab (see figure).
Note: See Using the Script Execution Log for details on how to further customize your
view of all log entries.
The Log Level field is essentially used as a simple filtering mechanism. Each log entry written
with nlapiLogExecution(type, title, details) specifies a log level in the type argument. When
logging details are displayed on the Execution Log tab of the Script Deployment record, you
can specify that all messages will display (by selecting Debug from the Log Level field) or a
specific type of message.
Important: Be aware that NetSuite governs the amount of logging that can be done by a
company in any given 60 minute time period. For complete details, see
Governance on Script Logging.
Use the Log Level field to filter which messages will appear on the Execution Log tab of the
Script Deployment page. Set filtering by selecting any of the following log levels from the Log
Level Field:
•
Debug: For scripts in testing mode. A log level set to Debug shows all Audit, Error, and
Emergency information on the Execution Log tab.
•
Audit: For scripts going into production. A log level set to Audit provides a record of
events that have occurred during the processing of the script (for example, “A request
was made to an external site.”).
•
Error: For scripts going into production. A log level set to Error shows only
unexpected script errors.
SuiteScript Developer and Reference Guide
Setting Script Execution Log Levels
•
321
Emergency: For scripts going into production. A log level set to Emergency shows
only the most critical errors in the script log.
Note: The log level you specify in the UI is independent of any error handling within your
script.
SuiteScript Developer and Reference Guide
Chapter 30 Executing Scripts as Admin
In the Execute as Admin check box on the Script Deployment page, select the check box if you
want the script to execute using administrative privileges, regardless of the permissions of the
currently logged-in user.
Note: The Execute as Admin check box appears on the Script Deployment page for all
script types except the global client script type.
For information about role restrictions in client SuiteScript, see Role Restrictions in
Client SuiteScript.
Also, be aware that only users with the administrator role have access to the
Execute as Admin checkbox. This checkbox is disabled for all others users who may
be working with SuiteScript. Even if you have been granted “Full” access to
SuiteScript (on the permissions tab of your NetSuite account), unless your role is
also an administrator, you will be unable to change the setting of the Execute As
Admin checkbox. This is also true for the Execute As Admin checkbox that appears
on the summary page in SuiteFlow.
There are scripts which may require that they run with administrative privilege. For example, if
you have a script that creates follow-up tasks once a sales order has been saved, and the script
needs to read data from employee records, the script will not complete execution if a user’s role
does not have permission to access employee records. In this case, it may be appropriate to have
the script Execute as Admin.
All bundle installation scripts need to Execute as Admin, so this option should always be
enabled for this type of script deployment.
However, use of Execute as Admin should be considered carefully, as this option allows scripts
to execute with privileges that the logged in user does not have. This may be appropriate for
certain scripts, but there are other cases where the script performs actions that are only
appropriate for certain roles.
SuiteScript Developer and Reference Guide
Executing Scripts as Admin
323
Note: Often when scripts execute without logins or in the Web store, they tend to be
implemented as Execute as Admin whenever any meaningful interaction with the
system is required.
SuiteScript Developer and Reference Guide
Chapter 31 Setting Available Without
Login
In the Available Without Login check box on the Script Deployment page, select the check
box to allow users without an active NetSuite session to have access to the Suitelet.
Note: The Available Without Login check box appears on the Script Deployment page for
Suitelets only.
When you select Available Without Login and then save the Script Deployment record, an
External URL appears on the Script Deployment page (see figure above). Use this URL for
Suitelets you want to make available to users who do not have an active NetSuite session.
The following are a few uses cases that address when you might want to make a Suitelet
externally available:
•
hosting one-off online forms (capturing test drive sign-up requests or partner
conference registrations, for example)
•
inbound partner communication (such as - listening for payment notification
responses from PayPal or Google checkout, or for generating the unsubscribe from
email campaigns page, which requires access to account information but should not
require a login or hosted website)
•
for Facebook/Google/Yahoo mashups in which the Suitelet lives in those web sites but
needs to communicate to NetSuite via POST requests
Note: Because there are no login requirements for Suitelets that are available without
login, be aware that the data contained within the Suitelet will be less secure.
Errors Related to the Available Without Login URL
Based on the use case for your Suitelet, you will use either the internal URL or the external
URL as the launching point for the Suitelet.
SuiteScript Developer and Reference Guide
Setting Available Without Login
325
Some of the factors determining whether the Suitelet will deploy sucessfully are the
dependencies between the type of URL you are referencing (internal or external), the Suitelet
deployment status (Testing or Released), and whether the Select All check box has been
selected on the Audience tab of the Script Deployment page. The following table summarizes
these dependencies.
Suitelet URL Type
Deployment Status
Select All check box
Result
internal
Testing
not checked
Suitelet deploys successfully
internal
Testing
checked
Suitelet deploys successfully
internal
Released
not checked
Error message: You do not have previleges to
view this page.
internal
Released
checked
Suitelet deploys successfully
external
Testing
not checked
Error message: You are not allowed to
navigate directly to this page.
external
Testing
checked
Error message: You are not allowed to
navigate directly to this page.
external
Released
checked
Suitelet deploys successfully
external
Released
not checked
Error message: You do not have previleges to
view this page.
SuiteScript Developer and Reference Guide
Chapter 32 Setting Script Deployment
Status
In the Status field on the Script Deployment page, set the deployment status of the script to
either Testing or Released.
Note: The Testing and Released statuses do not apply to scheduled scripts. To learn about
scheduled script deployment statuses, see Scheduled Script Deployment Statuses
or Deployment Status and Script Execution Summary.
Status Set to Testing
When a script’s deployment status is set to Testing, the script will execute for the script owner
only. Even if you have defined an audience on the Audience tab and saved the Script
Deployment record, the script will still only run for the script owner so long as it is in testing
mode.
Note that script owners can use the Audience tab, along with the Testing status, to test scripts
for various audience types. For information, see Using the Audience Tab to Test Scripts.
Also note that when using the SuiteScript Debugger to test scripts, the script’s deployment
status must be set to Testing. You cannot debug a Deployed script if the status has been set to
Released. (See Deployed Debugging for more information on using the SuiteScript Debugger
to test existing scripts.)
SuiteScript Developer and Reference Guide
Setting Script Deployment Status
327
If you are working with Suitelet Script Deployment records, also see Errors Related to the
Available Without Login URL. This section discusses the relevance of the Testing status as it
pertains to internally and externally available Suitelets.
Note: A bundle installation script cannot execute in target accounts if its deployment
status is set to Testing.
Status Set to Released
A script deployment status set to Released means that the script will run in the accounts of all
specified audience members. (See Defining Script Audience for information on defining script
audiences.) When the deployment status is set to Released, the script is considered to be
“production ready.”
Be aware that if you do not specify any values on the Audience tab, the script will execute for no
one other than the script author/owner, even if the script deployment status is set to Released.
Note: Bundle installation scripts do not have an Audience. If the deployment status is set
to Released for this type of script, it executes automatically in target accounts when
the associated bundle is installed or updated.
If you are working with Suitelet Script Deployment records, also see Errors Related to the
Available Without Login URL. This section discusses the relevance of the Released status as it
pertains to internally and externally available Suitelets.
SuiteScript Developer and Reference Guide
Chapter 33 Defining Script Audience
On the Audience tab on the Script Deployment page, define the audience access levels for the
script. When the script is deployed, it will run in the accounts of only the specified audiences.
Note: The Audience tab appears on the Script Deployment page for these script types:
Suitelet, portlet, user event, global client, action. You cannot specify an audience
for scheduled scripts or bundle installation scripts.
If you do not specify any values on the Audience tab, the script will execute for no one other
than the script author/owner, even if the script deployment status is set to Released. (For
information on the differences between the Released and Testing deployment statuses, see
Setting Script Deployment Status.)
If you choose both role and department options, a user must belong to one of the selected roles
AND one of the selected departments in order to access the search. If you choose options for
any other combinations of types, a user need only belong to a selected option of one type OR of
another.
If you want the script to run in the accounts of all NetSuite users, select the Select All check
box next to Roles. If you want the script to run in the accounts of only specific users, select the
appropriate roles, departments, groups, employees, or partners.
Be sure to save the Script Deployment record once all audience members are defined.
Important Things to Note:
SuiteScript Developer and Reference Guide
Defining Script Audience
329
•
If you are working with Suitelet Script Deployment records, also see Errors Related to
the Available Without Login URL. This section discusses the relevance of the Select
All check box as it pertains to internally and externally available Suitelets.
•
Mass update script script deployments and mass updates can both be assigned an
audience. It is the users responsibility to make sure the two audiences are in sync. For
information about working with the mass update script type, see Mass Update Scripts.
Using the Audience Tab to Test Scripts
If the Status field on the Script Deployment record is set to Testing, you can test scripts
assigned to specific audiences as long as you are a member of that audience type. (For
information on the Testing deployment status, see Setting Script Deployment Status.)
For example, if you have written a script that you want to run for everyone in the Support
Management role, you can log into NetSuite and then switch to the Support Management role
to test the script. As long as the deployment status for this script is set to Testing, the script will
run for no one other than you (as the script owner). Once you determine that the script runs as
expected for the Support Management role, you can change the script’s deployment status to
Released. Once the deployment is set to Released, it will run in the account for all those
assigned to the Support Management role.
This is a good approach for script owners to verify that their script will run in the accounts for
specified roles, departments, groups, employees, or partners.
Using the Audience Tab in OneWorld Accounts
Script authors/owners who are developing scripts for NetSuite OneWorld accounts can specify
script audience based on subsidiary. In OneWorld accounts, the Audience tab includes a
Subsidiaries multiselect field. After choosing subsidiaries, be sure to click Save on the Script
Deployment page.
Script owners working in a OneWorld account that has multiple subsidiaries can select the
subsidiaries they want their script to run in, and then log into an account of one of the specified
subsidiaries. As long as the script deployment status is set to Testing, the script will not run for
any of the subsidiary employees other than the script owner. This is a good way for script
owners to verify that the script will run in accounts for specified subsidiaries.
SuiteScript Developer and Reference Guide
Part 6 Creating Script Parameters
(Custom Fields)
Chapter 34 Creating Script Parameters
Overview
In the context of SuiteScript, script parameters are essentially just custom fields. Script
parameters are not considered to be parameters that are passed between JavaScript functions.
A script parameter can have any of the characteristics of a custom field created through pointand-click customization. They are configurable by administrators and end users and are
accessible programmatically through SuiteScript.
Script parameters are defined on the Parameters tab of the Script record page.
The following topics are covered in this section. They do not need to be read in order, although
it is recommended if you are not familiar with script parameters.
•
Why Create Script Parameters?
•
Creating Script Parameters
•
Referencing Script Parameters
•
Setting Script Parameter Preferences
Note: If you do not have experience with NetSuite custom fields, it is recommended that
you review Creating a Custom Field in the NetSuite Help Center.
SuiteScript Developer and Reference Guide
Chapter 35 Why Create Script Parameters?
You should create script parameters if you want one or more parts of your program to be
configurable, either through script deployment or by the end user. Script paramters should be
created whenever you need to parameterize a script that was deployed multiple times. This
makes it easy to customize the behavior of the program for each deployment.
Note: You can also configure scheduled scripts by specifying the configuration
parameters as arguments to nlapiScheduleScript(scriptId, deployId, params).
Deployment-specific parameters allows you to easily configure program behavior without
having to write code. This is particularly useful when admins deploy scripts that were installed
as part of a bundle. This allows them to control/modify the program without having to know
anything about the code. In other words, this is like the properties/config file that most
applications have which allow you to modify the runtime behavior.
Having script parameters also allows you to modify program behavior for troubleshooting
purposes without having to change code, which is often expensive and infeasible (for example,
when the script writer is unavailable). Finally, script parameters they give you the flexibility of
being able to handle a wide range of inputs depending on the context (for example, one script
deployed to 50 different records, each requiring a slightly different behavior). The alternative
would be to hard-code and deploy 50 different scripts. The downside to the latter is additional
maintenance (the code is not configurable, potential code duplication, changes in business
reqirements require code changes).
Note: You do not need to create script parameters if your program is not meant to be
configurable, in other words, everything is hard-coded.
SuiteScript Developer and Reference Guide
Chapter 36 Creating Script Parameters
Use the following steps to create script parameters. If you are unsure how to create a Script
record, see Step 4: Create Script Record.
1.
On the Script record, click the Parameters tab.
Note: If you want to add a parameter to a Script record that already exists, go to Setup
> Customization > Scripts > [script], where [script] is the desired script record. Open
the Script record in Edit mode. Click the Parameters tab and then click the New
Parameter button that appears on the tab.
2.
In the Label field, type the name of the parameter (custom field) as it will appear in the
UI once the script is deployed. The figure below shows that the field label on the UI
will appear as Check Box Required.
3.
In the ID field, create a custom ID for the script parameter. You can also leave the ID
field black and accept a system-generated ID. (It is best practice to create your own ID
for the script parameter. Doing so will help avoid naming conflicts should you later
decide to bundle your script.)
Note: Script parameter IDs must be in lowercase and contain no spaces. Also note that
parameter IDs cannot exceed 30 characters.
4.
From the Type drop-down list, select the parameter’s field type (for example,
Hyperlink, Date, Free-Form Text, or in this case, Check Box). For more information on
field types, see Custom Field Types in the NetSuite Help Center.
Note: If the parameter’s type is List/Record, specify the list or record using the List/
Record drop-down list (see figure below).
SuiteScript Developer and Reference Guide
Creating Script Parameters
334
Also note that if you define a saved search as a List/Record script parameter, only
saved searches that are public will appear in the List/Record parameter dropdown
field. For more information on working with searches using SuiteScript, see Searching
Overview in the NetSuite Help Center.
5.
From the Preference dropdown, set the script parameter preference to Company, User,
or Portlet (if creating a portlet script). Based on the preference, the parameter will
default to the values set on either the General Preferences page, the Set Preferences
page, or the portlet setup page. If no preference is specified, the script parameter is
considered to be a “deployment script parameter,” and its value is defined on the Script
Deployment record.
For more information setting parameter preferences, see Setting Script Parameter
Preferences.
6.
Once you have defined script parameter properties, click Add.
7.
If you have finished defining the parameter, save the Script record and set the script’s
deployment values on the Script Deployment page.
In this example, when the “Simple Form” Suitelet is deployed, the check box script
parameter appears on the form.
8.
To define additional properties for the script parameter, such as display size,
validation, or sourcing values, save the Script record and then re-open the Script
record.
9.
On the Script record page (see below), click the Parameters tab, and then click the link
to the script parameter you originally created.
SuiteScript Developer and Reference Guide
Creating Script Parameters
335
After clicking the parameter link, the Script Field page opens (see below). Use this page
to define additional values for the script parameter. For information on setting display,
validation, and sourcing values, see these sections in the NetSuite Help Center:
• Setting Display Options for Custom Fields
• Setting Validation and Defaulting Properties
• Setting Sourcing Criteria
• Setting Filtering Criteria
10.
Click Save on the Script Field page after defining all values.
SuiteScript Developer and Reference Guide
Chapter 37 Referencing Script Parameters
In your SuiteScript code you must use the nlobContext.getSetting(type, name) method to
reference script parameters. For example, to obtain the value of a script parameter called
custscript_checkboxtest2, you must use the following code:
//Add to the Suitelet a check box script parameter called Check Box Required
var field = form.addField('custscript_checkboxtest2', 'checkbox', 'Check Box Required');
//Get the parameter context and return a checked check box if value
//is set to T. Note that check box values are set to T or F, not true or false
if (nlapiGetContext().getSetting('SCRIPT', 'custscript_checkboxtest2') == 'T' {
field.setDefaultValue('T')
}
...remainder of Suitelet code
Be aware that you cannot write to a script parameter using SuiteScript. Although you can read
from these fields, you cannot write to them. The only time you can pass a value to a script
parameter outside of the UI is when you call nlapiScheduleScript(scriptId, deployId, params).
In the API documentation for this function, see Example 5 - Passing Script Parameters in a
Scheduled Script.
SuiteScript Developer and Reference Guide
Chapter 38 Setting Script Parameter
Preferences
As a script author, NetSuite gives you the ability to specify the preference type for each script
parameter (see figure). Available preference types are:
•
Company: If the parameter preference is set to Company (see figure 1), the script
parameter’s value is read from the value specified in Setup > Company > General
Preferences > Custom Preferences tab. See the Example later in this section.
•
User: If the preference is set to User (see figure 1), the parameter’s value is read from
the value set in Home > Set Preference > Custom Preferences tab.
Here, end users can override the default (company) script behavior and insert their
own default value. End users do not have to manipulate a script or its deployments to
change or customize the parameter.
•
Portlet: If the preference is set to Portlet, the parameter’s value is read from a user’s
personal portlet preferences.
•
<blank>: If you do not set a preference, the script parameter is considered a
“deployment” script parameter by default. In this case, you will define the value of the
script parameter on the Parameters tab of the Script Deployment record (see figure 2).
Note: See Creating Script Parameters for steps on creating a script parameter. Also see
Referencing Script Parameters for information on accessing script parameter
values.
Figure 1
SuiteScript Developer and Reference Guide
Setting Script Parameter Preferences
At the time these three script parameters were created, no preferences were set. In this case,
parameter values are defined on the Parameters tab of the Script Deployment record.
Figure 2
Note that users who install a bundled script that uses preferences can override the default
behavior of the script and customize the script to their specific business needs. Setting
preferences eliminates having to manipulate the script code or the script deployment. (For
information on bundling scripts, see SuiteBundler Overview in the NetSuite Help Center.)
Example
In this example, the parameter called Check Box Required (with the internal ID
custscript_checkboxtest2) is set to the Company preference.
By going to Setup > Company > General Preferences > Custom Preferences tab (see below),
administrators can set the default value of this parameter for the entire company. In this
example the value of the Check Box Required script parameter is set to T (the check box is
checked).
SuiteScript Developer and Reference Guide
338
Setting Script Parameter Preferences
339
When the Suitelet that contains this check box is deployed, the Check Box Required script
parameter will appear checked.
If the Check Box Required parameter had been set to F (the check box contained no check
mark), the check box would have appeared empty on the form when the Suitelet was deployed.
Script Parameter Preferences and Bundles
Bundled script parameters that have a user or company preference set are not updated in target
accounts when the bundle is updated. However, script parameters that do not have a
preference specified are considered part of the script deployment, and whether they are
updated in target accounts when the bundle is updated depends on the setting of the related
bundle object preference:
•
If the preference for the bundled script is set to Update Deployments, script
deployment parameters are updated in target accounts to match those in the source
account.
•
If the preference for the bundled script is set to Do Not Update Deployments, script
deployment parameters are not updated in target accounts.
If bundle authors expect target account users to want to change parameter values for a bundled
script, on the script record they should set the Preference for these parameters to be either
Company or User. Target account users can then change parameter values as needed, and these
values are not affected on bundle update, even if the related bundle object preference is set to
Update Deployments.
To prevent changes to target account script deployment parameters that do not have a
preference set, set the related bundle object preference to Do Not Update Deployments.
For more information about bundle object preferences, see Setting Bundle Object Preferences
SuiteScript Developer and Reference Guide
Setting Script Parameter Preferences
SuiteScript Developer and Reference Guide
340
Part 7 Searching with
SuiteScript
Chapter 39 Searching Overview
Similar to much of the searching functionality available through the NetSuite UI, SuiteScript
Search APIs allow you to retrieve real-time data from your account. You can search for a single
record by keywords, create saved searches, search for duplicate records, or return a set of
records that match filters you define.
The following sections provide details on searching with SuiteScript. If you are new to
SuiteScript searches, it is recommended that you read these topics in order.
•
Understanding SuiteScript Search Objects
•
Search Samples
•
Search APIs
•
Supported Search Operators, Summary Types, and Date Filters
SuiteScript Developer and Reference Guide
Chapter 40 Understanding SuiteScript
Search Objects
The basis of most SuiteScript searches use the following objects:
1.
nlobjSearchFilter - used to define filtering criteria for the search
2.
nlobjSearchColumn - used to define search return columns for the search
3.
nlobjSearchResult - used to get the values of specific search results
Once all filters and search columns are defined, the search is executed using the
nlapiSearchRecord(type, id, filters, columns) function.
Important: If you are performing a global search or a duplicate record search, you will
not use the objects listed above or the nlapiSearchRecord(...) function. For
details on these types of searches, see Searching for Duplicate Records and
Performing Global Searches.
Defining Search Filters
The following figure shows the UI equivalent of using the nlobjSearchFilter object to define
search filters. In the UI, users define search filters by clicking the Criteria tab on the search
record (in this case the Customer Search record).
In SuiteScript, the same filter value is specified through the nlobjSearchFilter object:
var filters = new Array();
filters[0] = new nlobjSearchFilter ('companyname', null, 'startswith', 'A' );
How do I know which search filters I can use in my code?
To figure out which search filters are available for a specific record type:
SuiteScript Developer and Reference Guide
Understanding SuiteScript Search Objects
344
1.
See the section SuiteScript Supported Records in the NetSuite Help Center.
2.
Click on the record you are running your script against.
3.
In the documentation for that record, see the Search Filters table. All available search
filters for that record type will be listed in the table.
Defining Search Columns
The following figure shows the UI equivalent of using the nlobjSearchColumn object to define
search return columns. In the UI, users define search columns by clicking the Results tab on
the search record (in this case the Customer Search record).
In SuiteScript, the same column values are specified using:
var columns = new Array();
columns[0] = new nlobjSearchColumn('entity');
columns[1] = new nlobjSearchColumn('phone');
columns[2] = new nlobjSearchColumn('companyname');
How do I know which search columns I can use in my code?
To figure out which search columns are available for a specific record type:
1.
See the section SuiteScript Supported Records in the NetSuite Help Center.
2.
Click on the record you are running your script against.
3.
In the documentation for that record, see the Search Columns table. All available
search columns for that record type will be listed in the table.
SuiteScript Developer and Reference Guide
Understanding SuiteScript Search Objects
345
Executing the Search
In the UI, users click the Submit button to execute a search. In SuiteScript, the equivalent of
clicking the Submit button is calling the nlapiSearchRecord(type, id, filters, columns) function:
// Define search filters
var filters = new Array();
filters[0] = new nlobjSearchFilter ('companyname', null, 'startswith', 'A');
// Define search columns
var columns = new Array();
columns[0] = new nlobjSearchColumn('entity');
columns[1] = new nlobjSearchColumn('phone');
columns[2] = new nlobjSearchColumn('companyname');
// Execute the Customer search. You must specify the internal ID of
// the record type you are searching against. Also, you will pass the values
// defined in the filters and columns arrays.
var searchResults = nlapiSearchRecord('customer', null, filters, columns);
Getting Search Return Values
If you want to get specific values returned by the search, you will use the nlobjSearchResult
object to specify the values.
// Define search filters
var filters = new Array();
filters[0] = new nlobjSearchFilter ('companyname', null, 'startswith', 'A');
// Define search columns
var columns = new Array();
columns[0] = new nlobjSearchColumn('entity');
columns[1] = new nlobjSearchColumn('phone');
columns[2] = new nlobjSearchColumn('companyname');
// Execute the search
var searchResults = nlapiSearchRecord('customer', null, filters, columns);
// Get the value of the Company Name column
var values = searchResults[0].getValue(columns[2]);
SuiteScript Developer and Reference Guide
Chapter 41 Search Samples
The following are samples of SuiteScript searches.
•
Creating Saved Searches
•
Executing Existing Saved Searches
•
Filtering a Search
•
Returning Specific Fields in a Search
•
Searching on Custom Records
•
Searching Custom Lists
•
Executing Joined Searches
•
Searching for an Item ID
•
Searching for Duplicate Records
•
Performing Global Searches
•
Searching CSV Saved Imports
•
Using Formulas, Special Functions, and Sorting in Search
•
Using Summary Filters in Search
For more general information that describes search objects, see Understanding SuiteScript
Search Objects.
Creating Saved Searches
The nlobjSearch object is the primary object used to encapsulate a NetSuite saved search. Note,
however, you are not required to save the search results returned in this object.
To create a saved search, you will first define all search criteria and then execute the search
using nlapiCreateSearch(type, filters, columns). The search will not be saved until you call the
nlobjSearch.saveSearch method.
By default, searches returned by nlapiCreateSearch(...) will be private, which follows the saved
search model in the UI. To make a saved search public, you must set the
nlobjSearch.setIsPublic(type) method to true.
Creating a Saved Search Using Search Filter List
// Define search filters
var filters = new Array();
filters[0] = new nlobjSearchFilter( 'trandate', null, 'onOrAfter', 'daysAgo90' );
SuiteScript Developer and Reference Guide
Search Samples
Executing Existing Saved Searches
347
filters[1] = new nlobjSearchFilter( 'projectedamount', null, 'between', 1000, 100000 );
filters[2] = new nlobjSearchFilter( 'salesrep', 'customer', 'anyOf ', \-5, null );
// Define return columns
var columns = new Array();
columns[0] = new nlobjSearchColumn( 'salesrep' );
columns[1] = new nlobjSearchColumn( 'expectedclosedate' );
columns[2] = new nlobjSearchColumn( 'entity' );
// Create the saved search
var search = nlapiCreateSearch( 'opportunity', filters, columns );
var searchId = search.saveSearch('My Opportunities in Last 90 Days', 'customsearch_kr');
Creating a Saved Search Using Search Filter Expression
//Define search filter expression
var filterExpression =[ [ 'trandate', 'onOrAfter', 'daysAgo90' ],
'or',
[ 'projectedamount', 'between', 1000, 100000 ],
'or',
'not', [ 'customer.salesrep', 'anyOf ', -5 ] ];
//Define return columns
var columns = new Array();
columns[0] = new nlobjSearchColumn( 'salesrep' );
columns[1] = new nlobjSearchColumn( 'expectedclosedate' );
columns[2] = new nlobjSearchColumn( 'entity' );
//Create the saved search
var search = nlapiCreateSearch( 'opportunity', filterExpression, columns );
var searchId = search.saveSearch('My Opportunities in Last 90 Days', 'customsearch_kr');
Executing Existing Saved Searches
NetSuite saved searches allow you to create reusable search definitions with many advanced
search filters/results display options. Although saved searches must be created in the UI, you
can pass the internal ID of the saved search to SuiteScript and re-execute the search on a
regular basis. This allows you to keep the searches up-to-date for all who might need to access
the results.
To re-execute an existing saved search, you will use nlapiSearchRecord(type, id, filters,
columns).
Note: For general information on NetSuite saved searches, see Using Saved Searches in
the NetSuite Help Center.
When using the nlapiSearchRecord(...) function to execute an existing saved search, note the
following:
•
Only saved searches on record types currently supported by SuiteScript can be
executed. For a list of records that support SuiteScript, see SuiteScript Supported
Records in the NetSuite Help Center.
SuiteScript Developer and Reference Guide
Search Samples
Executing Existing Saved Searches
•
348
Saved searches acted on by SuiteScript should be protected. If a saved search is edited
after script deployment is complete, the execution of the script could fail. You can add
security to a saved search by defining access permissions in the search definition.
Tip: You may want to include the script administrator in an email notification for any
time a saved search included in the script is updated. Email notifications can be
defined on the Alerts tab of the saved search definition.
•
On a Script record page, if you define a saved search as a List/Record script parameter,
only saved searches that are public will appear in the List/Record parameter dropdown
field. For information on script parameters, see Creating Script Parameters Overview
in the NetSuite Help Center.
•
In nlapiSearchRecord(type, id, filters, columns), the value of id can be the ID that
appears in the Internal ID column on the Saved Searches list page (see figure below).
Or it can be the value that appears in the ID column.
If you have created a custom scriptId for your saved search, this will appear in the ID
column (see figure). Note: To access the Saved Searches list page, go to Lists > Search >
Saved Searches.
In the following code, a Customer saved search is executed. The ID customsearch57 references
a specific saved search.
Note: The second parameter in nlapiSearchRecord(...) will be treated as a variable instead
of the custom Saved Search ID if it is not within quotes. Also note, if the Internal Id
of the saved search is used instead of the Saved Search ID, the Internal Id does not
need single quotes since it is evaluated as an integer.
function executeSavedSearch()
{
// specify the record type and the saved search ID
var searchresults = nlapiSearchRecord('customer', 'customsearch57', null, null);
for ( var i = 0; searchresults != null && i < searchresults.length; i++ )
{
var searchresult = searchresults[ i ];
}
}
SuiteScript Developer and Reference Guide
Search Samples
Filtering a Search
Filtering a Search
The following samples provide examples for how to set various kinds of filtering criteria in a
search. Also provided are samples that show how to filter the results.
Executing an Opportunity Search and Setting Search Filters
// Define search filters
var filters = new Array();
filters[0] = new nlobjSearchFilter( 'trandate', null, 'onOrAfter', 'daysAgo90' );
filters[1] = new nlobjSearchFilter( 'projectedamount', null, 'between', 1000, 100000 );
filters[2] = new nlobjSearchFilter( 'salesrep', 'customer', 'anyOf ', -5, null );
// Define search columns
var columns = new Array();
columns[0] = new nlobjSearchColumn( 'salesrep' );
columns[1] = new nlobjSearchColumn( 'expectedclosedate' );
columns[2] = new nlobjSearchColumn( 'entity' );
columns[3] = new nlobjSearchColumn( 'projectedamount' );
columns[4] = new nlobjSearchColumn( 'probability' );
columns[5] = new nlobjSearchColumn( 'email', 'customer' );
columns[6] = new nlobjSearchColumn( 'email', 'salesrep' );
// Execute the search. You must specify the internal ID of the record type.
var searchresults = nlapiSearchRecord( 'opportunity', null, filters, columns );
// Loop through all search results. When the results are returned, use methods
// on the nlobjSearchResult object to get values for specific fields.
for ( var i = 0; searchresults != null && i < searchresults.length; i++ )
{
var searchresult = searchresults[ i ];
var record = searchresult.getId( );
var rectype = searchresult.getRecordType( );
var salesrep = searchresult.getValue( 'salesrep' );
var salesrep_display = searchresult.getText( 'salesrep' );
var salesrep_email = searchresult.getValue( 'email', 'salesrep' );
var customer = searchresult.getValue( 'entity' );
var customer_email = searchresult.getValue( 'email', 'customer' );
var expectedclose = searchresult.getValue( 'expectedclosedate' );
var projectedamount = searchresult.getValue( 'projectedamount' );
var probablity = searchresult.getValue( 'probability' );
}
Executing an Opportunity Search and Setting Search Filter Expression
//Define search filter expression
var filterExpression =[ [ 'trandate', 'onOrAfter', 'daysAgo90' ],
'or',
[ 'projectedamount', 'between', 1000, 100000 ],
'or',
'not', ['customer.salesrep', 'anyOf ', -5 ] ] ;
//Define search columns
SuiteScript Developer and Reference Guide
349
Search Samples
Filtering a Search
350
var columns = new Array();
columns[0] = new nlobjSearchColumn('salesrep');
columns[1] = new nlobjSearchColumn('expectedclosedate');
columns[2] = new nlobjSearchColumn('entity');
columns[3] = new nlobjSearchColumn('projectedamount');
columns[4] = new nlobjSearchColumn('probability');
columns[5] = new nlobjSearchColumn('email', 'customer');
columns[6] = new nlobjSearchColumn('email', 'salesrep');
//Execute the search. You must specify the internal ID of the record type.
var searchresults = nlapiSearchRecord('opportunity', null, filterExpression, columns);
//Loop through all search results. When the results are returned, use methods
//on the nlobjSearchResult object to get values for specific fields.
for (var i = 0; searchresults != null && i < searchresults.length; i++)
{
var searchresult = searchresults[i];
var record = searchresult.getId();
var rectype = searchresult.getRecordType();
var salesrep = searchresult.getValue('salesrep');
var salesrep_display = searchresult.getText('salesrep');
var salesrep_email = searchresult.getValue('email', 'salesrep');
var customer = searchresult.getValue('entity');
var customer_email = searchresult.getValue('email', 'customer');
var expectedclose = searchresult.getValue('expectedclosedate');
var projectedamount = searchresult.getValue('projectedamount');
var probability = searchresult.getValue('probability');
}
Filtering Based on Check Box Fields
When filtering search results for check box fields, use the is operator with T or F as the filter
values. For example, in the following portlet script, all memorized Cash Sale transactions are
returned.
function testPortlet(portlet) {
portlet.setTitle('Memorized Cash Sales');
var filters = new Array();
filters[0] = new nlobjSearchFilter('name', null, 'equalTo', '87', null);
filters[1] = new nlobjSearchFilter('memorized', null, 'is', 'T', null);
var columns = new Array();
columns[0] = new nlobjSearchColumn('internalid');
columns[1] = new nlobjSearchColumn('memorized');
var searchresults = nlapiSearchRecord('cashsale', null, filters, columns);
for ( var i = 0; searchresults != null && i < searchresults.length; i++ )
{
var searchResult = searchresults[i];
portlet.addLine(i+": "+searchResult.getValue('internalid')+",
"+searchResult.getValue('memorized'),null,0);
SuiteScript Developer and Reference Guide
Search Samples
Filtering a Search
351
}
}
Executing a Customer Search and Filtering the Results
In the following sample, a search for all customer records (leads, prospects, customers) in the
system is executed with the maximum limit of 10 results set. Note that in this sample, if you
specify customer as the record type, customers, leads, and prospects are returned in the results.
function executeSearch()
{
var searchresults = nlapiSearchRecord( 'customer', null, null, null );
for ( var i = 0; i < Math.min( 10, searchresults.length ); i++)
{
var record = nlapiLoadRecord(searchresults[i].getRecordType(), searchresults[i].getId());
}
}
Filtering Based on None of Null Value
To search for a “none of null” value, meaning do not show results without a value for the
specified field, use the @NONE@ filter. For example,
searchFilters[0] = new nlobjSearchFilter('class', null, 'noneof ', '@NONE@');
In the following example, only customer records that match the entityid of test1 are returned.
function filterCustomers()
{
var filters = new Array();
filters[0] = new nlobjSearchFilter( 'entityid', null, 'contains', 'test1', null );
var searchresults = nlapiSearchRecord('customer', 11, filters, null);
var emailAddress = '';
for ( var i = 0; searchresults != null && i < searchresults.length; i++ )
{
var searchresult = searchresults[ i ];
}
}
Note: If it is unclear which values you can filter by for a given filter variable, try performing
a search that returns the value of a field as a result to see possible options.
SuiteScript Developer and Reference Guide
Search Samples
Returning Specific Fields in a Search
352
Returning Specific Fields in a Search
You can use the nlobjSearchResult.getValue method to return the values of specific record
fields. In the following example, the email fields for records returned from a saved customer
search are returned.
function findCustomerEmails()
{
var searchresults = nlapiSearchRecord('customer', customsearch8, null,null);
var emailAddress = '';
for ( var i = 0; searchresults != null && i < searchresults.length; i++ )
{
var searchresult = searchresults[ i ];
emailAddress += searchresult.getValue( 'email' );
}
}
For another example that shows how to return specific values in a search, see the sample for
Searching on Custom Records.
Note: In order to increase performance, if you only need to access a specific subset of
fields, you should limit the returned objects to include only that subset. This can be
accomplished using the nlobjSearchFilter and nlobjSearchColumn objects.
Searching on Custom Records
Searching on custom records is the same as searching on standard (built-in) records. The
following sample shows how to execute a search on a Warranty custom record type. (The
internal ID for this record type is customrecord_warranty).
This sample shows how to define search filters and search columns, and then execute the
search as you would for any other record type. This sample also shows how to use methods on
the nlobjSearchResult object to get the values for the search results.
function searchWarranties()
{
// define search filters
var filters = new Array();
filters[0] = new nlobjSearchFilter( 'created', null, 'onOrAfter', 'daysAgo15' );
// return opportunity sales rep, customer custom field, and customer ID
var columns = new Array();
columns[0] = new nlobjSearchColumn( 'name' );
columns[1] = new nlobjSearchColumn( 'owner' );
columns[2] = new nlobjSearchColumn( 'custrecord_customer' );
columns[3] = new nlobjSearchColumn( 'custrecord_resolutiontime' );
// execute the Warrenty search, passing all filters and return columns
var searchresults = nlapiSearchRecord( 'customrecord_warranty', null, filters, columns );
SuiteScript Developer and Reference Guide
Search Samples
Searching Custom Lists
353
// loop through the results
for ( var i = 0; searchresults != null && i < searchresults.length; i++ )
{
// get result values
var searchresult = searchresults[ i ];
var record = searchresult.getId( );
var rectype = searchresult.getRecordType( );
var name = searchresult.getValue( 'name' );
var resolution = searchresult.getValue( 'custrecord_resolutiontime' );
var customer = searchresult.getValue( 'custrecord_customer' );
var customer_name = searchresult.getText( 'custrecord_customer' );
}
}
This sample shows how you can do a search on custom records using a search filter expression.
function searchWarranties()
{
//Define search filter expression
var filterExpression = ['created', 'onOrAfter', 'daysAgo15'];
//Define search columns
var columns = new Array();
columns[0] = new nlobjSearchColumn('name');
columns[1] = new nlobjSearchColumn('owner');
columns[2] = new nlobjSearchColumn('custrecord_customer');
columns[3] = new nlobjSearchColumn('custrecord_resolutiontime');
//Execute the Warranty search, passing search filter expression and columns
var searchresults = nlapiSearchRecord('customrecord_warranty', null, filterExpression, columns);
//Loop through the results
for (var i = 0; searchresults != null && i < searchresults.length; i++)
{
//Get result values
var searchresult = searchresults[i];
var record = searchresult.getId();
var rectype = searchresult.getRecordType();
var name = searchresult.getValue('name');
var resolution = searchresult.getValue('custrecord_resolutiontime');
var customer = searchresult.getValue('custrecord_customer');
var customer_name = searchresult.getText('custrecord_customer');
}
}
Searching Custom Lists
The following sample shows how to search a custom list.
var col = new Array();
col[0] = new nlobjSearchColumn('name');
col[1] = new nlobjSearchColumn('internalId');
SuiteScript Developer and Reference Guide
Search Samples
Executing Joined Searches
354
var results = nlapiSearchRecord('customlist25', null, null, col);
for ( var i = 0; results != null && i < result.length; i++ )
{
var res = results[i];
var listValue = (res.getValue('name'));
var listID = (res.getValue('internalId'));
nlapiLogExecution('DEBUG', (listValue + ", " + listID));
}
Executing Joined Searches
This example shows how to set values for a joined search. In this case you are executing an Item
search that uses Customer and Currency (as specified on the Pricing record) as your filtering
criteria.
You will define the join to the Pricing record in the nlobjSearchFilter object. You will define
search return column values (also joins to the Pricing record) in the nlobjSearchColumn
object. You will execute the Item search using nlapiSearchRecord(type, id, filters, columns).
// Create a filters array and define search filters for an Item search
var filters = new Array();
// filter by a specific customer (121) on the Pricing record
filters[0] = new nlobjSearchFilter('customer', 'pricing', 'is', '121');
// filter by a currency type (USA) on the Pricing record
filters[1] = new nlobjSearchFilter('currency', 'pricing', 'is', '1');
// set search return columns for Pricing search
var columns = new Array();
// return data from pricelevel and unitprice fields on the Pricing record
columns[0] = new nlobjSearchColumn('pricelevel', 'pricing');
columns[1] = new nlobjSearchColumn('unitprice', 'pricing');
// specify name as a search return column. There is no join set in this field.
// This is the Name field as it appears on Item records.
columns[2] = new nlobjSearchColumns('name');
// execute the Item search, which uses data on the Pricing record as search filters
var searchresults = nlapiSearchRecord('item', null, null, columns);
The following figures show the UI equivalent of executing an Item search that uses filtering
criteria pulled from the Pricing record. Note that on the Criteria tab, all available search joins
for an Item search will appear at the bottom of the Filter drop-down list. Available join records
are marked with the ellipsis (...) after the record name.
Note: Not all joins that appear in the UI are supported in SuiteScript. To see which joins
are supported for a particular search, start by going to SuiteScript Supported
Records. Click the record type that you want to execute the search on. Based on the
SuiteScript Developer and Reference Guide
Search Samples
Executing Joined Searches
355
example described below, you will click Item Search record. Then look to see which
joins are supported for the record type.
The figures below show only how to set the filter values for a joined search. All of the same
concepts apply when specifying search return column values.
The first figure shows the Item Search record (Lists > Accounting > Items > Search).
When Pricing Fields... is selected, a popup appears with all search fields that are available on
the Pricing record (see figure below).
When you select the Customer field, another popup opens allowing you to select one or more
customers. In the code sample, customer 121 is specified. In the UI, this customer appears as
Abe Simpson (see below).
SuiteScript Developer and Reference Guide
Search Samples
Executing Joined Searches
This figure shows how Item search / pricing join filtering criteria appear in the UI.
In SuiteScript, this looks like:
var filters = new Array();
filters[0] = new nlobjSearchFilter('customer', 'pricing', 'is', '121');
filters[1] = new nlobjSearchFilter('currency', 'pricing', 'is', '1');
This example shows how you can execute joined searches using a search filter expression.
//Define search filter expression
var filterExpression = [ [ 'pricing.customer', 'is', 121 ],
'and',
[ 'pricing.currency', 'is', 1 ] ];
//Define search columns
var columns = new Array();
//Return data from pricelevel and unitprice fields on the Pricing record
columns[0] = new nlobjSearchColumn('pricelevel', 'pricing');
columns[1] = new nlobjSearchColumn('unitprice', 'pricing');
//Specify name as a search return column. There is no join set in this field.
//This is the Name field as it appears on Item records.
columns[2] = new nlobjSearchColumn('name');
SuiteScript Developer and Reference Guide
356
Search Samples
Executing Joined Searches
357
//Execute the Item search, which uses data on the Pricing record as search filter expression
var searchresults = nlapiSearchRecord('item', null , filterExpression, columns);
The following figures show the UI equivalent of executing the preceding example. These
figures showonly how to set the filter expression for a joined search. All of the same concepts
apply when specifying search return column values.
The first figure shows the Item Search record (Lists > Accounting > Items > Search).
When Pricing Fields… is selected, a popup appears with all search fields that are available on
the Pricing record. (See figure below.)
When you select the Customer field, another popup opens allowing you to select one or more
customers. In the code sample, customer 121 is specified. In the UI, this customer appears as
Abe Simpson. (See figure below.)
SuiteScript Developer and Reference Guide
Search Samples
Searching for an Item ID
358
The following figure shows how Item search / pricing join filtering criteria appear in the UI.
Searching for an Item ID
The following search sample returns an array of item search results matched by the "Item ID"
keyword. You can then iterate through each result and call nlobjSearchResult.getId() to get the
internal item ID.
var x = nlapiSearchRecord('item', null, new nlobjSearchFilter('itemid', null, 'haskeywords', itemidvalue));
Searching for Duplicate Records
In the course of doing business, it is common to have more than one record created for the
same contact, customer, vendor, or partner. In both the UI and in SuiteScript you can find all
duplicate records once your NetSuite administrator has enabled the Duplicate Detection &
Merge feature (Setup > Company > Enable Features, on the Company subtab, Data
Management section).
In SuiteScript, a search for duplicate records is executed using the nlapiSearchDetection(type,
fields, id) function. For the definition of this API, as well as a code sample, see
nlapiSearchDuplicate(type, fields, id).
Note: For general information on searching for duplicate records in NetSuite, see
Duplicate Record Detection in the NetSuite Help Center.
SuiteScript Developer and Reference Guide
Search Samples
Performing Global Searches
359
Performing Global Searches
NetSuite’s global search allows you to find records from anywhere in your account data. In the
UI, you enter your search keywords in the Search field in the upper right corner of any page.
In SuiteScript, global searches are executed using the nlapiSearchGlobal(keywords) function.
For the definition of this API, as well as a code sample, see nlapiSearchGlobal(keywords).
Note: For general information on global searching in NetSuite, see Global Search in the
NetSuite Help Center.
Searching CSV Saved Imports
You can use SuiteScript to search the CSV saved imports in an account. Executing this kind of
search may be useful if you need to access import information for CSV saved imports that were
bundled and installed in a new account.
For the type argument in nlapiSearchRecord(type, id, filters, columns), you will set
savedcsvimport. For example:
var search = nlapiSearchRecord('savedcsvimport', null, null, null);
Note that savedcsvimport is not a true record type in NetSuite, as it cannot be manipulated in
SuiteScript or in Web services. The savedcsvimport type can be used only in search. The
available filter and return values for savedcsvimport are:
•
internalid
•
name
•
description
Using Formulas, Special Functions, and Sorting in Search
function searchRecords()
{
// specify a formula column that displays the name as: Last Name, First Name (Middle Name)
var name = new nlobjSearchColumn('formulatext')
name.setFormula("{lastname}||', '||{firstname}||case when LENGTH({middlename})=0 then '' else '
('||{middlename}||')' end")
// now specify a numeric formula field
var number = new nlobjSearchColumn('formulanumeric').setFormula("1234.5678")
// now specify a numeric formula field and format the output using a special function
var roundednumber = new
nlobjSearchColumn('formulanumeric').setFormula("1234.5678").setFunction("round")
// now specify a sort column (sort by internal ID ascending)
var internalid = new nlobjSearchColumn('internalid').setSort( false /* bsortdescending */ )
var columns = [name, number, roundednumber, internalid]
SuiteScript Developer and Reference Guide
Search Samples
Using Summary Filters in Search
360
var filterHasMiddleName = new nlobjSearchFilter('middlename', null, 'isNotEmpty')
var searchresults = nlapiSearchRecord('contact', null, filterHasMiddleName , columns )
for ( var i = 0; i < searchresults.length; i++ )
{
// access the value using the column objects
var contactname = searchresults[i].getValue(name)
var value = searchresults[i].getValue(number)
var valuerounded = searchresults[i].getValue(roundednumber)
}
}
Using Summary Filters in Search
function searchRecords()
{
// perform a summary search: return all sales orders total amounts by customer for those with total sales >
1000
var filter = new nlobjSearchFilter('amount', null, 'greaterThan', 1000).setSummaryType('sum')
var entity = new nlobjSearchColumn('entity', null, 'group')
var amount = new nlobjSearchColumn('amount', null, 'sum')
var searchresults = nlapiSearchRecord('salesorder', null, filter, [entity, amount])
for ( var i = 0; i < searchresults.length; i++ )
{
// access the values this time using the name and summary type
var entity = searchresults[i].getValue('entity', null, 'group')
var entityName = searchresults[i].getText('entity', null, 'group')
var amount = searchresults[i].getValue('amount', null, 'sum')
}
}
SuiteScript Developer and Reference Guide
Chapter 42 Supported Search Operators,
Summary Types, and Date
Filters
This section lists all NetSuite field types that support SuiteScript search, as well as the operators
that that can be used on each type. Also listed are supported search summary types and search
date filters.
See the following sections for detailed reference information:
•
Search Operators
•
Search Summary Types
•
Search Date Filters
Search Operators
The following table lists each field type and its supported search operator.
Search Operator
Currency,
Decimal
Number,
Time of Day
after
Date
Check
Box
Email Address,
Free-Form Text,
Long Text,
Document,
Password,
Image
Percent, Phone
Number, Rich
Text, Text Area,
X
X
X
anyof
X
before
between
List/
Record
X
allof
any
Multi
Select
X
X
X
X
contains
X
doesnotcontain
X
doesnotstartwith
X
equalto
X
greaterthan
X
greaterthanorequalto
X
SuiteScript Developer and Reference Guide
Supported Search Operators, Summary Types, and Date
Filters
Search Operator
Currency,
Decimal
Number,
Time of Day
Date
is
Check
Box
Email Address,
Free-Form Text,
Long Text,
Document,
Password,
Image
Percent, Phone
Number, Rich
Text, Text Area,
X
isempty
X
Multi
Select
List/
Record
X
X
362
X
X
X
isnot
X
isnotempty
X
lessthan
X
lessthanorequalto
X
X
noneof
X
X
notafter
X
notallof
X
notbefore
X
notbetween
X
notempty
notequalto
X
notgreaterthan
X
notgreaterthanorequalto
X
notlessthan
X
notlessthanorequalto
X
noton
X
notonorafter
X
notonorbefore
X
notwithin
X
on
X
onorafter
X
onorbefore
X
startswith
within
X
X
Search Summary Types
The following table lists the summary types that can be applied to organize your search results.
Note that these summary types are available on the Results tab in the UI.
SuiteScript Developer and Reference Guide
Supported Search Operators, Summary Types, and Date
Filters
363
Summary Type
Type Internal ID
Purpose
Example
Group
group
Rolls up search results
under the column to which
you apply this type.
In a search for sales
transactions, you can group
the transactions found by
customer name.
Count
count
Counts the number of
results found that apply to
this column.
In a search of items
purchased by customers,
you can view a count of the
number of items purchased
by each customer.
Sum
sum
Sums search results.
In a search of purchases this
period, you can total the
Amount column on your
results.
Minimum
min
Shows the minimum
amount found in search
results.
In a search of sales
transactions by sales rep,
you can show the minimum
amount sold in the
transaction.
Maximum
max
Shows the maximum
amount found in search
results.
In a customer search by
partner, you can show the
maximum amount of sales
by each partner.
Average
avg
Calculates the average
amount found in your
search results.
In an employee search, you
can average the amounts of
your employees’ company
contributions.
Search Date Filters
The following table lists all supported search date filters.
Note: For relative date filters (filters that end with ago and fromnow), append the desired
time value to the filter to define the time period. For example, daysago15 is 15 days
ago from today or daysfromnow5 is 5 days from today.
Search Date Filter Values
daysago
daysfromnow
lastbusinessweek
lastfiscalquarter
lastfiscalquartertodate
lastfiscalyear
SuiteScript Developer and Reference Guide
Supported Search Operators, Summary Types, and Date
Filters
Search Date Filter Values
lastfiscalyeartodate
lastmonth
lastmonthtodate
lastrollingquarter
lastrollingyear
lastweek
lastweektodate
monthsago
monthsfromnow
nextbusinessweek
nextfiscalquarter
nextfiscalyear
nextfourweeks
nextmonth
nextonemonth
nextonequarter
nextoneweek
nextoneyear
nextweek
previousoneday
previousonemonth
previousonequarter
previousoneweek
previousoneyear
previousrollingquarter
previousrollingyear
quartersago
quartersfromnow
samemonthlastfiscalquarter
samemonthlastfiscalquartertodate
samemonthlastfiscalyear
samemonthlastfiscalyeartodate
samequarterlastfiscalyear
samequarterlastfiscalyeartodate
thisbusinessweek
thisfiscalquarter
SuiteScript Developer and Reference Guide
364
Supported Search Operators, Summary Types, and Date
Filters
Search Date Filter Values
thisfiscalquartertodate
thisfiscalyear
thisfiscalyeartodate
thismonth
thismonthtodate
thisrollingquarter
thisrollingyear
thisweek
thisweektodate
thisyear
today
tomorrow
weeksago
weeksfromnow
yearsago
yearsfromnow
yesterday
SuiteScript Developer and Reference Guide
365
Part 8 Working with
UI Objects
Chapter 43 UI Objects Overview
SuiteScript UI Objects are a collection of objects that can be used as a UI toolkit for server
scripts such as Suitelets and User Event Scripts. SuiteScript UI objects are generated on the
server as HTML. They are then displayed in the browser and are accessible through client
scripts. The following figure is a simple email form Suitelet built with UI objects.
The form itself is represented by the nlobjForm UI object. The Subject, Recipient email, and
Message fields are represented by the nlobjField UI object, and the Send Email button is
represented by the nlobjButton UI object.
To learn more about working with UI objects, see these topics:
•
Creating Custom NetSuite Pages with UI Objects
•
InlineHTML UI Objects
•
Building a NetSuite Assistant with UI Objects
Email Form Code
/**
* Build an email form Suitelet with UI objects. The Suitelet sends out an email
* from the current user to the recipient email address specified on the form.
*/
function simpleEmailForm(request, response)
{
if ( request.getMethod() == 'GET' )
{
var form = nlapiCreateForm('Email Form');
var subject = form.addField('subject','text', 'Subject');
subject.setLayoutType('normal','startcol');
SuiteScript Developer and Reference Guide
UI Objects Overview
subject.setMandatory( true );
var recipient = form.addField('recipient','email', 'Recipient email');
recipient.setMandatory( true );
var message = form.addField('message','textarea', 'Message');
message.setDisplaySize( 60, 10 );
form.addSubmitButton('Send Email');
response.writePage(form);
}
else
{
var currentuser = nlapiGetUser();
var subject = request.getParameter('subject')
var recipient = request.getParameter('recipient')
var message = request.getParameter('message')
nlapiSendEmail(currentuser, recipient, subject, message);
}
}
SuiteScript Developer and Reference Guide
368
Chapter 44 Creating Custom NetSuite
Pages with UI Objects
SuiteScript UI Objects encapsulate the UI elements necessary for building NetSuite-looking
portlets, forms, fields, sublists, tabs, lists, columns, and assistant. Note that when developing a
Suitelet with UI objects, you can also add custom fields with inline HTML.
Depending on the design and purpose of the custom UI, you can use either the nlobjFormUI
object or nlobjList UI object as the basis. These objects encapsulate a scriptable NetSuite form
and NetSuite list, respectively. You can then add a variety of scriptable UI elements to these
objects to adopt the NetSuite look-and-feel. These elements can include fields (through
nlobjField), buttons (through nlobjButton), tabs (through nlobjTab), and sublists (through
nlobjSubList).
Important: When adding UI elements to an existing page, you must prefix the element
name with custpage. This minimizes the occurrence of field/object name
conflicts. For example, when adding a custom tab to a NetSuite entry form in
a user event script, the name should follow a convention similar to
custpagecustomtab or custpagemytab.
UI Objects and Suitelets
In Suitelet development, UI objects allow you to programmatically build custom NetSuitelooking pages. A blank nlobjForm object is created with nlapiCreateForm(title, hideNavbar). If
you are building a custom assistant, a blank nlobjAssistant object is created with
nlapiCreateAssistant(title, hideHeader). On the server, the Suitelet code adds fields, steps, tabs,
buttons and sublists to the form and assistant objects.
The server defines the client script (if applicable) and sends the page to the browser. When the
page is submitted, the values in these UI objects become part of the request and available to aid
logic branching in the code.
For a basic example of a Suitelet built entirely of UI objects, see What Are Suitelets?. This
section also provides the code used to create the Suitelet. To see examples of an assistant or
“wizard” Suitelet built with UI objects, see Using UI Objects to Build an Assistant.
UI Objects and User Event Scripts
On entry forms and transaction forms, the nlobjForm object is accessed in user events scripts
on which new fields are added on the server before the pages are sent to the browser. With the
NetSuite nlobjForm object exposed, you can design user event scripts that manipulate most
built-in NetSuite UI components (for example, fields, tabs, sublists).
SuiteScript Developer and Reference Guide
Creating Custom NetSuite Pages with UI Objects
370
Note: If you are not familiar with concept of NetSuite entry or transaction forms, see
Custom Forms in the NetSuite Help Center.
The key to using user event scripts to customize a form during runtime is a second argument
named form in the before load event. This optional argument is the reference to the entry/
transaction form. You can use this to dynamically change existing form elements, or add new
ones (see Enhancing NetSuite Forms with User Event Scripts).
Note: Sometimes the best solution for a customized workflow with multiple pages is a
hybrid UI design, which encompasses both customized entry forms as well as
Suitelets built with UI objects.
SuiteScript Developer and Reference Guide
Chapter 45 InlineHTML UI Objects
[UE=HELP_TOPIC_OUT_OF_DATE_ALERT=UE]
SuiteScript UI objects make most of the NetSuite UI elements scriptable. However, they still
may not lend themselves well to certain use cases. In these circumstances, developers can
develop custom UI elements by providing HTML that SuiteScript can render on a NetSuite
page. These UI elements are known as “InlineHTML”.
InlineHTML can be implemented in two ways:
1.
Pure custom HTML with no SuiteScript UI objects
2.
Hybrid of custom HTML and SuiteScript UI objects
The first approach, shown on the left side, requires you to provide all the HTML code you want
to appear on the page, as if performing web designing on a blank canvas. The second approach,
shown on the right, allows custom HTML to be embedded in a NetSuite page. Example code is
available in the help section for Suitelets Samples.
An example of an application implemented with a hybrid of inlineHTML and UI objects is a
blog hosted within NetSuite. A blog page displays blog entries in descending chronological
order with “Read More” hyperlinks. Due to the potentially large number of entries, pagination
is required. Readers should also be able to read and leave comments. These requirements
cannot be easily satisfied by standard NetSuite UI elements in a reader-friendly manner.
However, rendering the blog entries’ data (stored as custom records) in HTML and displaying
it in SuiteScript UI objects as inlineHTML would satisfy this use case.
SuiteScript Developer and Reference Guide
InlineHTML UI Objects
SuiteScript Developer and Reference Guide
372
Chapter 46 Building a NetSuite Assistant
with UI Objects
NetSuite UI Object Assistant Overview
You can use UI objects to build an assistant or “wizard” within NetSuite that has the same lookand-feel as other built-in NetSuite assistants. To build your own assistant, you will use objects
such as nlobjAssistant, nlobjAssistantStep, nlobjFieldGroup, and nlobjField.
For examples that show some of the built-in assistants that come with NetSuite, see
Understanding NetSuite Assistants.
To learn to how programmatically construct your own assistant, see Using UI Objects to Build
an Assistant.
Understanding NetSuite Assistants
In NetSuite, assistants contain a series of steps that users must complete to accomplish a larger
task. In some assistants, users must complete the steps sequentially. In others, steps are nonsequential, and they do not all have to be completed. In these assistants, steps are provided only
as guidelines for actions users might want to take to complete a larger task.
The UI objects you use to construct your own assistant will encapsulate the look-and-feel of
assistants already built in to NetSuite. For examples of these assistants, see these topics:
•
Web Site Assistant
•
SuiteBundler Assistant
•
Import Assistant
SuiteScript Developer and Reference Guide
Building a NetSuite Assistant with UI Objects
Understanding NetSuite Assistants
374
Web Site Assistant
The Web Site Assistant is a built-in NetSuite assistant. This assistant guides users through a set
steps that are ordered sequentially. The ultimate goal of the assistant is to help users build their
own web sites.
Note: To access the Web Site Assistant, go to Setup > Web Site > Web Site Assistant.
This figure shows Step 1 (page 1) of the Web Site Assistant. Steps are ordered sequentially and
positioned vertically in the left panel. The current step is highlighted in gray.
All components called out in this figure can be built in a custom assistant.
SuiteScript Developer and Reference Guide
Building a NetSuite Assistant with UI Objects
Understanding NetSuite Assistants
375
SuiteBundler Assistant
The SuiteBundler Assistant is another built-in NetSuite assistant. This assistant guides users
through a set of steps in custom NetSuite solutions are “bundled,” later to be deployed into
other NetSuite accounts.
Note: To access the SuiteBundler Assistant, go to Setup > Customization > Create Bundle.
This figure shows Step 1 (page 1) of the SuiteBundler Assistant. Steps are ordered sequentially
and appear horizontally, directly below the title of the assistant.
All components called out in this figure can be built in a custom assistant.
SuiteScript Developer and Reference Guide
Building a NetSuite Assistant with UI Objects
Understanding NetSuite Assistants
376
Import Assistant
The Import Assistant guides users through a set steps that allow them to import data into
NetSuite.
Note: To access the Import Assistant, go to Setup > Import/Export > Import CSV Records.
This figure shows what an error message looks like in an assistant. Users cannot proceed to the
next step until the error is resolved. When building custom assistants, you can also throw
errors that prevent users from moving to the next step.
SuiteScript Developer and Reference Guide
Building a NetSuite Assistant with UI Objects
Using UI Objects to Build an Assistant
377
Using UI Objects to Build an Assistant
From a UI perspective, the building blocks of most assistants you build are going to include a
combination of the following: Steps, Field Groups, Fields, Buttons, Sublists.
To create this look, you will use objects such as nlobjAssistant, nlobjAssistantStep,
nlobjFieldGroup, and nlobjField. The API documentation for each object and all object
methods provides examples for building instances of each objects.
Also see these topics for additional information:
•
Understanding the Assistant Workflow
•
Using Redirection in an Assistant Workflow
•
Assistant Components and Concepts
•
UI Object Assistant Code Sample
Note that since your assistant is a Suitelet, once you have finished building the assistant, you
can initiate the assistant by creating a custom menu link that contains the Suitelet URL. (See
Running a Suitelet in NetSuite for details on creating custom menu links for Suitelets.)
SuiteScript Developer and Reference Guide
Building a NetSuite Assistant with UI Objects
Using UI Objects to Build an Assistant
378
Understanding the Assistant Workflow
If you have not done so already, please see Using UI Objects to Build an Assistant for
information on the UI objects that are used to create an assistant.
In your SuiteScript code, there is an order in which many components of an assistant must be
added. At a minimum you will:
1.
2.
Create a new assistant
a.
Call nlapiCreateAssistant(title, hideHeader).
b.
Add steps to the assistant. Use nlobjAssistant.addStep(name, label).
c.
Define whether the steps must be completed sequentially or whether they can be
completed in random order. Use nlobjAssistant.setOrdered(ordered).
Build assistant pages
Add fields, field groups, and sublists to build assistant pages for each step.
Note: In the context of an assistant, each step is considered a page.
In the assistant workflow diagram (below), see Build Page for a list of methods that
can be used to build a page.
3.
Process assistant pages
In your Suitelet, construct pages in response to a user’s navigation of the assistant. At a
minimum you will render a specific assistant step/page using a GET request. Then you
will process that page in the POST request, before then redirecting the user to another
step in the assistant.
For example, this is where you would update a user’s account based on data the user
has entered in the assistant.
The following flowchart provides an overview of a suggested assistant design.
SuiteScript Developer and Reference Guide
Building a NetSuite Assistant with UI Objects
Using UI Objects to Build an Assistant
Related Topics
•
•
•
Understanding NetSuite Assistants
Using UI Objects to Build an Assistant
UI Objects
SuiteScript Developer and Reference Guide
379
Building a NetSuite Assistant with UI Objects
Using UI Objects to Build an Assistant
380
Using Redirection in an Assistant Workflow
From within a custom assistant you can redirect users to:
•
a new record/page within NetSuite (for example, to a new Employee or Contact page in
NetSuite)
•
the start page of a built-in NetSuite assistant (for example, the Import Assistant or the
Web Site Assistant)
•
another custom assistant
To link users to another NetSuite page, built-in assistant, or custom assistant, and then return
them back to the originating assistant, you must set the value of the customwhence parameter
in the redirect URL to originating assistant. The value of customwhence will consist of the
scriptId and deploymentId of the originating custom assistant Suitelet.
Example
The following sample shows a helper function that appears at the end of the Assistant code
sample (see UI Object Assistant Code Sample). Notice that in this function, the value of the
customwhence parameter in the URL is the scriptId and deplomentId of the custom assistant
that you originally started with. To link users out of the originating assistant, and then return
them back to this assistant once they have completed other tasks, you must append the
customwhence parameter to the URL you are redirecting to.
function getLinkoutURL( redirect, type )
{
var url = redirect;
if ( type == "record" )
url = nlapiResolveURL('record', redirect);
url += url.indexOf('?') == -1 ? '?' : '&';
var context = nlapiGetContext();
url += 'customwhence='+ escape(nlapiResolveURL('suitelet',context.getScriptId(),
context.getDeploymentId()))
return url;
}
Note: If you redirect users to a built-in assistant or to another custom assistant, be aware
that they will not see the “Finish” page on the assistant they have been linked out
to. Once they complete the assistant they have been linked to, they will simply be
redirected back to the page where they left off in the original assistant.
SuiteScript Developer and Reference Guide
Building a NetSuite Assistant with UI Objects
Using UI Objects to Build an Assistant
381
Assistant Components and Concepts
The following information pertains to the UI components used to build an assistant. Also
described are the concepts associated with state management and error handling.
•
Steps
•
Field Groups
•
Fields
•
Sublists
•
Buttons
•
State Management
•
Error Handling
Steps
Create a step by calling nlobjAssistant.addStep(name, label), which returns a reference to the
nlobjAssistantStep object.
At a minimum, every assistant will include steps, since steps are what define each page of the
assistant. Whether the steps must be completed sequentially or in a more random order is up to
you. Enforced sequencing of steps be will defined by the nlobjAssistant.setOrdered(ordered)
method.
The placement of your steps (vertically along the left panel, or horizontally across the top of the
assistant) will also be determined by you. Also note that you can add helper text for each step
using the nlobjAssistantStep.setHelpText(help) method.
Note: Currently there is no support for sub-steps.
Field Groups
Create a field group by calling nlobjAssistant.addFieldGroup(name, label), which returns a
reference to the nlobjFieldGroup object.
In the UI, field group are collapsible groups of fields that can be displayed in a one-column or
two-column format. The following snippet shows how to use the
nlobjField.setLayoutType(type, breaktype) method to start a second column in a field group.
assistant.addFieldGroup("companyinfo", "Company Information");
assistant.addField("companyname", "text", "Company Name", null, "companyinfo")
assistant.addField("legalname", "text", "Legal Name", null, "companyinfo")
assistant.addField("shiptoattention", "text", "Ship To Attention", null, "companyinfo")
assistant.addField("address1", "text", "Address 1", null, "companyinfo").setLayoutType("normal", "startcol");
assistant.addField("address2", "text", "Address 2", null, "companyinfo");
assistant.addField("city", "text", "City", null, "companyinfo");
Note that field groups do not have to be collapsible. They can appear as a static grouping of
fields. See nlobjFieldGroup.setCollapsible(collapsible, hidden) for more information about
setting collapsibility.
SuiteScript Developer and Reference Guide
Building a NetSuite Assistant with UI Objects
Using UI Objects to Build an Assistant
382
Fields
Create a field by calling nlobjAssistant.addField(name, type, label, source, group), which
returns a reference to the nlobjField object.
Fields are added to the current step on a per-request basis. For example, as the sample below
shows, in a GET request, if the user’s current step is a step called "companyinformation",
(meaning the user has navigated to a step/page with the internal ID "companyinformation"),
the page that renders will include a field group and six fields within the group.
var step = assistant.getCurrentStep();
if (step.getName() == "companyinformation")
{
assistant.addFieldGroup("companyinfo", "Company Information");
assistant.addField("companyname", "text", "Company Name", null, "companyinfo")
assistant.addField("legalname", "text", "Legal Name", null, "companyinfo")
assistant.addField("shiptoattention", "text", "Ship To Attention", null, "companyinfo")
assistant.addField("address1", "text", "Address 1", null, "companyinfo").setLayoutType("normal", "startcol");
assistant.addField("address2", "text", "Address 2", null, "companyinfo");
assistant.addField("city", "text", "City", null, "companyinfo");
}
Note that all nlobjField APIs can be used with the fields returned from the addField(...)
method. Also, fields marked as 'mandatory' are respected by the assistant. Users cannot click
through to the next page if mandatory fields on the current page do not contain a value.
Important: The nlobjField.setLayoutType(type, break) method can be used to place a
column break in an assistant. Be aware that only the first column break that is
encountered will be honored. Currently assistants support only single or two
column layouts. You cannot set more than one column break.
Sublists
Create a sublist by calling nlobjAssistant.addSubList(name, type, label), which returns a
reference to the nlobjSubList object.
If you want to add a sublist to an assistant, be aware that only sublists of type inlineeditor are
supported. Also note that sublists on an assistant are always placed below all other elements on
the page.
The following figure shows an inlineeditor sublist on Step 3 of an assistant page.
[UE=HELP_TOPIC_OUT_OF_DATE_ALERT=UE]
SuiteScript Developer and Reference Guide
Building a NetSuite Assistant with UI Objects
Using UI Objects to Build an Assistant
383
Buttons
You do not need to programmatically add button objects to an assistant. Buttons are
automatically generated through the nlobjAssistant object.
Depending on which page you are on, the following buttons appear: Next, Back, Cancel, Finish.
When users reach the final step in an assistant, the Next button no longer displays, and the
Finish button appears. Button actions need to be communicated via the request using
nlobjAssistant.getLastAction().
Important: The addition of custom buttons are not currently supported on assistants.
State Management
Assistants support data and state tracking across pages within the same session until the
assistant is completed by the user (at which point the assistant is reset when the “Finished” page
displays).
Field data tracking is automatically saved in assistants. For example, if a user revisits a page
using the Back button, the previously entered data will be automatically displayed.
Every time a page is submitted, all the fields will be automatically tracked and when the page is
displayed. If the user did not explicitly set a value for a field or on a sublist, then the field(s) and
sublist(s) will be populated from data entered by the user the last time they submitted that
page.
Note: If state/data tracking needs to be preserved across sessions, you should use custom
records or tables to record this information.
Note that an SSS_NOT_YET_SUPPORTED_ERROR is thrown if the assistant is used on an
“Available Without Login” (external) Suitelet. (See Setting Available Without Login for
information on this Suitelet deployment option.) Session-based state tracking used in custom
assistants requires a session to exist across requests.
Finally, multiple Suitelet deployments should not be used to manage the pages within an
assistant, since data/state tracking is tied to the Suitelet instance. Developers should create one
Suitelet deployment per assistant.
Error Handling
If an error occurs on a step, the assistant displays two error indicators. The first indicator is a
red bar that appears directly below the step. The second indicator is the html you pass to
nlobjAssistant.setError(html).
SuiteScript Developer and Reference Guide
Building a NetSuite Assistant with UI Objects
Using UI Objects to Build an Assistant
384
Related Topics
•
•
•
•
Understanding NetSuite Assistants
Using UI Objects to Build an Assistant
UI Objects
Suitelets
UI Object Assistant Code Sample
The following is an implementation of a simple setup assistant with a few basic steps. State is
managed throughout the life of the user's session. In summary, this script shows you how to:
1.
Create the assistant.
2.
Create steps.
3.
Set the user’s first step.
4.
Build pages for each step.
5.
Process data entered by the user.
Note that this sample can be run in a NetSuite account. To do so, you must create a .js file for
the sample code below. Then you must create a new Suitelet script record and a script
deployment. Do not select the Available Without Login deployment option on the Script
Deployment page, otherwise the Suitelet will not run. (For general details on creating a Script
record, setting values on the Script Deployment page, and creating a custom menu link for a
Suitelet, see Running a Suitelet in NetSuite.)
Once the script is deployed, you can launch the assistant Suitelet by simply clicking the Suitelet
URL on the Script Deployment page. You can also create a tasklink for the Suitelet and launch
the Suitelet as a custom menu item.
Also notice that this sample has all three types of “link outs,” as defined in Using Redirection in
an Assistant Workflow: one link out to add employees, one to the Import Assistant, and one to
another custom assistant. Notice how the customwhence parameter is constructed and
appended to the target URL that you are linking out to. Also notice how
nlobjAssistant.sendRedirect(response) is used to ensure that customwhence is respected.
Important: If your browser is inserting scroll bars in this code sample, maximize your
browser window, or expand the main frame that this sample appears is.
/**
* Implementation of a simple setup assistant with support for multiple setup steps and sequential or ad-hoc step
traversal.
* State is managed throughout the life of the user's session but is not persisted across sessions. Doing so would
* require writing this information to a custom record.
*
* @param request request object
* @param response response object
SuiteScript Developer and Reference Guide
Building a NetSuite Assistant with UI Objects
Using UI Objects to Build an Assistant
385
*/
function showAssistant(request, response)
{
/* first create assistant object and define its steps. */
var assistant = nlapiCreateAssistant("Small Business Setup Assistant", true);
assistant.setOrdered( true );
nlapiLogExecution( 'DEBUG', "Create Assistant ", "Assistant Created" );
assistant.addStep('companyinformation', 'Setup Company Information').setHelpText("Setup your
<b>important</b> company information in the fields below.");
assistant.addStep('companypreferences', 'Setup Company Preferences').setHelpText("Setup your
<b>important</b> company preferences in the fields below.");
assistant.addStep('enterlocations', 'Enter Locations').setHelpText("Add Locations to your account.
You can create a location record for each of your company's locations. Then you can track employees
and transactions by location..");
assistant.addStep('enteremployees', 'Enter Company Employees').setHelpText("Enter your
company employees.");
assistant.addStep('importrecords', 'Import Records').setHelpText("Import your initial company data.");
assistant.addStep('configurepricing', 'Configure Pricing' ).setHelpText("Configure your item pricing.");
assistant.addStep('summary', 'Summary Information').setHelpText("Summary of your Assistant
Work.<br> You have made the following choices to configure your NetSuite account.");
/* handle page load (GET) requests. */
if (request.getMethod() == 'GET')
{
/*.Check whether the assistant is finished */
if ( !assistant.isFinished() )
{
// If initial step, set the Splash page and set the intial step
if ( assistant.getCurrentStep() == null )
{
assistant.setCurrentStep(assistant.getStep( "companyinformation") );
assistant.setSplash("Welcome to the Small Business Setup Assistant!", "<b>What
you'll be doing</b><br>The Small Business Setup Assistant will walk you
through the process of configuring your NetSuite account for your initial use..",
"<b>When you finish</b><br>your account will be ready for you to use to
run your business.");
}
var step = assistant.getCurrentStep();
// Build the page for a step by adding fields, field groups, and sublists to the assistant
if (step.getName() == "companyinformation")
{
assistant.addField('orgtypelabel','label','What type of organization are
you?').setLayoutType('startrow');
assistant.addField('orgtype', 'radio','Business To Consumer',
'b2c').setLayoutType('midrow');
assistant.addField('orgtype', 'radio','Business To Business','b2b').setLayoutType('midrow');
assistant.addField('orgtype', 'radio','Non-Profit','nonprofit').setLayoutType('endrow');
assistant.getField( 'orgtype', 'b2b' ).setDefaultValue( 'b2b' );
assistant.addField('companysizelabel','label','How big is your organization?');
assistant.addField('companysize', 'radio','Small (0-99 employees)', 's');
SuiteScript Developer and Reference Guide
Building a NetSuite Assistant with UI Objects
Using UI Objects to Build an Assistant
386
assistant.addField('companysize', 'radio','Medium (100-999 employees)','m');
assistant.addField('companysize', 'radio','Large (1000+ employees)','l');
assistant.addFieldGroup("companyinfo", "Company Information");
assistant.addField("companyname", "text", "Company Name", null,
"companyinfo").setMandatory( true );
assistant.addField("legalname", "text", "Legal Name", null, "companyinfo").setMandatory
( true );
assistant.addField("shiptoattention", "text", "Ship To Attention", null,
"companyinfo").setMandatory( true );
assistant.addField("address1", "text", "Address 1", null,
"companyinfo").setLayoutType("normal", "startcol");
assistant.addField("address2", "text", "Address 2", null, "companyinfo");
assistant.addField("city", "text", "City", null, "companyinfo");
assistant.getField("legalname").setHelpText("Enter a Legal Name if it differs from
your company name");
assistant.getField("shiptoattention").setHelpText("Enter the name of someone
who can sign for packages or important documents. This is important
because otherwise many package carriers will not deliver to your corporate address");
assistant.addFieldGroup("taxinfo", "Tax Information").setCollapsible(true /* collapsable */,
true /* collapsed by default */);
assistant.addField("employeeidnumber", "text", "Employee Identification Number (EIN)",
null, "taxinfo").setHelpText("Enter the EID provided to you by the state or
federal government");
assistant.addField("taxidnumber", "text", "Tax ID Number", null,
"taxinfo").setHelpText("Enter the Tax ID number used when you file your payroll
and sales taxes");
assistant.addField("returnmailaddress", "textarea", "Return Mail Address", null,
"taxinfo").setHelpText("In the rare event someone returns your products, enter
the mailing address.");
}
if (step.getName() == "companypreferences")
{
nlapiLogExecution( 'DEBUG', "Company Preferences ", "Begin Creating Page" );
assistant.addFieldGroup("companyprefs", "Company Preferences");
var firstDayOfWeek = assistant.addField("firstdayofweek", "select", "First Day of Week",
null, "companyprefs");
var stateAbbrs = assistant.addField("abbreviatestates", "checkbox", "Use State Abbreviations
in Addresses", null, "companyprefs");
var customerMessage = assistant.addField("customerwelcomemessage", "text", "Customer
Center Welcome Message", null, "companyprefs");
customerMessage.setMandatory( true );
assistant.addFieldGroup("accountingprefs", "Accounting Preferences").setCollapsible(true,
true );
var accountNumbers = assistant.addField("accountnumbers", "checkbox", "Use Account
Numbers", null, "accountingprefs");
var creditLimitDays = assistant.addField("credlimdays", "integer", "Days Overdue
for Warning or Hold", null, "accountingprefs");
var expenseAccount = assistant.addField("expenseaccount", "select", "Default
Expense Account", 'account', "accountingprefs");
customerMessage.setMandatory( true );
SuiteScript Developer and Reference Guide
Building a NetSuite Assistant with UI Objects
Using UI Objects to Build an Assistant
387
assistant.addField('customertypelabel','label','Please Indicate Your Default Customer
Type?' );
assistant.addField( 'customertype', 'radio', 'Individual', 'i' );
assistant.addField('customertype', 'radio', 'Company', 'c' );
// get the select options for First Day of Week
nlapiLogExecution( 'DEBUG', "Load Configuration ", "Company Preferences" );
var compPrefs = nlapiLoadConfiguration( 'companypreferences' );
var firstDay = compPrefs.getField( 'FIRSTDAYOFWEEK' );
nlapiLogExecution( 'DEBUG', "Create Day of Week Field ", compPrefs.getFieldText(
'FIRSTDAYOFWEEK') );
try
{
var selectOptions = firstDay.getSelectOptions();
}
catch( error )
{
assistant.setError( error );
}
if( selectOptions != null)
{
nlapiLogExecution( 'DEBUG', "Have Select Options ", selectOptions[0].getText() );
// add the options to the UI field
for (var i = 0; i < selectOptions.length; i++)
{
firstDayOfWeek.addSelectOption( selectOptions[i].getId(),
selectOptions[i].getText() );
}
}
// set the default values based on the product default
stateAbbrs.setDefaultValue( compPrefs.getFieldValue( 'ABBREVIATESTATES' ) );
customerMessage.setDefaultValue( compPrefs.getFieldValue(
'CUSTOMERWELCOMEMESSAGE' ) );
}
else if (step.getName() == "enterlocations")
{
var sublist = assistant.addSubList("locations", "inlineeditor", "Locations");
sublist.addField("name", "text", "Name");
sublist.addField("tranprefix", "text", "Transaction Prefix");
sublist.addField("makeinventoryavailable", "checkbox", "Make Inventory Available");
sublist.addField("makeinventoryavailablestore", "checkbox", "Make Inventory Available in
Web Store");
sublist.setUniqueField("name");
}
SuiteScript Developer and Reference Guide
Building a NetSuite Assistant with UI Objects
Using UI Objects to Build an Assistant
388
else if (step.getName() == "enteremployees")
{
// get the host
var host = request.getURL().substring(0, ( request.getURL().indexOf('.com') + 4) );
assistant.addFieldGroup("enteremps", "Enter Employees");
assistant.addField("employeecount", "integer", "Number of Employees in Company", null,
"enteremps").setMandatory( true );
assistant.addField("enterempslink", "url", "", null, "enteremps" ).setDisplayType
( "inline" ).setLinkText( "Click Here to Enter Your Employees").setDefaultValue( host
+ getLinkoutURL( 'employee', 'record') );
}
else if (step.getName() == "importrecords")
{
var host = request.getURL().substring(0, ( request.getURL().indexOf('.com') + 4) );
assistant.addFieldGroup("recordimport", "Import Data");
assistant.addField("recordcount", "integer", "Number of Records to Import", null,
"recordimport").setMandatory( true );
assistant.addField("importlink", "url", "", null, "recordimport" ).setDisplayType
( "inline" ).setLinkText( "Click Here to Import Your Data").setDefaultValue( host +
getLinkoutURL( "/app/setup/assistants/nsimport/importassistant.nl" ) );
}
else if (step.getName() == "configurepricing")
{
var host = request.getURL().substring(0, ( request.getURL().indexOf('.com') + 4) );
assistant.addFieldGroup("pricing", "Price Configuration");
assistant.addField("itemcount", "integer", "Number of Items to Configure", null,
"pricing").setMandatory( true );
/* When users click the ‘Click Here to Configure Pricing’ link, they will be taken to
* another custom assistant Suitelet that has a script ID of 47 and a deploy ID of 1. Note
* that the code for the “link out” assistant is not provided in this sample.
*
* Notice the use of the getLinkoutURL helper function, which sets the URL
* customwhence parameter so that after users finish the with the “link out” assistant,
* they will be redirected back to this (the originating) assistant.
*/
assistant.addField("importlink", "url", "", null, "pricing" ).setDisplayType
( "inline").setLinkText( "Click Here to Configure Pricing").setDefaultValue( host +
getLinkoutURL( "/app/site/hosting/scriptlet.nl?script=47&deploy=1" ) );
}
else if (step.getName() == "summary")
{
assistant.addFieldGroup("companysummary", "Company Definition Summary");
assistant.addField('orgtypelabel','label','What type of organization are you?', null,
'companysummary' );
SuiteScript Developer and Reference Guide
Building a NetSuite Assistant with UI Objects
Using UI Objects to Build an Assistant
389
assistant.addField('orgtype', 'radio','Business To Consumer', 'b2c',
'companysummary' ).setDisplayType( 'inline');
assistant.addField('orgtype', 'radio','Business To Business','b2b',
'companysummary' ).setDisplayType( 'inline');
assistant.addField('orgtype', 'radio','Non-Profit','nonprofit',
'companysummary' ).setDisplayType( 'inline');
assistant.addField('companysizelabel','label','How big is your organization?', null,
'companysummary' );
assistant.addField('companysize', 'radio','Small (0-99 employees)', 's',
'companysummary' ).setDisplayType( 'inline');;
assistant.addField('companysize', 'radio','Medium (100-999 employees)','m',
'companysummary' ).setDisplayType( 'inline');;
assistant.addField('companysize', 'radio','Large (1000+ employees)','l',
'companysummary' ).setDisplayType( 'inline');;
assistant.addField("companyname", "text", "Company Name", null,
"companysummary").setDisplayType( 'inline');
assistant.addField("city", "text", "City", null, "companysummary").setDisplayType('inline');
assistant.addField("abbreviatestates", "checkbox", "Use State Abbreviations in Addresses",
null, "companysummary").setDisplayType( 'inline');
assistant.addField("customerwelcomemessage", "text", "Customer Center Welcome
Message", null, "companysummary").setDisplayType( 'inline');
// get previously submitted steps
var ciStep = assistant.getStep( 'companyinformation' );
var cpStep = assistant.getStep( 'companypreferences' );
// get field values from previously submitted steps
assistant.getField( 'orgtype', 'b2b' ).setDefaultValue( ciStep.getFieldValue( 'orgtype' ) );
assistant.getField( 'companysize', 's' ).setDefaultValue( ciStep.getFieldValue
( 'companysize' ) );
assistant.getField( 'companyname' ).setDefaultValue( ciStep.getFieldValue
( 'companyname' ) );
assistant.getField( 'city' ).setDefaultValue( ciStep.getFieldValue( 'city' ) );
assistant.getField( 'abbreviatestates' ).setDefaultValue( cpStep.getFieldValue
( 'abbreviatestates' ) );
assistant.getField( 'customerwelcomemessage' ).setDefaultValue
( cpStep.getFieldValue( 'customerwelcomemessage' ) );
}
}
response.writePage(assistant);
}
/* handle user submit (POST) requests. */
else
{
assistant.setError( null );
/* 1. if they clicked the finish button, mark setup as done and redirect to assistant page */
if (assistant.getLastAction() == "finish")
SuiteScript Developer and Reference Guide
Building a NetSuite Assistant with UI Objects
Using UI Objects to Build an Assistant
390
{
assistant.setFinished( "You have completed the Small Business Setup Assistant." );
assistant.sendRedirect( response );
}
/* 2. if they clicked the "cancel" button, take them to a different page (setup tab) altogether as
appropriate. */
else if (assistant.getLastAction() == "cancel")
{
nlapiSetRedirectURL('tasklink', "CARD_-10");
}
/* 3. For all other actions (next, back, jump), process the step and redirect to assistant page. */
else
{
if (assistant.getLastStep().getName() == "companyinformation" && assistant.getLastAction()
== "next" )
{
// update the company information page
var configCompInfo = nlapiLoadConfiguration( 'companyinformation' );
configCompInfo.setFieldValue( 'city', request.getParameter( 'city' ) ) ;
nlapiSubmitConfiguration( configCompInfo );
}
if (assistant.getLastStep().getName() == "companypreferences" && assistant.getLastAction()
== "next" )
{
// update the company preferences page
var configCompPref = nlapiLoadConfiguration( 'companypreferences' );
configCompPref.setFieldValue( 'CUSTOMERWELCOMEMESSAGE',
request.getParameter( 'customerwelcomemessage' ) );
nlapiSubmitConfiguration( configCompPref );
// update the accounting preferences pages
var configAcctPref = nlapiLoadConfiguration( 'accountingpreferences' );
configAcctPref.setFieldValue( 'CREDLIMDAYS', request.getParameter( 'credlimdays' ) );
nlapiSubmitConfiguration( configAcctPref );
}
if (assistant.getLastStep().getName() == "enterlocations" && assistant.getLastAction() == "next"
)
{
// create locations
for (var i = 1; i <= request.getLineItemCount( 'locations'); i++)
{
locationRec = nlapiCreateRecord( 'location' );
locationRec.setFieldValue( 'name', request.getLineItemValue( 'locations', 'name', i ) );
SuiteScript Developer and Reference Guide
Building a NetSuite Assistant with UI Objects
Using UI Objects to Build an Assistant
locationRec.setFieldValue( 'tranprefix', request.getLineItemValue( 'locations',
'tranprefix', i ) );
locationRec.setFieldValue( 'makeinventoryavailable', request.getLineItemValue
('locations', 'makeinventoryavailable', i ) );
locationRec.setFieldValue( 'makeinventoryavailablestore',
request.getLineItemValue('locations', 'makeinventoryavailablestore', i ) );
try
{
// add a location to the account
nlapiSubmitRecord( locationRec );
}
catch( error )
{
assistant.setError( error );
}
}
}
if( !assistant.hasError() )
assistant.setCurrentStep( assistant.getNextStep() );
assistant.sendRedirect( response );
}
}
}
function getLinkoutURL( redirect, type )
{
var url = redirect;
if ( type == "record" )
url = nlapiResolveURL('record', redirect);
url += url.indexOf('?') == -1 ? '?' : '&';
var context = nlapiGetContext();
url += 'customwhence='+ escape(nlapiResolveURL('suitelet',context.getScriptId(),
context.getDeploymentId()))
return url;
}
SuiteScript Developer and Reference Guide
391
Part 9 Debugging SuiteScript
Chapter 47 Debugging SuiteScript
Debugging Overview
You can use the SuiteScript Debugger to debug server scripts. Server script types are user
event, Suitelet, scheduled, and portlet scripts.
To debug client scripts, NetSuite recommends using either the Firebug debugger, which
integrates with Firefox, or the Microsoft Script Debugger, which integrates with Internet
Explorer. For instructions on working with either of these debuggers, please see the
documentation provided with each product.
To work with the SuiteScript Debugger, you will need to learn about the following:
1.
Accessing a Debugger domain as well as requirements for running the SuiteScript
Debugger (see Before Using the Debugger)
2.
SuiteScript Debugger metering and permission restrictions (see Debugger Metering
and Permissions)
3.
How to use the SuiteScript Debugger (see Using the SuiteScript Debugger)
4.
SuiteScript Debugger tabs and buttons (see SuiteScript Debugger Interface)
To view script execution details either while using the SuiteScript Debugger, or after the script
has been deployed into NetSuite, see Using the Script Execution Log.
Using the SuiteScript Debugger
The SuiteScript Debugger provides two debugging modes, which are based on the type of
script you want to debug.
•
Ad-hoc Debugging: Enables you to debug code fragments written “on-the-fly.” With
ad-hoc debugging you are debugging a new script or code snippet that does not have a
defined SuiteScript deployment. Scripts that do not require any form/record-specific
interaction are good candidates for ad-hoc debugging.
•
Deployed Debugging: Enables you to select an existing script that already has a defined
SuiteScript deployment. These scripts include User Event, Portlet, Scheduled, and
Suitelet scripts. The status of these scripts must be set to Testing before they can be
loaded into the Debugger. You must also be the owner of the script.
SuiteScript Developer and Reference Guide
Debugging SuiteScript
Debugging Overview
Related Topics
•
•
•
Before Using the Debugger
SuiteScript Debugger Interface
Debugger Metering and Permissions
SuiteScript Developer and Reference Guide
394
Chapter 48 Before Using the Debugger
Before using the SuiteScript Debugger, you must be aware of the following:
•
There are three separate Debugger domains, accessible by going to Setup >
Customization > Script Debugger from a production account, a Beta account, or a
sandbox account. You can also access a Debugger domain by going directly to the
following URLs:
• https://debugger.netsuite.com/pages/login.jsp.
You must then log in to NetSuite.
Important: Any changes you make to your account while on this Debugger
domain will affect the data in your production account. For example, if you
execute a script in the Debugger that creates a new record, that record will appear
in your production account.
• https://debugger.beta.netsuite.com
If you have a Beta account and choose to run the Debugger in this environment, go
to this Debugger domain.
Note that if you go to Setup > Customization > Script Debugger in your Beta
account, you will be directed to the Debugger Beta domain. Any changes you
make to your account while on the Debugger Beta domain will affect your Beta
account only.
• https://debugger.sandbox.netsuite.com
If you have a sandbox account and choose to run the Debugger in this
environment, go to this Debugger domain.
Note that if you go to Setup > Customization > Script Debugger in your sandbox
account, you will be directed to the Debugger sandbox domain. Any changes you
make to your account while on the Debugger sandbox domain will affect your
sandbox account only.
Once are you logged on to a Debugger domain, you will see the Debugger logo at the
top of your account.
SuiteScript Developer and Reference Guide
Before Using the Debugger
396
Note: There may be a decrease in performance when working on Debugger domains.
•
The Debugger executes server-side scripts only (these script types include Suitelets,
Portlet scripts, Scheduled scripts, and User Event scripts). Client scripts (both formand record-level) should be tested on the form/record they run against.
•
To debug scripts, the following must apply:
• You must have scripting permission.
• You must be the assigned owner of the script.
• If you are debugging a script that already has a defined deployment, that script
must be in Testing mode before it can be loaded into the Debugger. If you want to
debug a script that has already been released into production, you must change the
script’s status from Released to Testing on the Script Deployment page.
•
If a bundled script has been installed into your account and the script has been marked
as hidden, you will be unable to debug this script.
Be aware that the SuiteScript Debugger is not any of the following:
•
An API test console
•
An integrated development environment (IDE)
•
A script deployment interface. To deploy SuiteScript to NetSuite, you must still create a
script record and define the script’s deployment parameters on the Script Deployment
page.
•
A Client SuiteScript debugger
•
A script runner interface (for example, scheduled scripts still need to be put
INQUEUE for task completion)
Related Topics
•
•
•
Debugger Metering and Permissions
Using the SuiteScript Debugger
SuiteScript Debugger Interface
SuiteScript Developer and Reference Guide
Chapter 49 Ad-hoc Debugging
Ad-hoc debugging is for testing scripts or code snippets that do not have a defined SuiteScript
deployment. Ad-hoc debugging is not for scripts that have a Script record or defined
deployment parameters (set on the Script Deployment page).
To use the Debugger in ad-hoc mode:
1.
Go to Setup > Customization > Script Debugger if you are already logged in to a
production, Beta, or sandbox NetSuite account. Or, go directly to one of the following
Debugger domains:
• https://debugger.netsuite.com
• https://debugger.beta.netsuite.com (if you have a Beta account and choose to run
the Debugger in this environment)
• https://debugger.sandbox.netsuite.com (if you have a sandbox account and choose
the run the Debugger in this environment)
Important: See Before Using the Debugger to learn about how the changes you make to
your account on a Debugger domain can affect your production, Beta, or
sandbox account.
SuiteScript Developer and Reference Guide
Ad-hoc Debugging
398
The following figure shows the Script Debugger start page.
2.
Type your code snippet in the New Script text area.
If you have already written your code in an IDE, copy-and-paste the code into the
Debugger text area. If you modify your script in the Debugger and you intend to save
the changes, you must copy the updated script from the Debugger and paste it into
your IDE.
3.
Next, click the Debug Script button.
The script is immediately loaded into the Debugger and the program's execution stops
at the first line of executable code. In this example, the first line of executable code is:
var g = 100;
SuiteScript Developer and Reference Guide
Ad-hoc Debugging
SuiteScript Developer and Reference Guide
399
Ad-hoc Debugging
400
Note that this sample includes an f1() calling function at the bottom of the script.
Without a calling function, this script will simply compile with nothing to execute.
With the ad-hoc script loaded into the Debugger, you can now step through each line to inspect
local variables and object properties. You can also add watches, evaluate expressions, and set
break points.
See SuiteScript Debugger Interface for information on stepping into/out of functions, adding
watches, setting and removing break points, and evaluating expressions.
SuiteScript Developer and Reference Guide
Ad-hoc Debugging
4.
After testing/debugging your ad-hoc script, you can either re-run the script (by
clicking the Re-run Script button), or put the script into edit mode (by clicking the
Switch to Editor button) and continue debugging.
SuiteScript Developer and Reference Guide
401
Ad-hoc Debugging
Related Topics
•
•
•
•
Debugger Metering and Permissions
Using the SuiteScript Debugger
Deployed Debugging
SuiteScript Debugger Interface
SuiteScript Developer and Reference Guide
402
Chapter 50 Deployed Debugging
Deployed-mode debugging is for testing and inspecting scripts that have a defined SuiteScript
deployment—in other words, you have already set the deployment for this script on the Script
Deployment page (see figure below).
To use the Debugger in deployed-mode:
1.
Go to Setup > Customization > Script Debugger if you are already logged in to a
production, Beta, or sandbox NetSuite account. Or, go directly to one of the following
Debugger domains:
• https://debugger.netsuite.com
• https://debugger.beta.netsuite.com (if you have a Beta account and choose to run
the Debugger in this environment)
• https://debugger.sandbox.netsuite.com (if you have a sandbox account and choose
the run the Debugger in this environment)
Important: See Before Using the Debugger to learn about how the changes you make to
your account on a Debugger domain can affect your production, Beta, or
sandbox account.
SuiteScript Developer and Reference Guide
Deployed Debugging
2.
Once you are on a Debugger domain, navigate to the script’s deployment page and
verify the script status is set to Testing. If you wish to debug a script that has already
been released into production, you must change the script status from Released to
Testing.
3.
Verify that you are the assigned owner of the script. You can only debug scripts in
which you are the assigned owner.
4.
To get to the Debugger start page, use the appropriate option:
404
• If you are on the Script Deployment page in View mode, click the Debug button. If
you are on the Script Deployment page in Edit mode, click the Save and Debug
button.
• If you are not on the Script Deployment page, you can navigate to the Debugger by
going to Setup > Customization > Script Debugger.
5.
When the Script Debugger page opens, click the Debug Existing button.
SuiteScript Developer and Reference Guide
Deployed Debugging
405
After clicking Debug Existing, the Script Debugger popup window opens. The popup
shows all the User Event, Portlet, Suitelet, and Scheduled scripts that are available for
debugging (see figure below). Note that only scripts whose statuses are set to Testing
will appear in the Script Debugger popup.
6.
Select the script you want to debug, and then click the Select and Close button in the
popup window.
The following figure shows the selection of a beforeLoad User Event script that runs on
Customer records. When a new Customer is created, this script sets a custom checkbox
field called Export to OpenAir to true.
7.
After clicking Select and Close, the Waiting for User Action screen appears (see figure
below). To load User Event, Portlet, and Suitelet scripts into the Debugger, you must
perform the action that calls the script.
Note: You do not have to perform any user actions for Scheduled scripts to load into the
Debugger. Simply select your Scheduled script from the Script Debugger popup
window, and then click Save and Close. The Scheduled script automatically loads.
In this example, you must create a new Customer for the User Event script to load into
the Debugger. Performing the action that actually calls the script creates a “real-time,”
live context for script debugging.
SuiteScript Developer and Reference Guide
Deployed Debugging
8.
406
Next, create a new Customer to load the User Event script into the Debugger.
Important: It is highly recommended that when performing user actions, you do so in
another window or another tab (see figure below). Doing so enables you to
keep the Debugger window open so that you can see the script as it loads.
•
The first figure shows that a new Customer will be created in a separate window.
•
The second figure shows the setOpenAirField.js file as it loads into the Script
Debugger window.
•
The third figure shows a new Customer record in a separate window (or separate tab).
Note the Export to OpenAir field defaults to true (meaning that the checkbox is
automatically selected).
SuiteScript Developer and Reference Guide
Deployed Debugging
SuiteScript Developer and Reference Guide
407
Deployed Debugging
9.
408
With the code in the Debugger text area, you have the following options:
a.
Click the Step Over button to begin stepping through each line of code.
b.
Add watches and evaluate expressions.
c.
Set break points and click the Run button to run the code. The Debugger will stop
code execution at the first break point set.
d.
Set no break points, click the Run button, and have the Debugger execute the
entire piece of code.
See SuiteScript Debugger Interface for information on stepping into/out of functions,
adding watches, setting and removing break points, and evaluating expressions.
10.
After testing/debugging a deployed-mode script, you can either re-run the script (by
clicking the Re-run Script button), or put the script into edit mode (by clicking the
Switch to Editor button) and continue debugging.
SuiteScript Developer and Reference Guide
Deployed Debugging
409
Important: If you modify your script in the Debugger, and you intend to save the
changes, you must copy the updated script from the Debugger and paste it
into your IDE. You must then re-load the updated .js file into the NetSuite file
cabinet.
Related Topics
•
•
•
•
Debugger Metering and Permissions
Using the SuiteScript Debugger
Ad-hoc Debugging
SuiteScript Debugger Interface
SuiteScript Developer and Reference Guide
Chapter 51 Debugger Metering and
Permissions
The SuiteScript Debugger adheres to the following metering and permission restrictions:
•
A user is only allowed to debug a single script at a time. Attempting to debug multiple
scripts simultaneously (for example, by opening two different browser windows) will
result in the same script/debugging session appearing in both windows.
•
Users can debug only their own scripts in their current login session.
•
There is a 1000 unit usage limit on all scripts being debugged. This is important to
note, particularly for script types such as Scheduled scripts, which are permitted
10,000 units when running in NetSuite. If, for example, you load a 2,000 unit
Scheduled script into the Debugger and attempt to step through or execute your code,
the Debugger will throw a usage limit error once it reaches 1000 units.
•
Email error notification is disabled for scripts being debugged. Additionally, execution
log details are displayed on the Execution Log tab in the Debugger rather than in the
execution log on the Script Deployment page.
•
There is a two minute time limit on scripts sitting idle in the Debugger. If you do not
perform some user action in the Debugger within the two minutes, the following error
is thrown (see figure):
If you receive this message and you are in deployed-debugging mode, click the Go
Back button. You must then reload your script by clicking the Debug Existing button
(see figure below).
If you are debugging in ad-hoc mode, click the Go Back button, click in the Debugger
text area, and re-type your code snippet.
(See Using the SuiteScript Debugger for information on deployed and ad-hoc
debugging modes.)
SuiteScript Developer and Reference Guide
Debugger Metering and Permissions
•
There is a 10 minute global timeout on all scripts being debugged. This means that
even if you are performing user actions within the Debugger every two minutes, the
Debugger itself will timeout after 10 minutes.
Related Topics
•
•
•
Before Using the Debugger
Using the SuiteScript Debugger
SuiteScript Debugger Interface
SuiteScript Developer and Reference Guide
411
Chapter 52 SuiteScript Debugger Interface
See the following sections to learn about the Debugger UI.
•
SuiteScript Debugger Buttons
•
SuiteScript Debugger Tabs
Use the Debugger buttons to control the flow of script execution. Use the tabs to inspect all
script variables, objects, and properties.
SuiteScript Debugger Buttons
There are five Debugger buttons that can be used to control/resume script execution once the
Debugger stops at a particular line:
•
Step Over: Resumes execution from the current line and stops at the next line (even if
the current line is a function call).
•
Step Into: Resumes execution from the current line and stops at the first line in any
function call made from the current line.
•
Step Out: Resumes execution from the current line until the end of the current
function, and stops at the first line following the line from where this function was
called -or- until the next break point -or- until the program terminates (either by error
or by normal completion).
•
Continue: Resumes program execution from the current line until the next break point
-or- until the program terminates
•
Cancel: Aborts execution of the program from the current line.
SuiteScript Developer and Reference Guide
SuiteScript Debugger Interface
413
Note: Keyboard shortcuts are enabled for all five Debugger buttons. See Debugger
Keyboard Shortcuts for details.
Related Topics
•
•
•
SuiteScript Debugger Tabs
Before Using the Debugger
Using the SuiteScript Debugger
SuiteScript Debugger Tabs
The SuiteScript Debugger includes the following tabs. Click the links below to jump to
information about each tab.
•
Execution Log
•
Local Variables
•
Watches
•
Evaluate Expressions
•
Break Points
Execution Log
Click the Execution Log tab to view all the execution logs (including errors logged by the
system) created by the currently executing program. The execution log details that appear on
this tab are the same details that would normally appear in the Execution Log on the Script
SuiteScript Developer and Reference Guide
SuiteScript Debugger Interface
414
Deployment page. However, when working in the Debugger, all script execution details appear
on the Execution Log tab within the Debugger; these details will NOT appear on the Execution
Log tab on the Script Deployment page.
The type, subject, details, and timestamp are displayed in the on the Debugger Execution Log
tab. The timestamp is recorded on the server but converted to the current user's time zone for
display. The console is automatically cleared at the start of every debugging session.
Log details are collapsed by default, but can be seen by clicking the expand/collapse icon.
Local Variables
Click the Local Variables to see a browse-able list of all local variables (primitives, objects, and
NetSuite objects) currently in scope. Note that for NetSuite (nlobj) objects, all properties are
private, even though they can be seen on the Local Variables tab. Do not try to reference these
properties directly in your script. Use the appropriate getter/setter functions instead.
Due to performance considerations, only the first 50 entries of an Array are displayed. Also,
only the first 500 characters of a String are displayed.
Click the Call Stack drop-down to see a list containing a browse-able view of the current
execution stack of the program. The function call and current line number for that function are
included in the Call Stack drop-down. Use the Call Stack drop-down to switch to different call
stacks for local variable observation. In addition, watch expressions and expression evaluations
will automatically be performed in the context specified by this field.
Watches
The Watch tab is where you can add or remove expressions to a list that is maintained and kept
up-to-date (“watched”) throughout the execution of a script. The expressions are always
SuiteScript Developer and Reference Guide
SuiteScript Debugger Interface
415
evaluated in the current call stack. This means that by default they are evaluated at the current
line of script execution. However, if you switch to a different function in the call stack, they will
be re-evaluated in that context.
•
To add an expression, type it into the Add Watch field and press the Enter key.
•
To remove a watch expression, click on the x icon to the left of the expression.
•
To browse sub-properties of a user-defined object, an array, or a NetSuite object (nlobj)
expression, click the expand/collapse icon next to the property name.
Note that you can use the watch window to navigate to object properties via a command line
interface. Any property that is viewable from the property browser can be added as a watch
expression simply by referencing the property using dot ( . ) notation, even if the property is
private in the actual script (for example, you can reference the ID of an nlobjRecord object
(referenced by a variable called record) by typing record.id).
Evaluate Expressions
Use the Evaluate Expressions tab to execute code at break points during the current program.
Doing so provides access to the program's state, allowing you to modify the state of the
program.
Enter an expression in the Evaluate Expression field and press the Enter key to run it at the
selected call stack. The results of an evaluated expression (if any) is displayed in the window
below. Any changes to the program's state will immediately be reflected in the Local Variables
and Watches windows.
SuiteScript Developer and Reference Guide
SuiteScript Debugger Interface
416
Break Points
Click the Break Points tab to view all of your instruction-level (line) break points as well as
your user event break points (see figure). Note that you can add user event break points by
selecting user events from the Break on User Event drop-down.
By setting breakpoints in your code, you can execute your code up to a certain point, and then
halt the execution at the break point and examine the current state of the execution.
To add/remove break points in your code:
•
To add a break point, click between the line number and the actual line of code (see
figure below).
•
To remove a break point, click the break point icon as it appears in the code. You can
also remove a break point by clicking the x icon next to the break point (as it appears
on the Break Points tab).
SuiteScript Developer and Reference Guide
SuiteScript Debugger Interface
Related Topics
•
•
•
SuiteScript Debugger Buttons
Before Using the Debugger
Using the SuiteScript Debugger
SuiteScript Developer and Reference Guide
417
Chapter 53 Debugger Keyboard Shortcuts
The following table lists the keyboard shortcuts that are enabled for all five debugger action
buttons. Your cursor must be inside the main Debugger text area for the keyboard shortcuts to
work.
Key
Command
i
Step Into
space
Step Over
o
Step Out
shift+space
Continue
q
Quit
d
Debug Script (New)
a
Debug Script (Existing)
r
Re-run Script
Related Topics
•
•
•
Before Using the Debugger
Using the SuiteScript Debugger
SuiteScript Debugger Interface
SuiteScript Developer and Reference Guide
Chapter 54 Debugger Glossary
Keyword
Definition
Line Break Point
User-defined line in source code where program halts
execution
User Event Break Point
User event possibly invokable during script execution where
the program halts execution
Watch
A variable expression that will be monitored throughout the
program's execution in the current scope
Call Stack
A stack (most recent on top) of all the active functions (and
their local variables) called up until the current line of execution
SuiteScript Developer and Reference Guide
Part 10 SuiteScript API
Chapter 55 SuiteScript API Overview
The SuiteScript API documentation is organized in a few different ways. Depending on how
you wish to access the information, see any of the following links:
•
SuiteScript Functions – Organizes the entire SuiteScript API into functional categories.
Links to all functions and objects are provided.
•
SuiteScript Objects – Defines all objects in the SuiteScript API
•
SuiteScript API - Alphabetized Index – Provides an alphabetized list of all SuiteScript
functions and objects. If you prefer viewing APIs as an alpabetized list, click this link.
Important Things to Note:
•
The SuiteScript API lets you programmatically extend NetSuite beyond the capabilities
offered through SuiteBuilder point-and-click customization. However, a sound
understanding of general NetSuite customization principles will help you when writing
SuiteScript. If you have no experience customizing NetSuite using SuiteBuilder, it is
worth seeing SuiteBuilder Overview.
•
Most SuiteScript APIs pass record, field, sublist, tab, search filter, and search column
IDs as arguments. In the NetSuite Help Center, see SuiteScript Reference to learn how
to access all supported internal IDs.
•
In your SuiteScript code, all record, field, sublist, tab, search join, search field, and
search column IDs must be in lowercase.
•
If you are new to SuiteScript and have no idea how to get a script to run in your
NetSuite account, you should start here: SuiteScript - The Basics.
SuiteScript Developer and Reference Guide
Chapter 56 SuiteScript Functions
SuiteScript Functions Overview
Important: If you are not familiar with the SuiteScript API, we recommend you see
SuiteScript API Overview.
This documentation organizes all SuiteScript functions into the functional categories listed
below. Note that some APIs appear in more than one category. For example,
nlapiLookupField(...) appears in both the Field APIs and Search APIs categories, however it is
documented only once.
•
Working with entire record object – see Record APIs
•
Working with subrecords – see Subrecord APIs
•
Working with fields on a record – see Field APIs
•
Working with sublists on a record – see Sublist APIs
•
Searching in NetSuite – see Search APIs
•
Scheduling scripts to run at specified times – see Scheduling APIs
•
Getting context information about a script, a user, an account – see Execution Context
APIs
•
Building a NetSuite-looking user interface in a Suitelet – see UI Builder APIs
•
Setting application navigation – see Application Navigation APIs
•
Working with Date and String objects – see Date APIs
•
Working with currency – see Currency APIs
•
Adding security to your application – see Encryption APIs
•
Working with XML – see XML APIs
•
Working with new or existing files – see File APIs
•
Adding error handling – see Error Handling APIs
•
Configuring your NetSuite account - see Configuration APIs
•
Interacting with the NetSuite Workflow (SuiteFlow) Manager - see SuiteFlow APIs
SuiteScript Developer and Reference Guide
SuiteScript Functions
SuiteScript Functions Overview
•
Working with dashboard portlets - see Portlet APIs
•
Working with NetSuite Analytics - see SuiteAnalytics APIs
•
Changing Currently Logged-in User Credentials - see User Credentials APIs
Record APIs
Functions
nlapiAttachRecord(type, id, type2, id2, attributes)
nlapiCopyRecord(type, id, initializeValues)
nlapiCreateCSVImport( )
nlapiCreateRecord(type, initializeValues)
nlapiDeleteRecord(type, id)
nlapiDetachRecord(type, id, type2, id2, attributes)
nlapiGetNewRecord()
nlapiGetOldRecord()
nlapiGetRecordId()
nlapiGetRecordType()
nlapiLoadRecord(type, id, initializeValues)
nlapiMergeRecord(id, baseType, baseId, altType, altId, fields)
nlapiMergeTemplate(id, baseType, baseId, altType, altId, fields)
nlapiSubmitCSVImport(nlobjCSVImport)
nlapiSubmitRecord(record, doSourcing, ignoreMandatoryFields)
nlapiTransformRecord(type, id, transformType, transformValues)
nlapiPrintRecord(type, id, mode, properties)
Objects
nlobjCSVImport object and all methods
nlobjRecord object and all methods
Subrecord APIs
Functions
nlapiCreateCurrentLineItemSubrecord(sublist, fldname)
nlapiCreateSubrecord(fldname)
nlapiEditCurrentLineItemSubrecord(sublist, fldname)
nlapiEditSubrecord(fldname)
nlapiRemoveCurrentLineItemSubrecord(sublist, fldname)
nlapiRemoveSubrecord(fldname)
SuiteScript Developer and Reference Guide
423
SuiteScript Functions
SuiteScript Functions Overview
nlapiViewCurrentLineItemSubrecord(sublist, fldname)
nlapiViewLineItemSubrecord(sublist, fldname, linenum)
nlapiViewSubrecord(fldname)
Objects
nlobjRecord object and its “subrecord-related” methods
nlobjSubrecord object and all methods
Field APIs
Functions
nlapiDisableField(fldnam, val)
nlapiGetField(fldnam)
nlapiGetFieldText(fldnam)
nlapiGetFieldTexts(fldnam)
nlapiGetFieldValue(fldnam)
nlapiGetFieldValues(fldnam)
nlapiInsertSelectOption(fldnam, value, text, selected)
nlapiLookupField(type, id, fields, text)
nlapiRemoveSelectOption(fldnam, value)
nlapiSetFieldText(fldname, txt, firefieldchanged, synchronous)
nlapiSetFieldTexts (fldname, txts, firefieldchanged, synchronous)
nlapiSetFieldValue(fldnam, value, firefieldchanged, synchronous)
nlapiSetFieldValues (fldnam, value, firefieldchanged, synchronous)
nlapiSubmitField(type, id, fields, values, doSourcing)
Objects
nlobjField object and all methods
nlobjRecord and all methods
nlobjSelectOption and all methods
Sublist APIs
Functions
nlapiCancelLineItem(type)
nlapiCommitLineItem(type)
nlapiDisableLineItemField(type, fldnam, val)
nlapiFindLineItemMatrixValue(type, fldnam, val, column)
nlapiFindLineItemValue(type, fldnam, val)
nlapiGetCurrentLineItemIndex(type)
SuiteScript Developer and Reference Guide
424
SuiteScript Functions
SuiteScript Functions Overview
nlapiGetCurrentLineItemMatrixValue(type, fldnam, column)
nlapiGetCurrentLineItemText(type, fldnam)
nlapiGetCurrentLineItemValue(type, fldnam)
nlapiGetCurrentLineItemValues(type, fldnam)
nlapiGetLineItemCount(type)
nlapiGetLineItemField(type, fldnamm, linenum)
nlapiGetLineItemMatrixField(type, fldnam, linenum, column)
nlapiGetLineItemMatrixValue(type, fldnam, linenum, column)
nlapiGetLineItemText(type, fldnam, linenum)
nlapiGetLineItemValue(type, fldnam, linenum)
nlapiGetLineItemValues(type, fldname, linenum)
nlapiGetMatrixCount(type, fldnam)
nlapiGetMatrixField(type, fldnam, column)
nlapiGetMatrixValue(type, fldnam, column)
nlapiInsertLineItem(type, line)
nlapiInsertLineItemOption(type, fldnam, value, text, selected)
nlapiIsLineItemChanged(type)
nlapiRefreshLineItems(type)
nlapiRemoveLineItem(type, line)
nlapiRemoveLineItemOption(type, fldnam, value)
nlapiSelectLineItem(type, linenum)
nlapiSelectNewLineItem(type)
nlapiSetCurrentLineItemMatrixValue(type, fldnam, column, value, firefieldchanged,
synchronous)
nlapiSetCurrentLineItemText(type, fldnam, text, firefieldchanged, synchronous)
nlapiSetCurrentLineItemValue(type, fldnam, value, firefieldchanged, synchronous)
nlapiSetCurrentLineItemValues(type, fldnam, values, firefieldchanged, synchronous)
nlapiSetLineItemValue(type, fldnam, linenum, value)
nlapiSetMatrixValue(type, fldnam, column, value, firefieldchanged, synchronous)
Objects
nlobjSubList and all methods
Note: Also see Subrecord APIs for a list of functions that can be used to create and access a
subrecord from a sublist field.
Search APIs
Functions
nlapiCreateSearch(type, filters, columns)
nlapiLoadSearch(type, id)
nlapiLookupField(type, id, fields, text)
SuiteScript Developer and Reference Guide
425
SuiteScript Functions
SuiteScript Functions Overview
nlapiSearchDuplicate(type, fields, id)
nlapiSearchGlobal(keywords)
nlapiSearchRecord(type, id, filters, columns)
Objects
nlobjSearch and all methods
nlobjSearchColumn object and all methods
nlobjSearchFilter object and all methods
nlobjSearchResult and all methods
nlobjSearchResultSet and all methods
Scheduling APIs
Functions
nlapiScheduleScript(scriptId, deployId, params)
nlapiSetRecoveryPoint()
nlapiYieldScript()
Execution Context APIs
Functions
nlapiGetContext()
nlapiGetDepartment()
nlapiGetLocation()
nlapiGetRole()
nlapiGetSubsidiary()
nlapiGetUser()
nlapiLogExecution(type, title, details)
Objects
nlobjContext object and all methods
UI Builder APIs
Functions
nlapiCreateAssistant(title, hideHeader)
nlapiCreateForm(title, hideNavbar)
nlapiCreateList(title, hideNavbar)
Objects
SuiteScript Developer and Reference Guide
426
SuiteScript Functions
SuiteScript Functions Overview
nlobjAssistant object and all methods
nlobjAssistantStep object and all methods
nlobjButton object and all methods
nlobjColumn object and all methods
nlobjField object and all methods
nlobjFieldGroup and all methods
nlobjForm object and all methods
nlobjList object and all methods
nlobjPortlet object and all methods
nlobjSubList object and all methods
nlobjTab object and all methods
Application Navigation APIs
Functions
nlapiRequestURL(url, postdata, headers, callback, httpMethod)
nlapiRequestURLWithCredentials(credentials, url, postdata, headers, httpMethod)
nlapiResolveURL(type, identifier, id, displayMode)
nlapiSetRedirectURL(type, identifier, id, editmode, parameters)
Objects
nlobjRequest object and all methods
nlobjResponse object and all methods
Date APIs
Functions
nlapiAddDays(d, days)
nlapiAddMonths(d, months)
nlapiDateToString(d, format)
nlapiStringToDate(str, format)
SuiteScript Developer and Reference Guide
427
SuiteScript Functions
SuiteScript Functions Overview
Currency APIs
Functions
nlapiExchangeRate(sourceCurrency, targetCurrency, effectiveDate)
nlapiFormatCurrency(str)
Encryption APIs
Functions
nlapiEncrypt(s, algorithm, key)
XML APIs
Functions
nlapiEscapeXML(text)
nlapiSelectNode(node, xpath)
nlapiSelectNodes(node, xpath)
nlapiSelectValue(node, xpath)
nlapiSelectValues(node, path)
nlapiStringToXML(text)
nlapiXMLToString(xml)
nlapiXMLToPDF(xmlstring)
File APIs
Functions
nlapiCreateFile(name, type, contents)
nlapiDeleteFile(id)
nlapiLoadFile(id)
nlapiSubmitFile(file)
Objects
nlobjFile object and all methods
SuiteScript Developer and Reference Guide
428
SuiteScript Functions
SuiteScript Functions Overview
Error Handling APIs
Functions
nlapiCreateError(code, details, suppressNotification)
Objects
nlobjError object and all methods
Communication APIs
Functions
nlapiOutboundSSO(id)
nlapiRequestURL(url, postdata, headers, callback, httpMethod)
nlapiSendCampaignEmail(campaigneventid, recipientid)
nlapiSendEmail(author, recipient, subject, body, cc, bcc, records, attachments)
nlapiSendFax(author, recipient, subject, body, records, attachments)
Configuration APIs
Functions
nlapiLoadConfiguration(type)
nlapiSubmitConfiguration(name)
Objects
nlobjConfiguration object and all methods
SuiteFlow APIs
Functions
nlapiInitiateWorkflow(recordtype, id, workflowid)
nlapiTriggerWorkflow(recordtype, id, workflowid, actionid)
Portlet APIs
Functions
nlapiRefreshPortlet()
nlapiResizePortlet()
SuiteScript Developer and Reference Guide
429
SuiteScript Functions
Record APIs
430
SuiteAnalytics APIs
Functions
nlapiCreateReportDefinition()
nlapiCreateReportForm(title)
Objects
nlobjPivotColumn object and all methods
nlobjPivotRow object and all methods
nlobjPivotTable object and all methods
nlobjPivotTableHandle object and all methods
nlobjReportColumn object and all methods
nlobjReportColumnHierarchy object and all methods
nlobjReportDefinition object and all methods
nlobjReportForm object and all methods
nlobjReportRowHierarchy object and all methods
User Credentials APIs
Function
nlapiGetLogin()
Objects
nlobjLogin object and all methods
Record APIs
For an overview of NetSuite records, see Working with Records and Subrecords in SuiteScript.
For information about sourcing, as it pertains to working with records, see Understanding
Sourcing in SuiteScript.
All APIs listed below are in alphabetical order.
•
nlapiAttachRecord(type, id, type2, id2, attributes)
•
nlapiCopyRecord(type, id, initializeValues)
•
nlapiCreateCSVImport( )
•
nlapiCreateRecord(type, initializeValues)
•
nlapiDeleteRecord(type, id)
•
nlapiDetachRecord(type, id, type2, id2, attributes)
SuiteScript Developer and Reference Guide
SuiteScript Functions
Record APIs
•
nlapiGetNewRecord()
•
nlapiGetOldRecord()
•
nlapiGetRecordId()
•
nlapiGetRecordType()
•
nlapiLoadRecord(type, id, initializeValues)
•
nlapiMergeRecord(id, baseType, baseId, altType, altId, fields)
•
nlapiMergeTemplate(id, baseType, baseId, altType, altId, fields)
•
nlapiSubmitCSVImport(nlobjCSVImport)
•
nlapiSubmitRecord(record, doSourcing, ignoreMandatoryFields)
•
nlapiTransformRecord(type, id, transformType, transformValues)
•
nlapiPrintRecord(type, id, mode, properties)
•
nlobjCSVImport
•
nlobjRecord
431
nlapiAttachRecord(type, id, type2, id2, attributes)
Attaches a single record to another record. The following attachment relationships are
supported:
•
Issue attached to Support Case
•
Contact attached to Customer|Partner|Vendor|Lead|Prospect|Project
•
File attached to any transaction, item, activity, custom, or entity record
•
Custom child record attached to supported parent record
•
Entity to a static entity group. Note that if attaching an entity to a static entity group,
you must specify entitygroup as the internal ID for the type2 argument (see below).
This API is supported in client, user event, scheduled, and Suitelet scripts.
Parameters
•
type {string} [required] - The record internal ID name for the record being attached to.
For a list of supported record types and their internal IDs, see SuiteScript Supported
Records in the NetSuite Help Center. Note that if you want to attach a file from the file
cabinet, set type to file.
•
id {string} [required] - The record internalId for the record being attached to, for
example 555 or 78.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Record APIs
432
•
type2 {string} [required] - The record internal ID for the record being attached. Note
that if attaching an entity to a static entity group, the internal ID for the entity group
record type is entitygroup.
•
id2 {string} [required] - The record internalId for the record being attached.
•
attributes {hashtable} [optional] - Name/value pairs containing attributes for the
attachment:
• contact->company record: role (the contact role id used for attaching contact to
customer/vendor/partner)
• customrecord*->parent record: field (the custom field used to link child custom
record to parent record)
Returns
•
void
Since
•
Version 2008.1
Example 1
The following example shows how to attach an Issue record to a Support Case record.
function testAttachment(request, response)
{
//Define variables for nlapiAttachRecord
var type = 'supportcase'; //Define the record type for the record being attached to
var id = 2352; //Define the internal ID for this record
var type2 = 'issue'; //Define record type for the record being attached
var id2 = 372; //Ensure id2 is a valid ID. An error is thrown if id2 is not valid.
var attributes = null;
nlapiAttachRecord(type, id, type2, id2, attributes);
response.write('done');
}
Example 2
The following sample shows how to attach and detach a child custom record from a parent
record. Prior to running this script, a custom record (record id = customrecord15) was created.
Next, a field was added to the record (field id = custrecord_customer). The field was marked as
a select/list field (source list = customer) and the record is parent was set.
Note: This script assumes there is a record with id=1 and a customer with id=79.
var fld = nlapiLookupField('customrecord15', 1, 'custrecord_customer')
nlapiAttachRecord('customrecord15', 1, 'customer', 79, {'field' : 'custrecord_customer'})
var newFld = nlapiLookupField('customrecord15', 1, 'custrecord_customer')
nlapiDetachRecord('customrecord15', 1, 'customer', 79, {'field' : 'custrecord_customer'})
var finalFld = nlapiLookupField('customrecord15', 1, 'custrecord_customer')
SuiteScript Developer and Reference Guide
SuiteScript Functions
Record APIs
433
Example 3
This sample shows how to attach a file object to a record (in this case a JPEG to a Customer
record). Once attached, the file will appear on the Files tab of the Customer record.
Important: Be aware that although the file internal ID is being reference in
nlapiAttachRecord, you cannot yet reference file in other record-level APIs –
such as nlapiCreateRecord, nlapiSubmitRecord, or nlapiLoadRecord. The File
(file) record is not yet supported in this capacity.
var type = 'customer'; // the record type for the record being attached to
var id = 406; // this is the internal ID for the customer
var type2 = 'file'; // the record type for the record being attached
var id2 = 297 ; // the internal ID of an existing jpeg in the file cabinet
var attributes = null;
nlapiAttachRecord(type, id, type2, id2, attributes)
Back to Record APIs | Back to SuiteScript Functions
nlapiCopyRecord(type, id, initializeValues)
Initializes a new record using field data from an existing record. Note that this API simply
creates a new instance of another record. After making changes to the copy, you must submit
the copy (which is considered as a new record) to the database for your changes to be
committed to NetSuite.
This API is supported in client, user event, scheduled, portlet, and Suitelet scripts. See API
Governance for the unit cost associated with this API.
Parameters
•
type {string} [required] - The record internal ID name. For a list of supported record
types and their internal IDs, see SuiteScript Supported Records in the NetSuite Help
Center.
•
id {int} [required] - The internalId for the record. If you are unsure how to find a
record’s internalId, see Showing Record and Field IDs in Your Account.
•
initializeValues {Object} [optional] - Contains an array of name/value pairs of defaults
to be used during record initialization. For a list of record initialization types and the
values they can take, see Record Initialization Defaults in the NetSuite Help Center.
Returns
•
An nlobjRecord object of a copied record
Example
The following example initializes a new partner record from an existing one.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Record APIs
434
var partner = nlapiCopyRecord('partner', 20)
partner.setFieldValue('entityid', 'New Partner')
Back to Record APIs | Back to SuiteScript Functions
nlapiCreateCSVImport( )
Initializes a new record and returns an nlobjCSVImport object. You can then use the methods
available on the returned record object to populate the object with the desired information.
Next, you can pass this object to nlapiSubmitCSVImport(nlobjCSVImport), which
asynchronously imports the data from the returned object into NetSuite.
Note that this API cannot be used to import data that is imported by simple (2-step) assistants
in the UI, because these import types do not support saved import maps. This limitation
applies to budget, single journal entry, single inventory worksheet, project tasks, and Web site
redirects imports.
Warning: This API is only supported for bundle installation scripts, scheduled scripts, and
RESTlets. If you attempt to execute this API in another type of script, an error is
returned.
Parameters
•
None
Returns
•
An nlobjCSVImport object to be passed as a parameter to
nlapiSubmitCSVImport(nlobjCSVImport).
Since
•
Version 2012.2
Examples
This sample uses a script ID to reference the import mapping and raw string for CSV data:
var mappingFileId = "CUSTIMPORTjob1"; //using script id of Saved CSV Import
var primaryFileAsString = "company name,isperson,subsidiary,externalid\ncompanytest001,FALSE,Parent
Company,companytest001";
var job = nlapiCreateCSVImport();
job.setMapping(mappingFileId);
job.setPrimaryFile(primaryFileAsString);
job.setOption("jobName", "job1Import");
//returns the internal id of the new job created in workqueue
var jobId = nlapiSubmitCSVImport(job);
SuiteScript Developer and Reference Guide
SuiteScript Functions
Record APIs
435
This sample uses an internal ID to reference the import map and a CSV file internal ID to
reference CSV data:
var mappingFileId = 2; //using internal id of Saved CSV Import
var primaryFile = nlapiLoadFile(73); //using the internal id of the file stored in the File Cabinet
var job = nlapiCreateCSVImport();
job.setMapping(mappingFileId);
job.setPrimaryFile(primaryFile);
job.setOption("jobName", "job2Import");
//returns the internal id of the new job created in workqueue
var jobId = nlapiSubmitCSVImport(job);
This sample, which is a multi-file import, uses a script ID to reference the import map and CSV
file internal IDs to reference CSV data, and provides a sublist identifier in the
setLinkedFile(file)method:
var mappingFileId = "CUSTIMPORTentityMultiFile";
var job = nlapiCreateCSVImport();
job.setMapping(mappingFileId);
//uploaded to File Cabinet <multifile_entity_primary.csv> with internal Id = 73
job.setPrimaryFile(nlapiLoadFile(73));
//uploaded to File Cabinet <multifile_entity_cust_address.csv> with internal Id = 74
job.setLinkedFile("addressbook", nlapiLoadFile(74));
job.setOption("jobName", "test_ImportMultiFileTransactionRecord-");
var jobId = nlapiSubmitCSVImport(job);
For more details about the methods used in these samples, see nlobjCSVImport.
Back to Record APIs | Back to SuiteScript Functions
nlapiCreateRecord(type, initializeValues)
Initializes a new record and returns an nlobjRecord object containing all the default field data
for that record type. You can then use the methods available on the returned record object to
populate the record with the desired information.
The nlapiCreateRecord function must be followed by the nlapiSubmitRecord(record,
doSourcing, ignoreMandatoryFields) function before the record is actually committed to the
database.
This API is supported in client, user event, scheduled, portlet, and Suitelet scripts. See API
Governance for the unit cost associated with this API.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Record APIs
436
Note: Values for all required fields must be provided or a newly instantiated record
cannot be submitted. See SuiteScript Supported Records in the NetSuite Help
Center for records that support SuiteScript, their fields, and whether the fields are
required for each record type. You can also refer to the NetSuite UI, which displays
all required fields in yellow. There may be additional required fields when custom
forms are used. Also, Note records cannot be created as standalone records. These
records are always associated with another record. Similarly, Message records
require an author and recipient to ensure that they are not created as standalone
records.
Parameters
•
type {string} [required] - The record internal ID name. For a list of supported record
types and their internal IDs, see SuiteScript Supported Records in the NetSuite Help
Center.
•
initializeValues {Object} [optional] - Contains an array of name/value pairs of defaults
to be used during record initialization. For a list of record initialization types and the
values they can take, see Record Initialization Defaults in the NetSuite Help Center.
Returns
•
An nlobjRecord object of a new record
Throws
•
SSS_INVALID_RECORD_TYPE
•
SSS_TYPE_ARG_REQD
Example 1
The following example initializes a new Opportunity record.
var record = nlapiCreateRecord('opportunity')
var defaultstatus = record.getFieldValue('entitystatus')
Example 2
In the next example, the createTaskRecord() function causes a new task record to be created.
This could be tied to an afterSubmit function of a user event and deployed to Opportunity
records so that each time an Opportunity is created, a task is automatically created.
Note: You must use the nlapiSubmitRecord(record, doSourcing, ignoreMandatoryFields)
function in conjunction with nlapiCreateRecord for the new record to be saved to
the database.
function createTaskRecord()
{
var taskTitle = 'Follow up regarding new Opportunity';
var record = nlapiCreateRecord( 'task');
SuiteScript Developer and Reference Guide
SuiteScript Functions
Record APIs
437
record.setFieldValue( 'title', taskTitle);
id = nlapiSubmitRecord(record, true);
}
Example 3
This example shows how to create a Message record, set its fields, and then submit the record.
var message = nlapiCreateRecord('message');
message.setFieldValue('entity', ...)
message.setFieldValue('message', ...)
//... set all the necessary fields
var internalId = nlapiSubmitRecord( message );
Back to Record APIs | Back to SuiteScript Functions
nlapiDeleteRecord(type, id)
Use this API to delete an existing record. This API is supported in client, user event, scheduled,
portlet, and Suitelet scripts. See API Governance for the unit cost associated with this API.
Parameters
•
type {string} [required] - The record internal ID name. For a list of supported record
types and their internal IDs, see SuiteScript Supported Records in the NetSuite Help
Center.
•
id {int} [required] - The internalId for the record
Returns
•
void
Throws
•
SSS_INVALID_RECORD_TYPE
•
SSS_TYPE_ARG_REQD
•
SSS_INVALID_INTERNAL_ID
•
SSS_ID_ARG_REQD
Warning: Use caution when using the nlapiDeleteRecord function in SuiteScript. Records
deleted using nlapiDeleteRecord are permanently deleted from the NetSuite
database.
Example 1
The following example deletes a specific task record in the system.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Record APIs
438
var id = nlapiDeleteRecord('task', 5000);
Example 2
In the next example a resultant record set from a customer saved search is deleted. Once the
search is performed, methods on the nlobjSearchResult object take the desired action. In this
example, the nlobjSearchResult.getRecordType and nlobjSearchResult.getId methods are used
to identify which records to delete.
function executeSavedSearch()
{
var searchresults = nlapiSearchRecord('customer', 57, null, null);
for ( var i = 0; searchresults != null && i < searchresults.length; i++ )
{
var searchresult = searchresults[ i ];
nlapiDeleteRecord(searchresults[i].getRecordType(), searchresults[i].getId();
}
}
Back to Record APIs | Back to SuiteScript Functions
nlapiDetachRecord(type, id, type2, id2, attributes)
Use this API to detache a single record from another record. The following detach relationships
are supported:
•
Issue detached from Support Case
•
Contact detached from Customer|Partner|Vendor|Lead|Prospect|Project
•
File detached from any transaction, item, activity, custom, or entity record
•
Custom child record detached from supported parent record
•
Entity detached from a static entity group. Note that if detaching an entity from a static
entity group, you must specify entitygroup as the internal ID for the type2 argument
(see below).
This API is supported in client, user event, scheduled, portlet, and Suitelet scripts.
Parameters
•
type {string} [required] - The record internal ID name for the record being detached.
For a list of record names, see the column called “Record Internal ID” in SuiteScript
Supported Records.
•
id {int} [required] - The record internalId for the record being detached
SuiteScript Developer and Reference Guide
SuiteScript Functions
Record APIs
439
•
type2 {string} [required] - The record internal ID name for the record being detached
from. Note that if detaching an entity from a static entity group, the internal ID for the
entity group record type is entitygroup.
•
id2 {int} [required] - The record internalId for the record being detached from
•
attributes {hashtable} [optional] - Name/value pairs containing attributes for the
attachment:
• customrecord*->parent record: field (the custom field used to link child custom
record to parent record)
Returns
•
void
Since
•
Version 2008.1
Example 1
The following example shows how to detach an Issue record from a Support Case record.
function testDetach(request, response)
{
//Define variables for nlapiDetachRecord
var type = 'issue'; //Define the record type for the record being detached
var id = 2352; //Define the internal ID for this record
var type2 = 'supportcase'; //Define record type for the record being detached from
var id2 = 372; //Ensure id2 is a valid ID. An error is thrown if id2 is not valid.
var attributes = null;
nlapiDetachRecord(type, id, type2, id2, attributes)
response.write('done');
}
Example 2
The following sample shows how to attach and detach a child custom record from a parent
record. Prior to running this script, a custom record (record id = customrecord15) was created.
Next, a field was added to the record (field id = custrecord_customer). The field was marked as
a select/list field (source list = customer) and the record is parent was set.
Note: This script assumes there is a record with id=1 and a customer with id=79.
var fld = nlapiLookupField('customrecord15', 1, 'custrecord_customer')
nlapiAttachRecord('customrecord15', 1, 'customer', 79, {'field' : 'custrecord_customer'})
var newFld = nlapiLookupField('customrecord15', 1, 'custrecord_customer')
nlapiDetachRecord('customrecord15', 1, 'customer', 79, {'field' : 'custrecord_customer'})
var finalFld = nlapiLookupField('customrecord15', 1, 'custrecord_customer')
SuiteScript Developer and Reference Guide
SuiteScript Functions
Record APIs
440
Back to Record APIs | Back to SuiteScript Functions
nlapiGetNewRecord()
Available in beforeLoad, beforeSubmit, and afterSubmit user event scripts. This API never
reflects any changes set by the system during the submit operation. It only reflects the field and
line item (sublist) values submitted by the user.
Note that you are not allowed to submit the current or previous record returned by
nlapiGetNewRecord(). Also note that only fields that are changed (submitted) will be available
via nlapiGetNewRecord().
Returns
•
An nlobjRecord containing all the values being used for a write operation
Back to Record APIs | Back to SuiteScript Functions
nlapiGetOldRecord()
Available in beforeLoad, beforeSubmit, and afterSubmit user event scripts. You are not allowed
to submit the current or previous record returned by nlapiGetOldRecord().
Returns
•
An nlobjRecord containing all the values for the current record prior to the write
operation
Back to Record APIs | Back to SuiteScript Functions
nlapiGetRecordId()
Use this API to retrieve the internalId of the current record in a user event script. This API is
available in client and user event scripts only.
Returns
•
The integer value of the record whose form the user is currently on, or for the record
that the current user event script is executing on. Note that the value of -1 is returned if
there is no current record or the current record is a new record.
Back to Record APIs | Back to SuiteScript Functions
SuiteScript Developer and Reference Guide
SuiteScript Functions
Record APIs
441
nlapiGetRecordType()
Use this API to retrieve the record type of the current record in a user event script. This API is
available to client and user event scripts only. If there is no current record type, the value of null
will be returned.
Returns
•
The string recordType name for the record whose form the user is currently on, or for
the record that the current User Event script is executing on.
Back to Record APIs | Back to SuiteScript Functions
nlapiLoadRecord(type, id, initializeValues)
Loads an existing record from the system and returns an nlobjRecord object containing all the
field data for that record. You can then extract the desired information from the loaded record
using the methods available on the returned record object. This API is a core API. It is available
in both client and server contexts.
This API is supported in client, user event, scheduled, portlet, and Suitelet scripts. See API
Governance for the unit cost associated with this API.
Important: Only records that support SuiteScript can be loaded using this API. In
NetSuite Help Center, see SuiteScript Supported Records for a list of records
that support SuiteScript. Also be aware that if a particular record instance has
been locked by the Lock Record workflow action, you will be unable to load
the record using the nlapiLoadRecord(...) API.
Note that when using this API, you can:
•
set the type parameter to 'inventoryitem' to load the follwing types of item records:
inventoryitem, lotnumberedinventoryitem, serializedinventoryitem
•
set the type parameter to 'assemblyitem' to load the following types of item records:
assemblyitem, lotnumberedassemblyitem, serializedassemblyitem
•
set the type parameter to 'customer' to load the following types of entity records:
customer, lead, prospect
Parameters
•
type {string} [required] - The record internal ID name. In the NetSuite Help Center, see
SuiteScript Supported Records. Use the values listed in the column “Record Internal
ID”.
•
id {int} [required] - internalId for the record, for example 555 or 78.
•
initializeValues {Object} [optional] - Contains an array of name/value pairs of defaults
to be used during record initialization. For a list of record initialization types and the
values they can take, see Record Initialization Defaults in the NetSuite Help Center.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Record APIs
442
Returns
•
An nlobjRecord object of an existing NetSuite record. This function returns the record
object exactly as the record appears in the system. Therefore, in beforeLoad user event
scripts, if you attempt to change a field and load the record simultaneously, the change
will not take effect.
Throws
•
SSS_INVALID_RECORD_TYPE
•
SSS_TYPE_ARG_REQD
•
SSS_INVALID_INTERNAL_ID
•
SSS_ID_ARG_REQD
Example 1
The following example loads a customer record from the system. Once the record is loaded, the
script uses the nlobjRecord.getFieldValue() method to return the value of the phone field.
Finally, the number of line items on the Address sublist are returned using the
nlobjRecord.getLineItemCount() method.
var record = nlapiLoadRecord('customer', 100)
var phone = record.getFieldValue('phone')
var numberOfAddresses = record.getLineItemCount('addressbook');
Example 2
In the next example, the search described in the section on nlapiSearchRecord(type, id, filters,
columns) is performed, but each search result object is loaded using the nlapiLoadRecord(type,
id, initializeValues) function. Then the getRecordType() and getId() nlobjRecord methods are
used to retrieve specific information about each record.
function executeSearch()
{
var rec = '';
var searchresults = nlapiSearchRecord( 'customer', null, null, null );
for ( var i = 0; i < Math.min( 500, searchresults.length ); i++)
{
var record = nlapiLoadRecord(searchresults[i].getRecordType(),
searchresults[i].getId() );
rec = rec + record.getRecordType() ;
rec = rec + ' -Record ID = ' + record.getId();
}
nlapiSendEmail(312, 312, 'customerRecordLoaded', rec, null);
}
Back to Record APIs | Back to SuiteScript Functions
SuiteScript Developer and Reference Guide
SuiteScript Functions
Record APIs
443
nlapiMergeRecord(id, baseType, baseId, altType, altId, fields)
Performs a mail merge operation and returns an nlobjFile object containing the results. This
API is supported in user event, scheduled, and Suitelet scripts.
Note: There is a 5MB limitation to the size of the file that can be merged using this API.
See API Governance for the unit cost associated with this API.
Important: This API supports the same records types that are supported in NetSuite’s
mail merge feature. Supported record types include NetSuite transactions,
entities, custom records, and support cases. Note that activity type records
such as tasks and events are not currently supported. Also note that
transaction column fields are not supported in NetSuite mail merge and
therefore are not available through nlapiMergeRecord.
Note: With nlapiSendEmail(author, recipient, subject, body, cc, bcc, records, attachments)
you can use NetSuite email templates to construct the body of the email using
nlapiMergeRecord. The nlapiMergeRecord API performs a merge operation using a
NetSuite email template and up to two business records.
Parameters
•
id {int} [required] - The internalId of the email template
•
baseType {string} [required] - The recordType for the primary record used in the
merge
•
baseId {int} [required] - The internalId for the primary record used in the merge
•
altType {string} [optional] - The recordType for the secondary record used in the
merge
•
altId {int} [optional] - The internalId for the secondary record used in the merge
•
fields {hashtable} [optional] - Array of NL tag names to data values (custom namevalue merge fields used for merge operation). Note that tag names must begin with NL.
Returns
•
An nlobjFile object containing the results of the merge operation
Since
•
Version 2008.1
Example
The following sample is a user event script that is deployed on an afterSubmit event. This script
applies to the Customer record type.
function afterSubmit(type)
{
SuiteScript Developer and Reference Guide
SuiteScript Functions
Record APIs
444
var newRec = nlapiGetNewRecord();
var senderInfo = nlapiGetContext();
var mailRec = nlapiMergeRecord(1, 'customer', newRec.getId());
var records = new Object();
records['entity'] = newRec.getId();
nlapiSendEmail(senderInfo.getUser(), newRec.getFieldValue('email'), mailRec.getName(),
mailRec.getValue(), null, null, records);
}
Back to Record APIs | Back to SuiteScript Functions
nlapiMergeTemplate(id, baseType, baseId, altType, altId, fields)
THIS API HAS BEEN DEPRECATED
This API was deprecated in NetSuite version 2008.1, however, it continues to be supported.
This function will not be enhanced in future versions of NetSuite.
In its place, users can use nlapiMergeRecord(id, baseType, baseId, altType, altId, fields), which
performs exactly the same as nlapiMergeTemplate. The only distinction between the two
functions is that nlapiMergeRecord returns a nlobjFile object (instead of a String).
Deprecated Since
•
Version 2008.1
See Also
•
nlapiMergeRecord(id, baseType, baseId, altType, altId, fields)
Back to Record APIs | Back to SuiteScript Functions
nlapiSubmitCSVImport(nlobjCSVImport)
Submits a CSV import job to asynchronously import record data into NetSuite. This API can
be used to:
•
Automate standard record data import for SuiteApp installations, demo environments,
and testing environments.
•
Import data on a schedule using a scheduled script.
•
Build integrated CSV imports with RESTlets.
When the API is executed, the import job is added to the queue. The progress of an import job
can be viewed at Setup > Import/Export > View CSV Import Status. For details, see Checking
CSV Import Status.
Executing this API consumes 100 governance units.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Record APIs
445
Note that this API cannot be used to import data that is imported by simple (2-step) assistants
in the UI, because these import types do not support saved import maps. This limitation
applies to budget, single journal entry, single inventory worksheet, project tasks, and Web site
redirects imports.
Warning: This API is only supported for bundle installation scripts, scheduled scripts, and
RESTlets. If you attempt to execute this API in another type of script, an error is
returned.
Parameters
•
nlobjCSVImport [required] - nlobjCSVImport object with methods to set the
following: saved import map, primary file, linked file(s) (optional), import job name
(optional).
Returns
•
Job ID of the import (which is also the identifier for the CSV response file)
Since
•
Version 2012.2
Throws
This API throws errors resulting from inline validation of CSV file data before the import of
data begins (the same validation that is performed between the mapping step and the save step
in the Import Assistant). Any errors that occur during the import job are recorded in the CSV
response file, just as they are for imports initiated through the Import Assistant.
Examples
This sample uses a script ID to reference the import map and raw string for CSV data:
var mappingFileId = "CUSTIMPORTjob1"; //using script id of Saved CSV Import
var primaryFileAsString = "company name,isperson,subsidiary,externalid\ncompanytest001,FALSE,Parent
Company,companytest001";
var job = nlapiCreateCSVImport();
job.setMapping(mappingFileId);
job.setPrimaryFile(primaryFileAsString);
job.setOption("jobName", "job1Import");
//returns the internal id of the new job created in workqueue
var jobId = nlapiSubmitCSVImport(job);
This sample uses an internal ID to reference the import map and a CSV file internal ID to
reference CSV data:
var mappingFileId = 2; //using internal id of Saved CSV Import
var primaryFile = nlapiLoadFile(73); //using the internal id of the file stored in the File Cabinet
var job = nlapiCreateCSVImport();
SuiteScript Developer and Reference Guide
SuiteScript Functions
Record APIs
446
job.setMapping(mappingFileId);
job.setPrimaryFile(primaryFile);
job.setOption("jobName", "job2Import");
//returns the internal id of the new job created in workqueue
var jobId = nlapiSubmitCSVImport(job);
This sample, which is a multi-file import, uses a script ID to reference the import map and CSV
file internal IDs to reference CSV data, and provides a sublist identifier in the
setLinkedFile(file)method:
var mappingFileId = "CUSTIMPORTentityMultiFile";
var job = nlapiCreateCSVImport();
job.setMapping(mappingFileId);
//uploaded to File Cabinet <multifile_entity_primary.csv> with internal Id = 73
job.setPrimaryFile(nlapiLoadFile(73));
//uploaded to File Cabinet <multifile_entity_cust_address.csv> with internal Id = 74
job.setLinkedFile("addressbook", nlapiLoadFile(74));
job.setOption("jobName", "test_ImportMultiFileTransactionRecord-");
var jobId = nlapiSubmitCSVImport(job);
For more details about the methods used in these samples, see nlobjCSVImport.
Back to Record APIs | Back to SuiteScript Functions
nlapiSubmitRecord(record, doSourcing, ignoreMandatoryFields)
Submits and commits new records or changes applied to an existing record and returns the
internalId for the committed record. The nlapiSumitRecord function can be used in
conjunction with nlapiCreateRecord or nlapiLoadRecord in order to create or modify a record
related to the current one.
This API is supported in client, user event, scheduled, portlet, and Suitelet scripts. See API
Governance for the unit cost associated with this API.
Important: When using nlapiSubmitRecord in a user event script, it is possible that the
related record modified or created by the script is committed to the database
but the actual record initiating the script fails on save. To avoid this scenario,
SuiteScripts that cause actions on records other than the current one should
be set to run afterSubmit.
Parameters
•
record {nlobjRecord} [required] - nlobjRecord object containing the data record
SuiteScript Developer and Reference Guide
SuiteScript Functions
Record APIs
•
447
doSourcing {boolean} [optional] - If not set, this argument defaults to false, which
means that dependent field values are not sourced. If set to true, sources dependent
field information for empty fields. Be aware that doSourcing takes the values of true or
false, not T or F. For more information on sourcing, see Understanding Sourcing in
SuiteScript in the NetSuite Help Center.
Important When working with records in dynamic mode, the value you provide for
doSourcing will be ignored. Field values will be sourced regardless of whether you set
doSourcing to true or to false. For information on dynamic scripting, see Working with
Records in Dynamic Mode.
•
ignoreMandatoryFields {boolean} [optional] - Disables mandatory field validation for
this submit operation. If set to true, ignores all standard and custom fields that were
made mandatory through customization. All fields that were made mandatory
through company preferences are also ignored.
Important: Use the ignoreMandatoryFields argument with caution. This argument
should be used mostly with Scheduled scripts, rather than User Event scripts. This
ensures that UI users do not bypass the business logic enforced through form
customization.
Returns
•
An integer value of the committed record’s internal ID (for example, 555, 21, or 4).
Throws
•
SSS_INVALID_RECORD_OBJ
•
SSS_RECORD_OBJ_REQD
•
SSS_INVALID_SOURCE_ARG
Example 1
The following example creates an estimate with two items.
var record = nlapiCreateRecord('estimate');
record.setFieldValue('entity', 79);
record.setFieldValue('memo', 'Estimate Memo' );
record.setLineItemValue('item', 'item', 1, 21);
record.setLineItemValue('item', 'quantity', 1, 10 );
record.setLineItemValue('item', 'price', 1, 1 );
record.setLineItemValue('item', 'item', 2, 21);
record.setLineItemValue('item', 'quantity', 2, 5 );
record.setLineItemValue('item', 'price', 2, 2 );
var id = nlapiSubmitRecord(record, true);
SuiteScript Developer and Reference Guide
SuiteScript Functions
Record APIs
448
Example 2
Expanding on the Example 2 in nlapiCreateRecord(type, initializeValues), the
createTaskRecord() function now causes a new task record to be created and submitted. This
could be tied to an afterSubmit function of a user event and deployed to Opportunity records
so that each time an Opportunity is created, a task is automatically created.
function createTaskRecord()
{
var taskTitle = 'Follow up regarding new Opportunity';
var record = nlapiCreateRecord( 'task');
record.setFieldValue( 'title', taskTitle);
id = nlapiSubmitRecord(record, true);
}
Understanding Sourcing in SuiteScript
Important: If you are working with a record in dynamic mode, the following information
does not apply. When submitting a record while in dynamic mode, the
doSourcing arguement is ignored. Whether you set doSourcing to true or to
false, all field values will be sourced. For information on dynamic scripting,
see Working with Records in Dynamic Mode.
When submitting a record in non-dynamic mode, you can retain full control over the data that
is written to the system by setting doSourcing to false, or you can accept sourcing values from
NetSuite by setting doSourcing to true. When set to true, fields normally dependent on values
from parent fields are automatically pre-populated.
Some advantages to setting doSourcing to true include:
•
Reduces the number of fields that have to be filled out while retaining data integrity
across fields
•
Ensures that field values reflect what would normally be submitted when using the
entering records via the UI.
Some advantages to setting doSourcing to false include:
•
You retain full control over the data that is written to the system
•
Reduces overhead incurred — with doSourcing set to true, all empty dependent fields
on the record (including supported sublists) must be processed
For example, in the UI when a customer is selected on an opportunity record, the leadsource,
partner, salesrep, and any custom sourced fields are automatically populated.
If creating an opportunity using SuiteScript with doSourcing set to false, the leadsource,
partner, salesrep, and any custom sourced fields not specifically set by the SuiteScript code
SuiteScript Developer and Reference Guide
SuiteScript Functions
Record APIs
449
would be empty. Therefore, doSourcing must be set to true for these fields to automatically
populate with values based on the value of the customer field.
Back to Record APIs | Back to SuiteScript Functions
nlapiTransformRecord(type, id, transformType, transformValues)
Initializes a new record using data from an existing record of a different type and returns an
nlobjRecord. This function can be useful for automated order processing such as creating item
fulfillment transactions and invoices off of orders.
This API is supported in client, user event, scheduled, and Suitelet scripts. See API Governance
for the unit cost associated with this API.
For a list of supported transform types, see Supported Transformation Types.
Parameters
•
type {string} [required] - The record internal ID name. In the NetSuite Help Center, see
SuiteScript Supported Records. The internal ID appears in the column called “Record
Internal ID”.
•
id {int} [required] - The internalId for the record, for example 555 or 78.
•
transformType {string} [required] - The record internal ID name of the record you are
transforming the existing record into
•
transformValues {hashtable} [optional] - An array of field name -> value pairs
containing field defaults used for transformation. Note that you can also specify
whether you want the record transformation to occur in dynamic mode. For details,
see Working with Records in Dynamic Mode.
Important: When doing a sales order to item fulfillment transform on a sales order
that has Multiple Shipping Routes (MSR) enabled, you must specify a shipgroup value.
For example:
var itemFulfillment = nlapiTransformRecord('salesorder', id, 'itemfulfillment', { 'shipgroup' : 5 });
var fulfillmentId = nlapiSubmitRecord(itemFulfillment, true);
If you do not specify a value, the system does not know which items on the order are
being fulfilled. If a shipgroup value is not specified, the value 1 (for the first shipping
group) is defaulted. This means that only the items belonging to the first shipping
group will be fulfilled when the sales order is transformed. For more information, see
Multiple Shipping Routes and SuiteScript in the NetSuite Help Center.
Returns
•
An nlobjRecord object
Throws
•
SSS_INVALID_URL_CATEGORY
SuiteScript Developer and Reference Guide
SuiteScript Functions
Record APIs
•
SSS_CATEGORY_ARG_REQD
•
SSS_INVALID_TASK_ID
•
SSS_TASK_ID_REQD
•
SSS_INVALID_INTERNAL_ID
•
SSS_INVALID_EDITMODE_ARG
450
Example 1
The following example uses nlapiTransformRecord to create an item fulfillment record from an
existing sales order.
var itemfulfillment = nlapiTransformRecord('salesorder', 1500, 'itemfulfillment');
itemfulfillment.setFieldValue('trandate', nlapiDateToString(new Date()) );
Example 2
The next script shows how to create an item receipt from a purchase order.
function transformPurchaseOrder()
{
var fromrecord;
var fromid;
var torecord;
var trecord;
var qty;
fromrecord = 'purchaseorder';
fromid = 26 ; // Transform PO with ID = 26 ;
torecord = 'itemreceipt';
// Transaform a record with given id to a different record type.
// For example - from PO to Item Receipt
// Get the object of the transformed record.
trecord = nlapiTransformRecord(fromrecord, fromid, torecord);
qty = trecord.getLineItemValue('item', 'quantity', 1 );
trecord.setLineItemValue('item', 'quantity', 1, '2' );
var idl = nlapiSubmitRecord(trecord, true);
nlapiSendEmail(-5, -5, 'Transform Email' + 'Original Qty = ' + qty + ' ' + 'Record Created = ' + idl , null);
}
Example 3
This script shows how to create an assembly build record from an assembly item, as well as how
to set the department field before submitting the new record.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Record APIs
451
function transformAssemblyItem()
{
var fromRecord = 'assemblyitem';
var fromId = 328;
var toRecord = 'assemblybuild';
var record = nlapiTransformRecord(fromRecord, fromId, toRecord, {'quantity': '1', 'location': '1'});
record.setFieldValue('department', '1');
var id = nlapiSubmitRecord(record, false);
}
Example 5
The following script shows how to create an assembly build record from an assembly item, as
well as how to set the quantity of the member items.
Important: The following sample references the Components (component) sublist, which
does not yet officially support SuiteScript. This sample is meant for
illustrative purposes only. It is meant only to show how to set the values for
nlapiTransformRecord(type, id, transformType, transformValues).
/* Assembly item name = Computer , Id = 328
2 Member components of Assembly item
Member 1 Name = CPU - Quantity = 2
Member 2 Name = Memory - Quantity = 4
*/
function transformAssemblyItem()
{
var fromRecord = 'assemblyitem';
var fromId = 328; // Id of the assembly item
var toRecord = 'assemblybuild';
var defaultV = new Array();
// Default quantity to build
defaultV.quantity = 1;
// Default location Id if Multi Location Inventory is enabled.
defaultV.location = '3';
var record = nlapiTransformRecord(fromRecord, fromId, toRecord, defaultV);
// Set quantity of member 1 to 4
record.setLineItemValue('component', 'quantity', 1, 4);
// Set quantity of member 2 to 8
record.setLineItemValue('component', 'quantity', 2, 8);
var id = nlapiSubmitRecord(record, false);
}
SuiteScript Developer and Reference Guide
SuiteScript Functions
Record APIs
452
Supported Transformation Types
Certain NetSuite record types cannot be created as standalone records. They are always created
from another record type because of relationships between the record types. The
nlapiTransfromRecord API can be used to create these types of records.
The following table shows the transformations that are supported in NetSuite:
Record Type
Record Name
Transform Type
Transform Name (Target Record)
assemblyitem
Build/Assembly
assemblybuild
Assembly Build
assemblybuild
Assembly Build
assemblyunbuild
Assembly Unbuild
cashsale
Cash Sale
cashrefund
Cash Sale
customer
Customer
cashsale
Cash Sale
customer
Customer
customerpayment
Customer Payment
customer
Customer
estimate
Quote
customer
Customer
invoice
Invoice
customer
Customer
opportunity
Opportunity
customer
Customer
salesorder
Sales Order
employee
Employee
expensereport
Expense Report
employee
Employee
timebill
Time
estimate
Quote
cashsale
Cash Sale
estimate
Quote
invoice
Invoice
estimate
Quote
salesorder
Sales Order
invoice
Invoice
creditmemo
Credit Memo
invoice
Invoice
customerpayment
Customer Payment
invoice
Invoice
returnauthorization
Return Authorization
lead
Lead
opportunity
Opportunity
opportunity
Opportunity
cashsale
Cash Sale
opportunity
Opportunity
estimate
Quote
opportunity
Opportunity
invoice
Invoice
opportunity
Opportunity
salesorder
Sales Order
prospect
Prospect
estimate
Quote
prospect
Prospect
opportunity
Opportunity
prospect
Prospect
salesorder
Sales Order
purchaseorder
Purchase Order
itemreceipt
Item Receipt
purchaseorder
Purchase Order
vendorbill
Vendor Bill
purchaseorder
Purchase Order
vendorreturnauthor
ization
Vendor Return Authorization
returnauthorization
Return
Authorization
cashrefund
Cash Refund
returnauthorization
Return
Authorization
creditmemo
Credit Memo
SuiteScript Developer and Reference Guide
SuiteScript Functions
Record APIs
Record Type
Record Name
Transform Type
Transform Name (Target Record)
returnauthorization
Return
Authorization
itemreceipt
Item Receipt
returnauthorization
Return
Authorization
revenuecommitmen
treversal
Revenue Commitment Reversal
Sales Order
cashsale
Cash Sale
salesorder
453
Note: The return authorization must
be approved and received for this
transform to work.
Note: The Advanced Billing feature
must be enabled for this transform to
work.
salesorder
Sales Order
invoice
Invoice
Note: The Advanced Billing feature
must be enabled for this transform to
work.
salesorder
Sales Order
itemfulfillment
Item Fulfillment
salesorder
Sales Order
returnauthorization
Return Authorization
salesorder
Sales Order
revenuecommitmen
t
Revenue Commitment
transferorder
Transfer Order
itemfulfillment
Item Fulfillment
transferorder
Transfer Order
itemreceipt
Item Receipt
vendor
Vendor
purchaseorder
Purchase Order
vendor
Vendor
vendorbill
Vendor Bill
vendorbill
Vendor Bill
vendorcredit
Vendor Credit
vendorbill
Vendor Bill
vendorpayment
Vendor Payment
vendorbill
Vendor Bill
vendorreturnauthor
ization
Vendor Return Authorization
vendorreturnautho
rization
Vendor Return
Authorization
itemfulfillment
Item Fulfillment
vendorreturnautho
rization
Vendor Return
Authorization
vendorcredit
Vendor Credit
workorder
Work Order
assemblybuild
Assembly Build
Back to Record APIs | Back to SuiteScript Functions
nlapiPrintRecord(type, id, mode, properties)
Returns an nlobjFile object containing the PDF or HTML document. This API is supported in
user event, scheduled, and Suitelet scripts.
Note: There is a 5MB limitation to the size of the file that can be accessed using this API.
There are two primary use cases for nlapiPrintRecord:
SuiteScript Developer and Reference Guide
SuiteScript Functions
Record APIs
1.
454
Send email or fax attachments using either nlapiSendEmail(author, recipient, subject,
body, cc, bcc, records, attachments) or nlapiSendFax(author, recipient, subject, body,
records, attachments). See Example 1 and Example 2.
For example, you can create a PDF or HTML object of a transaction or statment and
then send the object as an attachment. This would be useful when sending out
monthly collections notices for customers with overdue invoices.
2.
Stream PDF/HTML documents to the server (for example, to maintain an archive of
statement/transactions on your server). Example 3.
Important: nlapiPrintRecord is not supported in client scripting. This is a server-sideonly API. Also note that this function does not send transactions or
statements to a printer to be printed. It also does not launch Adobe Acrobat
if the mode specified is PDF.
Parameters
•
type {string} [required] - Print operation type. Can be any of the following:
• TRANSACTION
• STATEMENT
• PACKINGSLIP
• PICKINGTICKET
• BILLOFMATERIAL
•
id {int} [required] - The internal ID of the transaction or statement being printed
•
mode {string} [optional] - The output type: PDF|HTML|DEFAULT. DEFAULT uses the
user/company preference for print output
•
properties {hashtable} [optional] - Name/value pairs used to configure the print
operation.
• TRANSACTION: formnumber
• STATEMENT: openonly (T|F), startdate, statementdate, formnumber
• PACKINGSLIP: formnumber, itemfulfillment
• PICKINGTICKET: formnumber, shipgroup, location
Returns
•
nlobjFile object
Since
•
Version 2008.1
SuiteScript Developer and Reference Guide
SuiteScript Functions
Record APIs
455
Example 1
In the following sample a PDF object is created from a specific transaction. This object is then
sent as an attachment using nlapiSendEmail.
function printTrans()
{
//print the transaction to a PDF file object
var file = nlapiPrintRecord('TRANSACTION', 1799, 'DEFAULT', null);
//send the PDF as an attachment
nlapiSendEmail('-5', 'kwolfe@netsuite.com', 'Incoming Transaction', 'Please see attached transaction', null, null,
null, file);
}
Example 2
In this sample a PDF object is created from a specific statement. This object is then sent as an
attachment using nlapiSendEmail.
function printStatement()
{
//create an array to set the STATEMENT properties
var sdate = new Array();
sdate.startdate = '02/07/2008';
sdate.statementdate = '03/01/2008';
sdate.openonly = 'T';
//print the statement to a PDF file object
var file1 = nlapiPrintRecord('STATEMENT', 87, 'PDF', sdate);
//send the PDF as an attachment
nlapiSendEmail('-5', 'kwolfe@netsuite.com', 'Regular Statement', 'Please see attached statment', null, null, null,
file1);
}
Example 3
This sample shows how to create a PDF of a particular transaction. First the file variable is set
to a PDF file object. This PDF is then returned as an nlobjResponse object. The response object
content type is set to PDF (using the nlobjFile.getType() method). Finally, the the output of the
response object is written to the server.
var file = nlapiPrintRecord('TRANSACTION', 1799, 'PDF', null);
response.setContentType(file.getType());
response.write(file.getValue());
Back to Record APIs | Back to SuiteScript Functions
SuiteScript Developer and Reference Guide
SuiteScript Functions
Subrecord APIs
456
nlobjCSVImport
See nlobjCSVImport - defined in the section on Standard Objects.
Back to Record APIs | Back to SuiteScript Functions
nlobjRecord
See nlobjRecord - defined in the section on Standard Objects.
Back to Record APIs | Back to SuiteScript Functions
Subrecord APIs
For an overview of NetSuite subrecords, see Working with Subrecords in SuiteScript.
The subrecord APIs that contain “LineItem” are for creating and working with subrecords from
a sublist field on the parent record. The APIs that do not have “LineItem” in the name are for
creating and working with subrecords from a body field on the parent record.
Note that most of the functions listed below return an nlobjSubrecord object. After creating or
editing a subrecord, you must save your changes using the nlobjSubrecord.commit() method.
You must then save the subrecord’s parent record using nlapiSubmitRecord(record,
doSourcing, ignoreMandatoryFields). If you do not commit both the subrecord and the parent
record, all changes to the subrecord are lost. For complete details on saving subrecords, see
Saving Subrecords Using SuiteScript.
Important: Subrecords are used in the context of the Advanced Bin / Numbered
Inventory Management feature. Currently, the only supported subrecord in
NetSuite is the Inventory Details subrecord. For scripting examples that show
how to use subrecord APIs in the context of this feature, see Using SuiteScript
with Advanced Bin / Numbered Inventory Management.
All APIs listed below are in alphabetical order.
•
nlapiCreateCurrentLineItemSubrecord(sublist, fldname)
•
nlapiCreateSubrecord(fldname)
•
nlapiEditCurrentLineItemSubrecord(sublist, fldname)
•
nlapiEditSubrecord(fldname)
•
nlapiRemoveCurrentLineItemSubrecord(sublist, fldname)
SuiteScript Developer and Reference Guide
SuiteScript Functions
Subrecord APIs
•
nlapiRemoveSubrecord(fldname)
•
nlapiViewCurrentLineItemSubrecord(sublist, fldname)
•
nlapiViewLineItemSubrecord(sublist, fldname, linenum)
•
nlapiViewSubrecord(fldname)
•
nlobjSubrecord
•
nlobjRecord - all methods with “subrecord” in method signature
457
nlapiCreateCurrentLineItemSubrecord(sublist, fldname)
Returns a nlobjSubrecord object. Use this API to create a subrecord from a sublist field on the
parent record.
Important: This API should only be used in user event scripts on the parent record. Note,
however, this API is not supported in beforeLoad user event scripts. This API
is also not currently supported in form-level or record-level client
SuiteScripts associated with the parent record.
This API is currently used only in the context of the Advanced Bin / Numbered Inventory
feature. For information, see Using SuiteScript with Advanced Bin / Numbered Inventory
Management. Also see Working with Subrecords in SuiteScript for general information on
working with subrecords in NetSuite.
Parameters
•
sublist {string} [required] - The sublist internal ID on the parent record (for example,
use item as the ID for the Items sublist).
•
fldname {string} [required] - The internal ID of the “subrecord field” on the sublist of
the parent record (for example, inventorydetail as the ID for the Inventory Details
sublist field).
Returns
•
nlobjSubrecord
Since
•
Version 2011.2
Example
See Creating a subrecord in the NetSuite Help Center.
Back to Subrecord APIs | Back to SuiteScript Functions
SuiteScript Developer and Reference Guide
SuiteScript Functions
Subrecord APIs
458
nlapiCreateSubrecord(fldname)
Returns a nlobjSubrecord object. Use this API to create a subrecord from a body field on the
parent record.
Important: This API should only be used in user event scripts on the parent record. Note,
however, this API is not supported in beforeLoad user event scripts. This API
is not currently supported in form-level or record-level client SuiteScripts
associated with the parent record.
This API is currently used only in the context of the Advanced Bin / Numbered Inventory
feature. For information, see Using SuiteScript with Advanced Bin / Numbered Inventory
Management. Also see Working with Subrecords in SuiteScript for general information on
working with subrecords in NetSuite.
Parameters
•
fldname {string} [required] - The internal ID of the “subrecord field” on the body of
the parent record (for example, inventorydetail as the ID for the Inventory Details body
field).
Returns
•
nlobjSubrecord
Since
•
Version 2011.2
Example
See Creating a subrecord in the NetSuite Help Center.
Back to Subrecord APIs | Back to SuiteScript Functions
nlapiEditCurrentLineItemSubrecord(sublist, fldname)
Returns a nlobjSubrecord object. Use this API to edit a subrecord from a sublist field on the
parent record.
Important: This API should only be used in user event scripts on the parent record. This
API is not currently supported in form-level or record-level client SuiteScripts
associated with the parent record.
This API is currently used only in the context of the Advanced Bin / Numbered Inventory
feature. For information, see Using SuiteScript with Advanced Bin / Numbered Inventory
Management. Also see Working with Subrecords in SuiteScript for general information on
working with subrecords in NetSuite.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Subrecord APIs
459
Parameters
•
sublist {string} [required] - The sublist internal ID on the parent record (for example,
use item as the ID for the Items sublist).
•
fldname {string} [required] - The internal ID of the “subrecord field” on the sublist of
the parent record (for example, inventorydetail as the ID for the Inventory Details
sublist field).
Returns
•
nlobjSubrecord
Since
•
Version 2011.2
Example
See Editing a subrecord in the NetSuite Help Center.
Back to Subrecord APIs | Back to SuiteScript Functions
nlapiEditSubrecord(fldname)
Returns a nlobjSubrecord object. Use this API to edit a subrecord from a body field on the
parent record.
Important: This API should only be used in user event scripts on the parent record. This
API is not currently supported in form-level or record-level client SuiteScripts
associated with the parent record.
This API is currently used only in the context of the Advanced Bin / Numbered Inventory
feature. For information, see Using SuiteScript with Advanced Bin / Numbered Inventory
Management. Also see Working with Subrecords in SuiteScript for general information on
working with subrecords in NetSuite.
Parameters
•
fldname {string} [required] - The internal ID of the “subrecord field” on the body of
the parent record (for example, inventorydetail as the ID for the Inventory Details body
field).
Returns
•
nlobjSubrecord
Since
•
Version 2011.2
Example
See Editing a subrecord in the NetSuite Help Center.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Subrecord APIs
460
Back to Subrecord APIs | Back to SuiteScript Functions
nlapiRemoveCurrentLineItemSubrecord(sublist, fldname)
Returns a nlobjSubrecord object. Use this API to remove a subrecord from a sublist field on the
parent record.
This API is currently used only in the context of the Advanced Bin / Numbered Inventory
feature. For information, see Using SuiteScript with Advanced Bin / Numbered Inventory
Management. Also see Working with Subrecords in SuiteScript for general information on
working with subrecords in NetSuite.
Parameters
•
sublist {string} [required] - The sublist internal ID on the parent record (for example,
use item as the ID for the Items sublist).
•
fldname {string} [required] - The internal ID of the “subrecord field” on the sublist of
the parent record (for example, inventorydetail as the ID for the Inventory Details
sublist field).
Returns
•
void
Since
•
Version 2011.2
Back to Subrecord APIs | Back to SuiteScript Functions
nlapiRemoveSubrecord(fldname)
Returns a nlobjSubrecord object. Use this API to remove a subrecord from a body field on the
parent record.
This API is currently used only in the context of the Advanced Bin / Numbered Inventory
feature. For information, see Using SuiteScript with Advanced Bin / Numbered Inventory
Management. Also see Working with Subrecords in SuiteScript for general information on
working with subrecords in NetSuite.
Parameters
•
fldname {string} [required] - The internal ID of the “subrecord field” on the body of
the parent record (for example, inventorydetail as the ID for the Inventory Details body
field).
Returns
•
void
SuiteScript Developer and Reference Guide
SuiteScript Functions
Subrecord APIs
461
Since
•
Version 2011.2
Back to Subrecord APIs | Back to SuiteScript Functions
nlapiViewCurrentLineItemSubrecord(sublist, fldname)
Returns a nlobjSubrecord object. Use this API to view a subrecord from a sublist field on the
parent record. Calling this API analogous to doing a “get” on a subrecord, however, the
nlobjSubrecord object returned is in read-only mode. Therefore, an error is thrown if you
attempt to edit a subrecord returned by this API.
You can call this API when you want your script to read the nlobjSubrecord object of the
current sublist line you are on. After you get the nlobjSubrecord object, you can use regular
record API to access its values.
This API is currently used only in the context of the Advanced Bin / Numbered Inventory
feature. For information, see Using SuiteScript with Advanced Bin / Numbered Inventory
Management. Also see Working with Subrecords in SuiteScript for general information on
working with subrecords in NetSuite.
Parameters
•
sublist {string} [required] - The sublist internal ID on the parent record (for example,
use item as the ID for the Items sublist).
•
fldname {string} [required] - The internal ID of the “subrecord field” on the sublist of
the parent record (for example, inventorydetail as the ID for the Inventory Details
sublist field).
Returns
•
nlobjSubrecord
Since
•
Version 2011.2
Back to Subrecord APIs | Back to SuiteScript Functions
nlapiViewLineItemSubrecord(sublist, fldname, linenum)
Returns a nlobjSubrecord object. Use this API to view a subrecord from a sublist field on the
parent record. Calling this API analogous to doing a “get” on a subrecord, however, the
nlobjSubrecord object returned is in read-only mode. Therefore, an error is thrown if you
attempt to edit a subrecord returned by this function.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Subrecord APIs
462
You can call this API when you want to read the value of a line you are not currently on (or
have not selected). For example, if you are editing line 2 as your current line, you can call
nlapiViewLineItemSubrecord on line 1 to get the value of line 1.
This API is currently used only in the context of the Advanced Bin / Numbered Inventory
feature. For information, see Using SuiteScript with Advanced Bin / Numbered Inventory
Management. Also see Working with Subrecords in SuiteScript for general information on
working with subrecords in NetSuite.
Parameters
•
sublist {string} [required] - The sublist internal ID on the parent record (for example,
use item as the ID for the Items sublist).
•
fldname {string} [required] - The internal ID of the “subrecord field” on the sublist of
the parent record (for example, inventorydetail as the ID for the Inventory Details
sublist field).
•
linenum {int} [required] - The line number for the sublist field. Note the first line
number on a sublist is 1 (not 0).
Returns
•
nlobjSubrecord
Since
•
Version 2011.2
Back to Subrecord APIs | Back to SuiteScript Functions
nlapiViewSubrecord(fldname)
Returns a nlobjSubrecord object. Use this API to view a subrecord from a body field on the
parent record. Calling this API analogous to doing a “get” on a subrecord, however, the
nlobjSubrecord object returned is in read-only mode. Therefore, an error is thrown if you
attempt to edit a subrecord returned by this function.
This API is currently used only in the context of the Advanced Bin / Numbered Inventory
feature. For information, see Using SuiteScript with Advanced Bin / Numbered Inventory
Management. Also see Working with Subrecords in SuiteScript for general information on
working with subrecords in NetSuite.
Parameters
•
fldname {string} [required] - The internal ID of the “subrecord field” on the body of
the parent record (for example, inventorydetail as the ID for the Inventory Details body
field).
Returns
•
nlobjSubrecord
SuiteScript Developer and Reference Guide
SuiteScript Functions
Field APIs
463
Since
•
Version 2011.2
Back to Subrecord APIs | Back to SuiteScript Functions
nlobjSubrecord
See nlobjSubrecord - defined in the section on Standard Objects.
Back to Subrecord APIs | Back to SuiteScript Functions
nlobjRecord
See nlobjRecord - defined in the section on Standard Objects. If you have used SuiteScript to
load the parent record, you will use the “subrecord related” methods on nlobjRecord to create
and access a subrecord.
Back to Subrecord APIs | Back to SuiteScript Functions
Field APIs
For an overview of NetSuite fields, see Working with Fields.
All APIs listed below are in alphabetical order.
•
nlapiDisableField(fldnam, val)
•
nlapiGetField(fldnam)
•
nlapiGetFieldText(fldnam)
•
nlapiGetFieldTexts(fldnam)
•
nlapiGetFieldValue(fldnam)
•
nlapiGetFieldValues(fldnam)
•
nlapiInsertSelectOption(fldnam, value, text, selected)
•
nlapiLookupField(type, id, fields, text)
•
nlapiRemoveSelectOption(fldnam, value)
•
nlapiSetFieldText(fldname, txt, firefieldchanged, synchronous)
•
nlapiSetFieldTexts (fldname, txts, firefieldchanged, synchronous)
•
nlapiSetFieldValue(fldnam, value, firefieldchanged, synchronous)
SuiteScript Developer and Reference Guide
SuiteScript Functions
Field APIs
•
nlapiSetFieldValues (fldnam, value, firefieldchanged, synchronous)
•
nlapiSubmitField(type, id, fields, values, doSourcing)
•
nlobjField
464
nlapiDisableField(fldnam, val)
Sets the given field to disabled or enabled based on the value (true or false). This API is
supported in client scripts only.
Parameters
•
fldnam {string} [required] - The internal ID name of the field to enable/disable
•
val {boolean} [required] - If set to true the field is disabled. If set to false it is enabled.
Important: The values for this parameter can be true or false, not T or F.
Returns
•
void
Back to Field APIs | Back to SuiteScript Functions
nlapiGetField(fldnam)
Use this function to obtain body field metadata. Calling this function instantiates the
nlobjField object, which then allows you to use the methods available to nlobjField to get field
metadata.
This API is supported in client and user event scripts only. Note, however, when nlapiGetField
is used in client scripts, the field object returned is read-only. The means that you can use
nlobjField getter methods in client scripts (to obtain metadata about the field), but you cannot
use nlobjField setter methods to set field properties.
Note: To obtain metadata for sublist fields, use nlapiGetLineItemField(type, fldnamm,
linenum).
Parameters
•
fldnam {string} [required] - The internal ID name of the field being set
Returns
•
Returns an nlobjField object representing this field
Since
•
Version 2009.1
SuiteScript Developer and Reference Guide
SuiteScript Functions
Field APIs
465
Example
The following script is attached to a Sales Order. The nlapiGetField API returns a nlobjField
object. This script then uses the field object methods getType() and getLabel() to return the
field’s type and UI label.
function clientScript(type)
{
var field = nlapiGetField('memo'); // specifiy the internalId of the Memo field
alert(field.getType()); // returns text as the field type
alert(field.getLabel()); // returns Memo as the field UI label
}
Back to Field APIs | Back to SuiteScript Functions
nlapiGetFieldText(fldnam)
Use this API to get the text value (rather than the internal ID value) of a field. This API is
available in client and user event scripts only.
Parameters
•
fldnam {string} [required] - The internal ID name of the field being set
Returns
•
The string UI display name for a select field corresponding to the current selection
Example
The following client script reads the text value of the Department field. If the Department field
contains no value when the page loads, an alert is thrown telling users to select the Service
department (one of the text values in the Department dropdown field). If the page loads and
the department field defaults to Sales, an alert is thrown telling users to select the Service
department instead.
function pageInit_getFieldTextTest() {
var departId = nlapiGetFieldText('department');
if (departId == '') {
alert('Please specify the Service department');
}
if (departId == 'Sales') {
alert('Please select the Service department');
}
}
SuiteScript Developer and Reference Guide
SuiteScript Functions
Field APIs
466
Important: nlapiGetFieldText cannot be used on hidden fields or non select fields.
Back to Field APIs | Back to SuiteScript Functions
nlapiGetFieldTexts(fldnam)
Returns the display names for a multiselect field corresponding to the current selection. This
API is available in client and user event scripts only.
Parameters
•
fldnam {string} [required] - The name of the field whose display values are returned
Returns
•
The display names for a multiselect field as an Array.
Since
•
Version 2009.1
Back to Field APIs | Back to SuiteScript Functions
nlapiGetFieldValue(fldnam)
Use this function to get the internal ID of a field. For example, if the customer Abe Simpson
appears in a field, this function will return 87, which represents the internal ID value of the Abe
Simpson customer record. Note that if you are getting the value of an inline checkbox, the
return value will be F if the field is unset.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Field APIs
467
This API is available in client and user event scripts only.
Also be aware that this API is not supported during delete events. Calling
nlapiGetFieldValue(...) on a record you are attempting to delete will return a user error.
Also note that if you are trying to return an array of values from a multiselect field, it is
recommended that you use the nlapiGetFieldValues(fldnam) API.
Finally, NetSuite recommends that you read the topic Getting Field Values in SuiteScript, which
addresses the rare instances in which the value returned by this API is inconsistent.
Parameters
•
fldnam {string} [required] - The internal ID name of the field.
Returns
•
The string value of a field on the current record, or returns null if the field does not
exist on the record or the field is restricted.
Important: If you choose to use nlapiGetFieldValue(fldnam) to return values from a
multiselect field (rather than use the nlapiGetFieldValues(fldnam) API), you
must delimit multiselect values using CHR(5) or the ANSI control character
with code 5.
For example:
function stringToArray (str)
{
//Use ChrCode 5 as a separator
var strChar5 = String.fromCharCode(5);
//Use the Split method to create an array,
//where Chrcode 5 is the separator/delimiter
var multiSelectStringArray = str.split(strChar5);
return multiSelectStringArray;
}
function displayResult ()
{
var str = stringToArray(nlapiGetFieldValue('custentity8'));
alert (str);
}
Back to Field APIs | Back to SuiteScript Functions
nlapiGetFieldValues(fldnam)
Use this function to get an array of internal ID values for a multiselect field.
This API is available in client and user event scripts only.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Field APIs
468
Parameters
•
fldnam {string} [required] - The internal ID of the field. For a list of fields that are
supported in SuiteScript and their internal IDs, see the SuiteScript Reference Guide.
Returns
•
The values of a multiselect field as an Array on the current record. Returns null if the
field does not exist on the record or the field is restricted.
Since
•
Version 2009.1
Back to Field APIs | Back to SuiteScript Functions
nlapiInsertSelectOption(fldnam, value, text, selected)
Adds a select option to a select/multiselect field added via script. Note that this API can only be
used on select/multiselect fields that are added via the UI Objects API (for example, in Suitelets
or beforeLoad user events scripts).
Parameters
•
fldnam {string} [required] - The internalId of the scripted field
•
value {string | int} [required] - A unique value for the select option. Note that the
datatype for this argument will vary depending on the value that is set. For example,
you may assign numerical values such as 1, 2, 3 or string values such as option1,
option2, option3.
•
text {string} [required] - The display name of the select option
•
selected {boolean} [optional] - If not set, this argument defaults to false. If set to true,
the select option becomes the default option. Important: The values for this parameter
can be true or false, not T or F.
Returns
•
void
Back to Field APIs | Back to SuiteScript Functions
nlapiLookupField(type, id, fields, text)
Performs a search for one or more body fields on a record. This function supports joined-field
lookups. Note that the notation for joined fields is: join_id.field_name
Note: Long text fields are truncated at 4000 characters in search/lookup operations.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Field APIs
469
See API Governance for the unit cost associated with this API. This API is available in client,
user event, scheduled, portlet, and Suitelet scripts.
Parameters
•
type {string} [required] - The record internal ID name. In the NetSuite Help Center, see
SuiteScript Supported Records. Record IDs are listed in the “Record Internal ID”
column.
•
id {int} [required] - The internalId for the record, for example 777 or 87.
•
fields {string | string[]} [required] - Sets an array of column/field names to look up, or a
single column/field name. The fields parameter can also be set to reference joined
fields (see the third code sample).
•
text {boolean} [optional] - If not set, this argument defaults to false and the internal ID
of the drop-down field is returned. If set to true, this argument returns the UI display
name for this field or fields (valid only for SELECT|IMAGE|DOCUMENT fields).
Returns
•
{string | hashtable} - A single value (or text) or an associative Array of field name ->
value (or text) pairs depending on the field’s argument.
Example 1
The following example is executed from an Opportunity afterSubmit User Event script and
returns salesrep detail information.
var record = nlapiGetNewRecord();
var salesrep = record.getFieldValue('salesrep')
var salesrep_email = nlapiLookupField('employee', salesrep, 'email');
var salesrep_supervisor = nlapiLookupField('employee', salesrep, 'supervisor', true);
Example 2
The following example shows how to use the nlapiLookupField function to return an array of
field names. In this example, the email, phone, and name fields are returned from a Customer
record.
var fields = ['email', 'phone', 'entityid']
var columns = nlapiLookupField('customer', customer_id, fields);
var email = columns.email
var phone = columns.phone
var name = columns.entityid
Example 3
The following example returns the partner phone number for a customer specified by the
customer recordId. In this scenario, using a joined field lookup eliminates having to perform
two different nlapiLookupField calls (one for customer.partner and another for partner.phone)
to obtain the same information.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Field APIs
470
nlapiLookupField('customer', customer_id, 'partner.phone')
Back to Field APIs | Back to SuiteScript Functions
nlapiRemoveSelectOption(fldnam, value)
Removes a single select option from a select or multiselect field added via script. Note that this
API call can only be used on select/multiselect fields that are added via the UI Objects API (for
example on Suitelets or beforeLoad user event scripts).
Parameters
•
fldnam {string} - The name of the scripted field
•
value {string} - The value of the select option to be removed or null to delete all the
options
Returns
•
void
Back to Field APIs | Back to SuiteScript Functions
nlapiSetFieldText(fldname, txt, firefieldchanged, synchronous)
Sets the value of a select field on the current record using the UI display name. This function is
available in client and user event scripts only.
Parameters
•
fldname {string} [required] - The name of the field being set
•
txt {string} [required] - The display name associated with the value that the field is
being set to
•
firefieldchanged {boolean} [optional] - If true, then the fieldchange script for that field
is executed. If no value is provided, this argument defaults to true. (Available in Client
SuiteScript only). See Using the Fire Field Changed Parameter for more information.
Note: The firefieldchanged parameter takes the values of true or false, not T or F.
•
synchronous {boolean} [optional] - This parameter is relevant for client SuiteScripts
only. In server scripts (such as user event scripts), this parameter will always execute as
true.
In client scripts, if you do not set the value of synchronous, the default value is false,
and the API executes asynchronously. If set to true, this API executes synchronously,
which ensures a predictable script execution. Setting to true forces your client script to
wait on any specified sourcing before continuing with the rest of the script.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Field APIs
471
Note: In client scripts, the synchronous parameter takes the values of true or false, not T
or F.
Returns
•
void
Back to Field APIs | Back to SuiteScript Functions
nlapiSetFieldTexts (fldname, txts, firefieldchanged, synchronous)
Sets the values of a multi-select field on the current record using the UI display names. This
function is available in client and user event scripts only.
Parameters
•
fldname {string} [required] - The name of the field being set
•
txts {string[]} [required] - The display names associated with the values that the field is
being set to
•
firefieldchanged {boolean} [optional] - If true, then the fieldchange script for that field
is executed. If no value is provided, this argument defaults to true. (Available in Client
SuiteScript only). See Using the Fire Field Changed Parameter for more information.
Note: The firefieldchanged parameter takes the values of true or false, not T or F.
•
synchronous {boolean} [optional] - This parameter is relevant for client SuiteScripts
only. In server scripts (such as user event scripts), this parameter will always execute as
true.
In client scripts, if you do not set the value of synchronous, the default value is false,
and the API executes asynchronously. If set to true, this API executes synchronously,
which ensures a predictable script execution. Setting to true forces your client script to
wait on any specified sourcing before continuing with the rest of the script.
Note: In client scripts, the synchronous parameter takes the values of true or false, not T
or F.
Returns
•
void
Since
•
2009.1
Back to Field APIs | Back to SuiteScript Functions
SuiteScript Developer and Reference Guide
SuiteScript Functions
Field APIs
472
nlapiSetFieldValue(fldnam, value, firefieldchanged, synchronous)
Sets the value of a given body field. This API can be used in user event beforeLoad scripts to
initialize field on new records or non-stored fields. (Non-stored fields are those that have the
Store Value preference unchecked on the custom field page.)
For client-side scripting, this API can be triggered by a PageInit client event trigger.
This API is available in client and user event scripts only.
Parameters
•
fldnam {string} [required] - The internal ID name of the field being set
•
value {string} [required] - The value the field is being set to. Note: Check box fields
take the values of T or F, not true or false.
•
firefieldchanged {boolean} [optional] - If true, then the fieldchange script for that field
is executed. If no value is provided, this argument defaults to true. (Available in Client
SuiteScript only). See Using the Fire Field Changed Parameter for more information.
Note: The firefieldchanged parameter takes the values of true or false, not T or F.
•
synchronous {boolean} [optional] - This parameter is relevant for client SuiteScripts
only. In server scripts (such as user event scripts), this parameter will always execute as
true.
In client scripts, if you do not set the value of synchronous, the default value is false,
and the API executes asynchronously. If set to true, this API executes synchronously,
which ensures a predictable script execution. Setting to true forces your client script to
wait on any specified sourcing before continuing with the rest of the script.
Note: In client scripts, the synchronous parameter takes the values of true or false, not T
or F.
Returns
•
void
Example
This sample shows the relationship between setting the value for a parent field and the sourcing
that occurs synchronously for a child field.
In this example the value for the Customer (entity) field gets set to a specific customer when a
Sales Order first loads. Once the value is set for entity, the value of the Sales Rep (salesrep) field
synchronously sources, and an alert is thrown to identify the Sales Rep. If the value of the
synchronous parameter had not been set to true for nlapiSetFieldValue, there is a possibility that
the alert would be thrown before it included the sales rep ID. With synchronous set to true, the
alert cannot be thrown until the salesrep field data has been correctly sourced from the entity
field.
//Set this script to run on a PageInit (page load) client event trigger
function setCustomer()
SuiteScript Developer and Reference Guide
SuiteScript Functions
Field APIs
473
{
nlapiSetFieldValue('entity', 87, null, true);
}
//Set this script to run on a FieldChanged client trigger. The Sales Rep
//(salesrep) field sources its data based on the value of the entity field.
function setSalesRep(type, fld)
{
if (fld =='entity')
{
var val = nlapiGetFieldValue('salesrep');
alert('sales rep is ' + val);
}
}
Back to Field APIs | Back to SuiteScript Functions
nlapiSetFieldValues (fldnam, value, firefieldchanged, synchronous)
Sets the value of a multiselect body field on a current record. This API can be used for user
event beforeLoad scripts to initialize fields on new records or non-stored fields. (Non-stored
fields are those that have the Store Value preference unchecked on the custom field page.
For client-side scripting, this API can be triggered by a PageInit client event trigger.
This API is available in client and user event scripts only.
Parameters
•
fldnam {string} [required] - The internal ID name of the field being set
•
value {string} [required] - The value the field is being set to (Array).
•
firefieldchanged {boolean} [optional] - If true, then the fieldchange script for that field
is executed. If no value is provided, this argument defaults to true. (Important: This
parameter is available in client scripts only). See Using the Fire Field Changed
Parameter for more information.
Note: The firefieldchanged parameter takes the values of true or false, not T or F.
•
synchronous {boolean} [optional] - This parameter is relevant for client SuiteScripts
only. In server scripts (such as user event scripts), this parameter will always execute as
true.
In client scripts, if you do not set the value of synchronous, the default value is false,
and the API executes asynchronously. If set to true, this API executes synchronously,
which ensures a predictable script execution. Setting to true forces your client script to
wait on any specified sourcing before continuing with the rest of the script.
Note: In client scripts, the synchronous parameter takes the values of true or false, not T
or F.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Field APIs
474
Returns
•
void
Since
•
2009.1
Example
var values = new Array() // define a new Array and set customers
values[0] ='80'; // 80 references the internal ID of first customer, Abe Simpson
values[1] = '81'; // 81 references the internal ID of the second customer, Abe Lincoln
// set values for the multiselect field called Customers Multiselect Field
nlapiSetFieldValues('custbody23', values);
Back to Field APIs | Back to SuiteScript Functions
nlapiSubmitField(type, id, fields, values, doSourcing)
Updates one or more body fields or custom fields on a record. This function can be used on any
record that supports inline editing and on any body field or custom field that supports inline
editing. Note that this function cannot be used to update sublist “line item” fields.
The nlapiSubmitField(...) function is a companion function to nlapiLookupField(type, id,
fields, text).
nlapiSubmitField(...) is available in client, user event, scheduled, portlet, and Suitelet scripts.
See API Governance for the unit cost associated with this API. Note that the metering for this
API is on a per-call basis, not per updated line. For example you can update five fields with one
call to nlapiSubmitField, and the entire operation will cost 10 units (if the API is executing on a
standard transaction record).
Important: In the NetSuite UI, users cannot set fields that are not inline editable.
SuiteScript, however, does let you set non inline editable fields using
nlapiSubmitField, but this is NOT the intended use for this API. See
Consequences of Using nlapiSubmitField on Non Inline Editable Fields to
learn about the increased governance cost of using this API on non inline
editable fields.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Field APIs
475
Parameters
•
type {string} [required] - The record internal ID name of the record you are updating.
•
id {int} [required] - The internalId for the record, for example 777 or 87
•
fields {string | string[]} [required] - An Array of field names being updated -or- a single
field name
•
values {string | string[]} [required] - An Array of field values being updated -or- a
single field value
•
doSourcing {boolean} [optional] - If not set, this argument defaults to false and field
sourcing does not occur. If set to true, sources in dependent field information for
empty fields. Note: doSourcing takes the values of true or false, not T or F.
Returns
•
void
Example 1
The following example inactivates a set of custom records returned by a saved search. Note that
the Inactive field on the Custom Record definition page is check box. In SuiteScript, check
boxes always take the value or T or F, not true or false.
var records = nlapiSearchRecord('customrecord_oldrecords', 'customsearch_records_to_inactivate');
for ( var i = 0; i < records.length; i++ ) {
nlapiSubmitField(records[i].getRecordType(), records[i].getId(), 'isinactive', 'T');
}
Example 2
This sample shows nlapiSubmitField in the context of a Suitelet.
function updateFields(request, response) {
//item fulfillment
nlapiSubmitField('itemfulfillment', 55, 'memo', 'Memo for item fulfillment', true);
//customer
nlapiSubmitField('customer', 87, 'comments', 'Enter custom memo here', true);
}
Back to Field APIs | Back to SuiteScript Functions
nlobjField
See nlobjField - defined in the section on UI Objects.
Back to Field APIs | Back to SuiteScript Functions
SuiteScript Developer and Reference Guide
SuiteScript Functions
Sublist APIs
Sublist APIs
For an overview of NetSuite sublists, see Working with Subtabs and Sublists.
All APIs listed below are in alphabetical order.
•
nlapiCancelLineItem(type)
•
nlapiCommitLineItem(type)
•
nlapiDisableLineItemField(type, fldnam, val)
•
nlapiFindLineItemMatrixValue(type, fldnam, val, column)
•
nlapiFindLineItemValue(type, fldnam, val)
•
nlapiGetCurrentLineItemIndex(type)
•
nlapiGetCurrentLineItemMatrixValue(type, fldnam, column)
•
nlapiGetCurrentLineItemText(type, fldnam)
•
nlapiGetCurrentLineItemValue(type, fldnam)
•
nlapiGetLineItemCount(type)
•
nlapiGetLineItemField(type, fldnamm, linenum)
•
nlapiGetLineItemMatrixField(type, fldnam, linenum, column)
•
nlapiGetLineItemMatrixValue(type, fldnam, linenum, column)
•
nlapiGetLineItemText(type, fldnam, linenum)
•
nlapiGetLineItemValue(type, fldnam, linenum)
•
nlapiGetMatrixCount(type, fldnam)
•
nlapiGetMatrixField(type, fldnam, column)
•
nlapiGetMatrixValue(type, fldnam, column)
•
nlapiInsertLineItem(type, line)
•
nlapiInsertLineItemOption(type, fldnam, value, text, selected)
•
nlapiIsLineItemChanged(type)
•
nlapiRefreshLineItems(type)
•
nlapiRemoveLineItem(type, line)
•
nlapiRemoveLineItemOption(type, fldnam, value)
•
nlapiSelectLineItem(type, linenum)
•
nlapiSelectNewLineItem(type)
SuiteScript Developer and Reference Guide
476
SuiteScript Functions
Sublist APIs
477
•
nlapiSetCurrentLineItemMatrixValue(type, fldnam, column, value, firefieldchanged,
synchronous)
•
nlapiSetCurrentLineItemText(type, fldnam, text, firefieldchanged, synchronous)
•
nlapiSetCurrentLineItemValue(type, fldnam, value, firefieldchanged, synchronous)
•
nlapiSetCurrentLineItemValues(type, fldnam, values, firefieldchanged, synchronous)
•
nlapiSetLineItemValue(type, fldnam, linenum, value)
•
nlapiSetMatrixValue(type, fldnam, column, value, firefieldchanged, synchronous)
•
nlobjSubList
nlapiCancelLineItem(type)
Cancels any uncommited changes to the current line of a sublist
Parameters
•
type {string} [required] - The sublist internal ID (for example, use addressbook as the
ID for the Address sublist). In the NetSuite Help Center, see Scriptable Sublists for a list
of sublists that support SuiteScript, sublist internal IDs, and sublist field IDs.
Returns
•
void
Back to Sublist APIs | Back to SuiteScript Functions
nlapiCommitLineItem(type)
Saves/commits the changes to the current line in a sublist. This is the equivalent of clicking
Done for a line item in the UI.
Parameters
•
type {string} [required] - The sublist internal ID (for example, use addressbook as the
ID for the Address sublist). In the NetSuite Help Center, see Scriptable Sublists for a list
of sublists that support SuiteScript, sublist internal IDs, and sublist field IDs.
•
Returns
•
void
Back to Sublist APIs | Back to SuiteScript Functions
SuiteScript Developer and Reference Guide
SuiteScript Functions
Sublist APIs
478
nlapiDisableLineItemField(type, fldnam, val)
Sets the given line item field of a sublist to disabled or enabled based on the value (true or
false).
Parameters
•
type {string} [required] - The sublist internal ID (for example, use addressbook as the
ID for the Address sublist). In the NetSuite Help Center, see Scriptable Sublists for a list
of sublists that support SuiteScript, sublist internal IDs, and sublist field IDs.
•
fldnam {string} [required] - The name of the line item field to enable/disable
•
val {boolean} [required] - If set to true the field is disabled. If set to false it is enabled.
Important: The values for this parameter can be true or false, not T or F.
Returns
•
void
Back to Sublist APIs | Back to SuiteScript Functions
nlapiFindLineItemMatrixValue(type, fldnam, val, column)
This API returns the line number of a particular price in a given column. If the value is present
on multiple lines, it will return the line item of the first line that contains the value. This API is
supported in client and user event scripts. Use this API on a matrix sublists only.
Note: Currently the Pricing sublist and Demand Plan Detail sublist are the only matrix
sublist types that support SuiteScript. For details, see Pricing Sublist and Demand
Plan Detail Sublist in the NetSuite Help Center.
Parameters
•
type {string} [required] - The sublist internal ID. In the NetSuite Help Center, see
Pricing Sublist Internal IDs to determine the correct internal ID of your pricing list.
•
fldnam {string} [required] - The internal ID of the matrix field
•
val {string} [required] - The value of the field
•
column {int} [required] - The column number for this field. Column numbers start at
1, not 0.
Returns
•
The line number (as an integer) of a specified matrix field
Since
•
Version 2009.2
SuiteScript Developer and Reference Guide
SuiteScript Functions
Sublist APIs
479
Example
This sample shows how to return the line number of a particular price in a given column. Note
that if the specified value is present on multiple lines, this API returns the line number of the
first line that contains the value.
var column1 = nlapiFindLineItemMatrixValue('price', 'price', 213.00, 1);
alert('The line number of price 213 from column 1 is. ' + column1);
Back to Sublist APIs | Back to SuiteScript Functions
nlapiFindLineItemValue(type, fldnam, val)
Use this API to find the line number of a specific field in a sublist. This API can be used on any
sublists that supports SuiteScript. This API is supported in client and user event scripts only.
Parameters
•
type {string} [required] - The sublist internal ID (for example, use addressbook as the
ID for the Address sublist). In the NetSuite Help Center, see Scriptable Sublists for a list
of sublists that support SuiteScript, sublist internal IDs, and sublist field IDs.
•
fldnam {string} [required] - The field internal ID
•
val {string} [required] - The value of the field
Returns
•
The line number (as an integer) of a specific sublist field
Since
•
Version 2009.2
Example
nlapiFindLineItemValue('item', 'quantity', '1');
Back to Sublist APIs | Back to SuiteScript Functions
nlapiGetCurrentLineItemIndex(type)
Returns the line number of the currently selected line in a group.
Note: The first line number on a sublist is 1 (not 0).
SuiteScript Developer and Reference Guide
SuiteScript Functions
Sublist APIs
480
Parameters
•
type {string} [required] - The sublist internal ID (for example, use addressbook as the
ID for the Address sublist). In the NetSuite Help Center, see Scriptable Sublists for a list
of sublists that support SuiteScript, sublist internal IDs, and sublist field IDs.
Returns
•
The integer value for the currently selected line number in a sublist
Back to Sublist APIs | Back to SuiteScript Functions
nlapiGetCurrentLineItemMatrixValue(type, fldnam, column)
Use this API to get the value of the currently selected matrix field. This API should be used on
matrix sublists only. This API is supported in client and user event scripts.
Important: Currently the Pricing sublist and Demand Plan Detail sublist are the only
matrix sublist types that support SuiteScript. For details, see Pricing Sublist
and Demand Plan Detail Sublist in the NetSuite Help Center.
Parameters
•
type {string} [required] - The sublist internal ID. In the NetSuite Help Center, see
Pricing Sublist Internal IDs to determine the correct internal ID of your pricing list.
•
fldnam {string} [required] - The internal ID of the matrix field being set.
•
column {int} [required] - The column number for this field. Column numbers start at
1, not 0.
Returns
•
The string value of a field on the currently selected line in a matrix sublist. Returns null
if the field does not exist.
Since
•
Version 2009.2
Example
This sample executes on a pageInit client event. The script throws an alert to let the user know
the values that appear in the first column and the second column of a Pricing sublist.
function getCurrentLine()
{
//Get values for column 1 and column 2
var column1 = nlapiGetCurrentLineItemMatrixValue('price', 'price', 1);
var column2 = nlapiGetCurrentLineItemMatrixValue('price', 'price', 2);
alert('The values in column 1 and 2 are ' + column1 + ' '+column2);
}
SuiteScript Developer and Reference Guide
SuiteScript Functions
Sublist APIs
481
Example 2
This sample executes on a validateField client event. It runs in an account that has the Multiple
Currencies feature enabled. The script gets the value specified in the second column of the
pricing matrix that appears on the USA currency tab (price1). Based on the value, it then sets
values on the British Pound tab (price2). To set line item values, notice the pattern of selecting
the line, then setting values, then committing the changes.
function validateFieldOnItem(type, fld, column)
{
if(type == 'price1')
{
if(nlapiGetCurrentLineItemMatrixValue('price1', 'price', 1)=='44.00')
{
nlapiSetFieldValue('department', 5);
nlapiSelectLineItem('price2', '1');
nlapiSetCurrentLineItemMatrixValue('price2', 'price', 1, '11');
nlapiSetCurrentLineItemMatrixValue('price2', 'price', 2, '12');
nlapiCommitLineItem('price2');
}
}
return true;
}
Back to Sublist APIs | Back to SuiteScript Functions
nlapiGetCurrentLineItemText(type, fldnam)
Returns the display name (the UI label) of a select field (based on its current selection) on the
currently selected line. Typically used in validate line functions.
Parameters
•
type {string} [required] - The sublist internal ID (for example, use addressbook as the
ID for the Address sublist). In the NetSuite Help Center, see Scriptable Sublists for a list
of sublists that support SuiteScript, sublist internal IDs, and sublist field IDs.
•
fldnam {string} [required] - The name of the field being set
Returns
•
The string display name of a select field (based on its current selection) on the
currently selected line. Returns null if the field does not exist.
Back to Sublist APIs | Back to SuiteScript Functions
SuiteScript Developer and Reference Guide
SuiteScript Functions
Sublist APIs
482
nlapiGetCurrentLineItemValue(type, fldnam)
Returns the value of a sublist field on the currently selected line
Parameters
•
type {string} [required] - The sublist internal ID (for example, use addressbook as the
ID for the Address sublist). In the NetSuite Help Center, see Scriptable Sublists for a list
of sublists that support SuiteScript, sublist internal IDs, and sublist field IDs.
•
fldnam {string} [required] - The name of the field being set
Returns
•
The string value of a field on the currently selected line. Returns null if field does not
exist.
Back to Sublist APIs | Back to SuiteScript Functions
nlapiGetCurrentLineItemValues(type, fldnam)
Returns the values of a multiselect sublist field on the currently selected line. One example of a
multiselect sublist field is the Serial Numbers field on the Items sublist.
This function is not supported in client SuiteScript. It is meant to be used in user event scripts.
Parameters
•
type {string} [required] - The sublist internal ID (for example, use addressbook as the
ID for the Address sublist). In the NetSuite Help Center, see Scriptable Sublists for a list
of sublists that support SuiteScript, sublist internal IDs, and sublist field IDs.
•
fldnam {string} [required] - The name of the multiselect field.
Returns
•
An array of string values for the multiselect sublist field (on the currently selected line)
Since
•
Version 2012.1
Back to Sublist APIs | Back to SuiteScript Functions
nlapiGetLineItemCount(type)
Use this API to determine the number of line items on a sublist. You can then use APIs such as
nlapiInsertLineItem or nlapiRemoveLineItem to add or remove lines before/after existing lines.
The nlapiGetLineItemCount API is available in Client and User Event scripts only. If you want
to get the line count of a sublist in a Suitelet, see nlobjSubList.getLineItemCount(group).
Important: The first line number on a sublist is 1 (not 0).
SuiteScript Developer and Reference Guide
SuiteScript Functions
Sublist APIs
483
Parameters
•
type {string} [required] - The sublist internal ID (for example, use addressbook as the
ID for the Address sublist). In the NetSuite Help Center, see Scriptable Sublists for a list
of sublists that support SuiteScript, sublist internal IDs, and sublist field IDs.
Returns
•
The integer value for the number of lines in a sublist for the current record
Example
The following sample shows how to use nlapiGetLineItemCount to programatically determine
the number of line items on a sublist.
function getLineCount()
{
var lineNum = nlapiGetLineItemCount('solutions');
alert('The line item count for this sublist is: ' + lineNum);
}
Back to Sublist APIs | Back to SuiteScript Functions
nlapiGetLineItemField(type, fldnamm, linenum)
Use this function to obtain sublist (line item) field metadata. Calling this function instantiates
the nlobjField object, which then allows you to use all the methods available to nlobjField to get
field metadata.
Note: To obtain metadata for body fields, use nlapiGetField(fldnam).
Parameters
•
type {string} [required] - The sublist internal ID (for example, use addressbook as the
ID for the Address sublist). In the NetSuite Help Center, see Scriptable Sublists for a list
of sublists that support SuiteScript, sublist internal IDs, and sublist field IDs.
•
fldnam {string} [required] - The internal ID of the sublist field
•
linenum {int} [required] - The line number for this field. Note the first line number on
a sublist is 1 (not 0).
Returns
•
An nlobjField object representing this line item field
Since
•
Version 2009.1
SuiteScript Developer and Reference Guide
SuiteScript Functions
Sublist APIs
484
Example
The following script is attached to a Sales Order. The nlapiGetLineItemField API returns a
nlobjField object. This script then uses the field object methods getType() and getLabel() to
return the sublist field’s type and UI label.
function clientSideScript(type, form)
{
var field = nlapiGetLineItemField('item', 'quantity');
alert(field.getType()); // returns float as the field type
alert(field.getLabel()); // returns Quantity as the field UI label
}
Back to Sublist APIs | Back to SuiteScript Functions
nlapiGetLineItemMatrixField(type, fldnam, linenum, column)
Use this API to obtain metadata for a field that appears in a matrix sublist. This API is
supported in client and user event scripts.
Note: Currently the Pricing sublist and Demand Plan Detail sublist are the only matrix
sublist types that support SuiteScript. For details, see Pricing Sublist and Demand
Plan Detail Sublist in the NetSuite Help Center.
Calling this function instantiates the nlobjField object, which then allows you to use all the
methods available to the nlobjField object.
Note: To obtain metadata for body fields, use nlapiGetField(fldnam).
Parameters
•
type {string} [required] - The sublist internal ID. In the NetSuite Help Center, see
Pricing Sublist Internal IDs to determine the correct internal ID of your pricing list.
•
fldnam {string} [required] - The internal ID of the field (line) whose value you want
returned.
•
linenum {int} [required] - The line number for this field. Note the first line number on
a sublist is 1 (not 0).
•
column {int} [required] - The column number for this field. Column numbers start at
1, not 0.
Returns
•
An nlobjField object representing this sublist field. Returns null if the field you have
specified does not exist.
Since
•
Version 2009.2
SuiteScript Developer and Reference Guide
SuiteScript Functions
Sublist APIs
485
Example
This script executes on a pageInit client event. It gets the metadata of a matrix field on the
Pricing sublist.
function getFieldInfo()
{
var matrixField = nlapiGetLineItemMatrixField('price1', 'price', '1', '1');
var fieldLabel = matrixField.getLabel();
var fieldName = matrixField.getName();
var fieldType = matrixField.getType();
var fieldMetaInfo = 'Label: '+fieldLabel+' Name: '+fieldName+' Type: '+fieldType ;
alert('price field metadata is : '+ fieldMetaInfo);
}
Back to Sublist APIs | Back to SuiteScript Functions
nlapiGetLineItemMatrixValue(type, fldnam, linenum, column)
Use this API to get the value of a matrix field that appears on a specific line in a specific
column. This API can be used only in the context of a matrix sublist. This API is supported in
client and user event scripts.
Important: Currently the Pricing sublist and Demand Plan Detail sublist are the only
matrix sublist types that support SuiteScript. For details, see Pricing Sublist
and Demand Plan Detail Sublist in the NetSuite Help Center.
Parameters
•
type {string} [required] - The sublist internal ID. In the NetSuite Help Center, see
Pricing Sublist Internal IDs to determine the correct internal ID of your pricing list.
•
fldnam {string} [required] - The internal ID of the matrix field whose value you want
returned.
•
linenum {int} [required] - The line number for this field. Note the first line number on
a sublist is 1 (not 0).
•
column {int} [required] - The column number for this field. Column numbers start at 1
(not 0).
Returns
•
The string value of the matrix field.
Since
•
Version 2009.2
SuiteScript Developer and Reference Guide
SuiteScript Functions
Sublist APIs
486
Example
This sample executes on a pageInit client event. The script will throw an alert that lists the
values appearing in columns 1 and 2 on line 1 of the Pricing sublist.
function getMatValues()
{
nlapiSelectLineItem('price', 1);
var column1 = nlapiGetLineItemMatrixValue('price', 'price', 1, 1);
var column2 = nlapiGetLineItemMatrixValue('price', 'price', 1, 2);
alert('Values from row 1 and 2 are ' + column1 + ' '+column2);
}
Back to Sublist APIs | Back to SuiteScript Functions
nlapiGetLineItemText(type, fldnam, linenum)
Returns the display name of a select field (based on its current selection) in a sublist.
Parameters
•
type {string} [required] - The sublist internal ID (for example, use addressbook as the
ID for the Address sublist). In the NetSuite Help Center, see Scriptable Sublists for a list
of sublists that support SuiteScript, sublist internal IDs, and sublist field IDs.
•
fldnam {string} [required] - The name of the field being set
•
linenum {int} [required] - The line number for this field. Note the first line number on
a sublist is 1 (not 0).
Returns
•
The string value of the display name of a select field (based on its current selection) in
a sublist. Returns null if field does not exist on the record or the field is restricted.
Example
This is a simple client script that throws an alert with the value of the myText variable.
function testGetText()
{
var myText = nlapiGetLineItemText('item', 'item', 1);
if (myText != '' || myText != null)
{
alert ('value obtained is ' +myText);
}
else
{
alert('value obtained is not valid');
}
}
SuiteScript Developer and Reference Guide
SuiteScript Functions
Sublist APIs
487
Back to Sublist APIs | Back to SuiteScript Functions
nlapiGetLineItemValue(type, fldnam, linenum)
Available only in client and user event SuiteScripts. Note that you cannot set default line item
values when the line is not in edit mode.
Also, NetSuite recommends that you read the topic Getting Field Values in SuiteScript, which
addresses the rare instances in which the value returned by this API is inconsistent.
Note: Normally custom transaction column fields that are not checked to show on a
custom form are not available to get/setLineItemValue APIs. However, if you set
them to show, but then set the label to empty, they will be available on the form
but will not appear on the sublist. Note this does not apply to fields that are marked
as Hidden on the custom field definition. These fields are always available on every
form.
Parameters
•
type {string} [required] - The sublist internal ID (for example, use addressbook as the
ID for the Address sublist). In the NetSuite Help Center, see Scriptable Sublists for a list
of sublists that support SuiteScript, sublist internal IDs, and sublist field IDs.
•
fldnam {string} [required] - The internal ID of the field (line item) whose value is
being returned
•
linenum {int} [required] - The line number for this field. Note the first line number on
a sublist is 1 (not 0).
Returns
•
The string value of a sublist line item
Back to Sublist APIs | Back to SuiteScript Functions
nlapiGetLineItemValues(type, fldname, linenum)
Returns the values of a multiselect sublist field on a selected line. One example of a multiselect
sublist field is the Serial Numbers field on the Items sublist.
This function is not supported in client SuiteScript. It is meant to be used in user event scripts.
Parameters
•
type {string} [required] - The sublist internal ID (for example, use addressbook as the
ID for the Address sublist). In the NetSuite Help Center, see Scriptable Sublists for a list
of sublists that support SuiteScript, sublist internal IDs, and sublist field IDs.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Sublist APIs
488
•
fldnam {string} [required] - The internal ID of the multiselect field
•
linenum {int} [required] - The line number for this field. Note the first line number on
a sublist is 1 (not 0).
Returns
•
An array of string values for the multiselect sublist field
Since
•
Version 2012.1
Back to Sublist APIs | Back to SuiteScript Functions
nlapiGetMatrixCount(type, fldnam)
Use this API in a matrix sublist to get the number of columns for a specific matrix field. This
API is supported in client and user event scripts.
Note: Currently the Pricing sublist and the Demand Plan Detail sublist are the only matrix
sublist types that support SuiteScript, and this API typically would not be used for
the Demand Plan Detail sublist. For details on working with the Pricing sublist, see
Pricing Sublist in the NetSuite Help Center.
Note: The first column in a matrix is 1, not 0.
Parameters
•
type {string} [required] - The sublist internal ID. In the NetSuite Help Center, see
Pricing Sublist Internal IDs to determine the correct internal ID of your pricing list.
•
fldnam {string} [required] - The field internal ID of the matrix field.
Returns
•
The integer value for the number of columns of a specified matrix field
Since
•
Version 2009.2
Example
This sample executes on a pageInit client event. If there are 2 columns in the pricing matrix, the
value of 2 will be passed to matrixCount variable. If there are 3 columns, the value of 3 will be
passed. Note that the type parameter is set to price1. This means that the Multiple Currencies
feature has been enabled in the user’s account, and the user is scripting to the USA tab on the
Pricing Sublist.
function getCount()
{
SuiteScript Developer and Reference Guide
SuiteScript Functions
Sublist APIs
489
var matrixCount = nlapiGetMatrixCount('price1', 'price');
alert('Matrix Count is '+ matrixCount);
}
Back to Sublist APIs | Back to SuiteScript Functions
nlapiGetMatrixField(type, fldnam, column)
Use this API to get field metadata for a matrix “header” field in a matrix sublist.
Note: Currently the Pricing sublist and the Demand Plan Detail sublist are the only matrix
sublist types that support SuiteScript, and this API is used only for the Pricing
sublist. For details on working with the Pricing sublist, see Pricing Sublist in the
NetSuite Help Center.
For example, if the Quantity Pricing feature is enabled in your account, you will see the Qty
fields at the top of the pricing matrix. The Qty fields are considered to be the header fields in
the pricing matrix. For more information on matrix header fields, see Matrix APIs in the
NetSuite Help Center.
This API is supported in client and user event scripts.
Parameters
•
type {string} [required] - The sublist internal ID. In the NetSuite Help Center, see
Pricing Sublist Internal IDs to determine the correct internal ID of your pricing list.
•
fldnam {string} [required] - The internal ID of the matrix header field.
•
column {int} [required] - The column number for this field. Column numbers start at 1
(not 0).
Returns
•
nlobjField object
Since
•
Version 2009.2
Example
This sample executes on a pageInit client event to get the metadata of a matrix header field. In
this case, Qty is the matrix header field on the Pricing sublist. Once you call
nlapiGetMatrixField() you can use all the methods on the nlobjField object to get whatever
field metadata you might need.
function getMatrixHeaderInfo()
{
var qtyObject = nlapiGetMatrixField('price', 'price', 2);
var fieldLabel = qtyObject.getLabel();
SuiteScript Developer and Reference Guide
SuiteScript Functions
Sublist APIs
490
var fieldName = qtyObject.getName();
var fieldType = qtyObject.getType();
var fieldMetaInfo = 'Label: '+fieldLabel+' Name: '+fieldName+' Type: '+fieldType ;
alert('Get Quantity Field Meta data ' + fieldMetaInfo);
}
Back to Sublist APIs | Back to SuiteScript Functions
nlapiGetMatrixValue(type, fldnam, column)
Use this API to get the value of a matrix “header” field in a matrix sublist.
Note: Currently the Pricing sublist and the Demand Plan Detail sublist are the only matrix
sublist types that support SuiteScript, and this API is used only for the Pricing
sublist. For details on working with the Pricing sublist, see Pricing Sublist in the
NetSuite Help Center.
For example, if the Quantity Pricing feature is enabled in your account, you will see the Qty
fields at the top of the pricing matrix. The Qty fields are considered to be the header fields in
the pricing matrix. See Matrix APIs in the NetSuite Help Center for more information on
matrix header fields.
This API is supported in client and user event scripts.
Parameters
•
type {string} [required] - The sublist internal ID. In the NetSuite Help Center, see
Pricing Sublist Internal IDs to determine the correct internal ID of your pricing list.
•
fldnam {string} [required] - The internal ID of the matrix header field.
•
column {int} [required] - The column number for this field. Column numbers start at 1
(not 0).
Returns
•
The integer value of a matrix header field. For example, on the Pricing sublist the value
of a specified quantity level (Qty) field is returned.
Since
•
Version 2009.2
Example 1
This sample executes on a pageInit client event to get the value of the quantity level that
appears on the second column of the Pricing sublist. Note that the type parameter is set to
price1. This means that the Multiple Currencies feature has been enabled in the user’s account,
and the user is scripting to the USA tab on the Pricing Sublist.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Sublist APIs
491
function getMatValue()
{
var matrixValue = nlapiGetMatrixValue('price1', 'price', 2);
alert('Value in the column is '+ matrixValue);
}
Example 2
This sample executes on a validateField client event. It gets the value of a quantity (Qty) matrix
header field.
function validateFieldOnItem(type, fld, column)
{
if( type=='price1' )
{
if(nlapiGetMatrixValue('price1', 'price', '2')=='100')
{
alert('Item is available to ship');
nlapiSetFieldValue('department', 5);
nlapiSelectLineItem('price2', '1');
nlapiSetCurrentLineItemMatrixValue('price2', 'price', 1, '100');
nlapiSetCurrentLineItemMatrixValue('price2', 'price', 2, '90');
nlapiCommitLineItem('price2');
}
}
return true;
}
Back to Sublist APIs | Back to SuiteScript Functions
nlapiInsertLineItem(type, line)
Inserts a line above the currently selected line in a sublist. Available to client and user event
scripts only.
Parameters
•
type {string} [required] - The sublist internal ID (for example, use addressbook as the
ID for the Address sublist). In the NetSuite Help Center, see Scriptable Sublists for a list
of sublists that support SuiteScript, sublist internal IDs, and sublist field IDs.
•
line {int} [required] - The line number in which to insert new line. Note the first line
number on a sublist is 1 (not 0).
Returns
•
void
Back to Sublist APIs | Back to SuiteScript Functions
SuiteScript Developer and Reference Guide
SuiteScript Functions
Sublist APIs
492
nlapiInsertLineItemOption(type, fldnam, value, text, selected)
Adds a select option to a select/multiselect field that was added through scripting. This field
will appear as a line item on a sublist.
Note that this API can only be used on select/multiselect fields that are added via the UI
Objects API (for example on Suitelets or beforeLoad user events).
For performance reasons, you should disable the drop-down before adding multiple options,
then enable the drop-down when finished.
Parameters
•
type {string} [required] - The sublist internal ID (for example, use addressbook as the
ID for the Address sublist). In the NetSuite Help Center, see Scriptable Sublists for a list
of sublists that support SuiteScript, sublist internal IDs, and sublist field IDs.
•
fldnam {string} [required] - The name of the scripted field
•
value {string | int} [required] - A unique value for the select option. Note that the
datatype for this argument will vary depending on the value that is set. For example,
you may assign numerical values such as 1, 2, 3 or string values such as option1,
option2, option3.
•
text {string} [required] - The display name of the select option
•
selected {boolean} [optional] - If not set, this argument defaults to false. If set to true,
the selected option will become the default selection. Note: The values for this
parameter are true or false, not T or F.
Returns
•
void
Back to Sublist APIs | Back to SuiteScript Functions
nlapiIsLineItemChanged(type)
Determines whether any changes have been made to a sublist
Parameters
•
type {string} [required] - The sublist internal ID (for example, use addressbook as the
ID for the Address sublist). In the NetSuite Help Center, see Scriptable Sublists for a list
of sublists that support SuiteScript, sublist internal IDs, and sublist field IDs.
Returns
•
Returns true if the currently selected line of the sublist has been edited
Back to Sublist APIs | Back to SuiteScript Functions
SuiteScript Developer and Reference Guide
SuiteScript Functions
Sublist APIs
493
nlapiRefreshLineItems(type)
Makes a server call in order to refresh staticlist (read-only) sublists. For inlineeditor or editor
sublists, it simply redraws the sublist. This API does not do anything for sublists of type list.
Parameters
•
type {string} [required] - The sublist internal ID (for example, use addressbook as the
ID for the Address sublist). In the NetSuite Help Center, see Scriptable Sublists for a list
of sublists that support SuiteScript, sublist internal IDs, and sublist field IDs.
Returns
•
void
Back to Sublist APIs | Back to SuiteScript Functions
nlapiRemoveLineItem(type, line)
Removes the currently selected line in a sublist. Available to client and user event scripts only.
Note: For Scheduled scripts, use the equivalent record-level method:
nlobjRecord.removeLineItem(group, linenum).
Parameters:
•
type {string} [required] - The sublist internal ID (for example, use addressbook as the
ID for the Address sublist). In the NetSuite Help Center, see Scriptable Sublists for a list
of sublists that support SuiteScript, sublist internal IDs, and sublist field IDs.
•
line {int} [required] - The line number you want to remove (only valid for User Event
scripts and Suitelets). Note the first line number on a sublist is 1 (not 0).
Returns
•
void
Back to Sublist APIs | Back to SuiteScript Functions
nlapiRemoveLineItemOption(type, fldnam, value)
Removes a single select option from a select or multiselect line item field added through a
script
Parameters
•
type {string} [required] - The sublist internal ID (for example, use addressbook as the
ID for the Address sublist). In the NetSuite Help Center, see Scriptable Sublists for a list
of sublists that support SuiteScript, sublist internal IDs, and sublist field IDs.
•
fldnam {string} [required] - The name of the scripted field
SuiteScript Developer and Reference Guide
SuiteScript Functions
Sublist APIs
•
494
value {string} [required] - The value of the select option to be removed or null to delete
all the options
Returns
•
void
Back to Sublist APIs | Back to SuiteScript Functions
nlapiSelectLineItem(type, linenum)
Selects an existing line in a sublist
Parameters
•
type - {string} [required] - The sublist internal ID (for example, use addressbook as the
ID for the Address sublist). In the NetSuite Help Center, see Scriptable Sublists for a list
of sublists that support SuiteScript, sublist internal IDs, and sublist field IDs.
•
linenum - {int} [required] - The line number to select. Note the first line number on a
sublist is 1 (not 0).
Returns
•
void
Back to Sublist APIs | Back to SuiteScript Functions
nlapiSelectNewLineItem(type)
Use this function if you want to set a value on a sublist line that does not currently exist. This
API is the UI equivalent of clicking a sublist tab (for example the Items sublist tab) so that you
can then add a new line (or item, in this example) to the sublist.
Parameters
•
type {string} [required] - The sublist internal ID (for example, use addressbook as the
ID for the Address sublist). In the NetSuite Help Center, see Scriptable Sublists for a list
of sublists that support SuiteScript, sublist internal IDs, and sublist field IDs.
Returns
•
void
Example
function sampleClientPageInit()
{
nlapiSetFieldValue('entity', '294');
// this is the equivalent of selecting the Items sublist tab. You must do this when you want to
// add new lines to a sublist
SuiteScript Developer and Reference Guide
SuiteScript Functions
Sublist APIs
495
nlapiSelectNewLineItem('item');
// set the item and location values on the currently selected line
nlapiSetCurrentLineItemValue('item', 'item', 380);
nlapiSetCurrentLineItemValue('item', 'location', 102);
// commit the line to the database
nlapiCommitLineItem('item');
}
Back to Sublist APIs | Back to SuiteScript Functions
nlapiSetCurrentLineItemMatrixValue(type, fldnam, column, value,
firefieldchanged, synchronous)
This API is typically used in validate line functions to set the value of a given matrix sublist
field before it has been added to the form. This API is supported in client and user event
scripts. Also note that it should be used on matrix sublists only.
Note: Currently the Pricing sublist and Demand Plan Detail sublist are the only matrix
sublist types that support SuiteScript. For details, see Pricing Sublist and Demand
Plan Detail Sublist in the NetSuite Help Center.
Parameters
•
type {string} [required] - The sublist internal ID. In the NetSuite Help Center, see
Pricing Sublist Internal IDs to determine the correct internal ID of your pricing list.
•
fldnam {string} [required] - The internal ID of the matrix field.
•
column {int} [required] - The column number for this field. Column numbers start at 1
(not 0).
•
value {string | int} [required] - The value the field is being set to.
•
firefieldchanged {boolean} [optional] - If true, then the field change script for that field
is executed. If no value is provided, this argument defaults to true. (Available in Client
SuiteScript only). See Using the Fire Field Changed Parameter for more information.
Note: The firefieldchanged parameter takes the values of true or false, not T or F.
•
synchronous {boolean} [optional] - This parameter is relevant for client SuiteScripts
only. In server scripts (such as user event scripts), this parameter will always execute as
true.
In client scripts, if you do not set the value of synchronous, the default value is false,
and the API executes asynchronously. If set to true, this API executes synchronously,
which ensures a predictable script execution. Setting to true forces your client script to
wait on any specified sourcing before continuing with the rest of the script.
Note: In client scripts, the synchronous parameter takes the values of true or false, not T
or F.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Sublist APIs
496
Returns
•
void
Since
•
Version 2009.2
Example
The following sample is a user event script that executes on a beforeLoad event. This script is
set to execute on the Pricing sublist on an Inventory Item record. On the Pricing sublist it will
set the Base Price for the first two columns of the USA tab. The presence of the USA tab
indicates that the Multiple Currencies feature is enabled in this account. Therefore, the internal
ID of the type parameter in all matrix APIs will be price1.
function beforeLoad(type, form)
{
nlapiSetFieldValue('itemid', '124');
//Set the pricing matrix header field (Qty) in the second column to 600
nlapiSetMatrixValue('price1', 'price', '2', 600);
//Set values on line one. First you must select the line, then set all values,
//then commit the line.
nlapiSelectLineItem('price1', '1');
nlapiSetCurrentLineItemMatrixValue('price1', 'price', 1, '11');
nlapiSetCurrentLineItemMatrixValue('price1', 'price', 2, '12');
nlapiCommitLineItem('price1');
}
Back to Sublist APIs | Back to SuiteScript Functions
nlapiSetCurrentLineItemText(type, fldnam, text, firefieldchanged,
synchronous)
Sets the value of a select field on the currently selected line using the display name. See also,
Using the Fire Field Changed Parameter.
Parameters
•
type {string} [required] - The sublist internal ID (for example, use addressbook as the
ID for the Address sublist). In the NetSuite Help Center, see Scriptable Sublists for a list
of sublists that support SuiteScript, sublist internal IDs, and sublist field IDs.
•
fldnam {string} [required] - The name of the field being set
•
text {string} [required] - The display name associated with the value that the field is
being set to
SuiteScript Developer and Reference Guide
SuiteScript Functions
Sublist APIs
•
497
firefieldchanged {boolean} [optional] - If true, then the fieldchange script for that field
is executed. If no value is provided, this argument defaults to true. (Available in Client
SuiteScript only). See Using the Fire Field Changed Parameter for more information.
Note: The firefieldchanged parameter takes the values of true or false, not T or F.
•
synchronous {boolean} [optional] - This parameter is relevant for client SuiteScripts
only. In server scripts (such as user event scripts), this parameter will always execute as
true.
In client scripts, if you do not set the value of synchronous, the default value is false,
and the API executes asynchronously. If set to true, this API executes synchronously,
which ensures a predictable script execution. Setting to true forces your client script to
wait on any specified sourcing before continuing with the rest of the script.
Note: In client scripts, the synchronous parameter takes the values of true or false, not T
or F.
Returns
•
void
Back to Sublist APIs | Back to SuiteScript Functions
nlapiSetCurrentLineItemValue(type, fldnam, value, firefieldchanged,
synchronous)
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.
Parameters
•
type {string} [required] - The sublist internal ID (for example, use addressbook as the
ID for the Address sublist). In the NetSuite Help Center, see Scriptable Sublists for a list
of sublists that support SuiteScript, sublist internal IDs, and sublist field IDs.
•
fldnam {string} [required] - The name of the field being set
•
value {string} [required] - The value the field is being set to. Note: Check box fields
take the values of T or F, not true or false.
•
firefieldchanged {boolean} [optional] - If true, then the fieldchange script for that field
is executed. If no value is provided, this argument defaults to true. (Available in Client
SuiteScript only). See Using the Fire Field Changed Parameter for more information.
Note: The firefieldchanged parameter takes the values of true or false, not T or F.
•
synchronous {boolean} [optional] - This parameter is relevant for client SuiteScripts
only. In server scripts (such as user event scripts), this parameter will always execute as
true.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Sublist APIs
498
In client scripts, if you do not set the value of synchronous, the default value is false,
and the API executes asynchronously. If set to true, this API executes synchronously,
which ensures a predictable script execution. Setting to true forces your client script to
wait on any specified sourcing before continuing with the rest of the script.
Note: In client scripts, the synchronous parameter takes the values of true or false, not T
or F.
Returns
•
void
Back to Sublist APIs | Back to SuiteScript Functions
nlapiSetCurrentLineItemValues(type, fldnam, values, firefieldchanged, synchronous)
Sets the values for a multi-select sublist field. Note that like any other “set field” APIs, the values
you use will be internal ID values. For example, rather than specifying 'Abe Simpson' as a
customer value, you will use 232 or 88 or whatever the internal ID is for customer Abe
Simpson.
However, if you are using this API to set the serialnumber field on the Item sublist, you will set
the text string of the actual serial number, for example 'serialnum1', 'serialnum2', and so on.
This API is supported in client scripts only.
Parameters
•
type {string} [required] - The sublist internal ID (for example, use addressbook as the
ID for the Address sublist). In the NetSuite Help Center, see Scriptable Sublists for a list
of sublists that support SuiteScript, sublist internal IDs, and sublist field IDs.
•
fldnam {string} [required] - The name of the multi-select sublist field being set.
•
values {array} [required] - The values for the field.
•
firefieldchanged {boolean} [optional] - If true, then the fieldchange script for that field
is executed. If no value is provided, this argument defaults to true. (Available in Client
SuiteScript only). See Using the Fire Field Changed Parameter for more information.
Note: The firefieldchanged parameter takes the values of true or false, not T or F.
•
synchronous {boolean} [optional] - This parameter is relevant for client SuiteScripts
only. In client scripts, if you do not set the value of synchronous, the default value is
false, and the API executes asynchronously. If set to true, this API executes
synchronously, which ensures a predictable script execution. Setting to true forces your
client script to wait on any specified sourcing before continuing with the rest of the
script.
Note: In client scripts, the synchronous parameter takes the values of true or false, not T
or F.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Sublist APIs
499
Returns
•
void
Since
•
Version 2012.1
Example
If the source of the items comes from different lot numbers, the best way of setting the serial
number is the following. Note this is for client scripting only.
var serialArr = new Array();
serialArr[0] = 'amsLot1(1)';
serialArr[1] = 'amsLot2(1)';
nlapiSelectNewLineItem('item');
nlapiSetCurrentLineItemValue('item', 'item', 199, true, true);
nlapiSetCurrentLineItemValue('item', 'quantity', 2, true, true);
nlapiSetCurrentLineItemValues('item', 'serialnumbers', serialArr, true, true);
nlapiCommitLineItem('item');
Back to Sublist APIs | Back to SuiteScript Functions
nlapiSetLineItemValue(type, fldnam, linenum, value)
Sets the value of a sublist field on the current, new record. This API can be used in beforeLoad
user event scripts to initialize sublist line items, but only on new records and only on nonstored sublist fields. If you execute this API on an existing record, nothing will happen.
Note that this API is supported in user event scripts only.
This function can be used in client SuiteScript, but note that it is supported only on custom
fields and the Description field. If you use this function to set the value of a standard, built-in
line item field, the function will not execute.
Note: Normally custom transaction column fields that are not checked to show on a
custom form are not available to get/setLineItemValue APIs. However, if you set
them to show, but then set the label to empty, they will be available on the form
but will not appear on the sublist. Note this does not apply to fields that are marked
as Hidden on the custom field definition. These fields are always available on every
form.
Parameters
•
type {string} [required] - The sublist internal ID (for example, use addressbook as the
ID for the Address sublist). In the NetSuite Help Center, see Scriptable Sublists for a list
of sublists that support SuiteScript, sublist internal IDs, and sublist field IDs.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Sublist APIs
500
•
fldnam {string} [required] - The name of the field being set
•
linenum {int} [required] - The line number for this field. Note the first line number on
a sublist is 1 (not 0).
•
value {string} [required] - The value the field is being set to
Returns
•
void
Back to Sublist APIs | Back to SuiteScript Functions
nlapiSetMatrixValue(type, fldnam, column, value, firefieldchanged,
synchronous)
This API is used to set a header field in a matrix sublist. This API is supported in client and
user event scripts. It is typically used in pageInit (client) and beforeLoad (user event) events.
Also note that this API should be used on matrix sublists only.
Note: Currently the Pricing sublist and the Demand Plan Detail sublist are the only matrix
sublist types that support SuiteScript, and this API is used only for the Pricing
sublist. For details on working with the Pricing sublist, see Pricing Sublist in the
NetSuite Help Center.
In the case of the Pricing sublist, this API is used to set the quantity levels that appear in the
Qty fields (see figure). Note that you should use this API only if you have the Quantity Pricing
feature enabled in your account, as these header fields appear only if this feature is enabled.
[UE=HELP_TOPIC_OUT_OF_DATE_ALERT=UE]
Parameters
•
type {string} [required] - The sublist internal ID. In the NetSuite Help Center, see
Pricing Sublist Internal IDs to determine the correct internal ID of your pricing list.
•
fldnam {string} [required] - The name of the field being set.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Sublist APIs
501
•
value {string} [required] - The value the field is being set to. Note: Check box fields
take the values of T or F, not true or false.
•
column {int} [required] - The column number for this field. Column numbers start at 1
(not 0).
•
firefieldchanged {boolean} [optional] - If true, then the field change script for that field
is executed. If no value is provided, this argument defaults to true. (Available in Client
SuiteScript only). See Using the Fire Field Changed Parameter for more information.
Note: The firefieldchanged parameter takes the values of true or false, not T or F.
•
synchronous {boolean} [optional] - This parameter is relevant for client SuiteScripts
only. In server scripts (such as user event scripts), this parameter will always execute as
true.
In client scripts, if you do not set the value of synchronous, the default value is false,
and the API executes asynchronously. If set to true, this API executes synchronously,
which ensures a predictable script execution. Setting to true forces your client script to
wait on any specified sourcing before continuing with the rest of the script.
Note: In client scripts, the synchronous parameter takes the values of true or false, not T
or F.
Returns
•
void
Since
•
Version 2009.2
Example
The following sample is a user event script that executes on a beforeLoad event. This script is
set to execute on the Pricing sublist on an Inventory Item record. On the Pricing sublist it will
set the Base Price for the first two columns of the USA tab. The presence of the USA tab
indicates that the Multiple Currencies feature is enabled in this account. Therefore, the internal
ID of the type parameter in all matrix APIs will be price1.
function beforeLoad(type, form)
{
nlapiSetFieldValue('itemid', '124');
//Set the pricing matrix header field (Qty) in the second column to 600
nlapiSetMatrixValue('price1', 'price', '2', 600);
//Set values on line one. First you must select the line, then set all values,
//then commit the line.
nlapiSelectLineItem('price1', '1');
nlapiSetCurrentLineItemMatrixValue('price1', 'price', 1, '11');
nlapiSetCurrentLineItemMatrixValue('price1', 'price', 2, '12');
nlapiCommitLineItem('price1');
}
SuiteScript Developer and Reference Guide
SuiteScript Functions
Sublist APIs
502
Back to Sublist APIs | Back to SuiteScript Functions
nlobjSubList
See nlobjSubList - defined in the section on UI Objects.
Back to Sublist APIs | Back to SuiteScript Functions
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 an unending loop exists as follows:
1.
The Client script watches for fieldA to change.
2.
fieldA changes.
3.
The script 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
client scripts.
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 firefieldchanged parameter, you can modify the above example to:
1.
Client script watches for fieldA to change.
2.
fieldA changes.
3.
Client script writes to fieldA using firefieldchanged = false, so the Field Changed event
does not fire.
The following API calls can set the firefieldchanged parameter.
Note: The set line item text and value functions are NOT affected, as these do not currently
call field changed after firing.
•
nlapiSetFieldValue(fldnam, value, firefieldchanged, synchronous)
•
nlapiSetFieldText(fldname, txt, firefieldchanged, synchronous)
•
nlapiSetCurrentLineItemValue(type, fldnam, value, firefieldchanged, synchronous)
SuiteScript Developer and Reference Guide
SuiteScript Functions
Search APIs
•
503
nlapiSetCurrentLineItemText(type, fldnam, text, firefieldchanged, synchronous)
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.
Search APIs
For an overview of using SuiteScript to execute searches in NetSuite, see Searching Overview.
All APIs listed below are in alphabetical order.
•
nlapiCreateSearch(type, filters, columns)
•
nlapiLoadSearch(type, id)
•
nlapiLookupField(type, id, fields, text)
•
nlapiSearchDuplicate(type, fields, id)
•
nlapiSearchGlobal(keywords)
•
nlapiSearchRecord(type, id, filters, columns)
•
nlobjSearchColumn
•
nlobjSearchFilter
•
nlobjSearchResult
nlapiCreateSearch(type, filters, columns)
Creates a new search. The search can be modified and run as an ad-hoc search, without saving
it. Alternatively, calling nlobjSearch.saveSearch(title, scriptId) will save the search to the
database, so it can be resused later in the UI or using nlapiLoadSearch(type, id).
Note: This function is agnostic in terms of its filters argument. It can accept input of either
a search filter (nlobjSearchFilter), a search filter list (nlobjSearchFilter[]), or a search
filter expression (Object[]).
Parameters
•
type {string} [required] - The record internal ID of the record type you are searching
(for example, customer|lead|prospect|partner|vendor|contact). For a list of internal
IDs, in the NetSuite Help Center see SuiteScript Supported Records.
•
filters {nlobjSearchFilter | nlobjSearchFilter[] | Object[] } [optional] - A single
nlobjSearchFilter object - or - an array of nlobjSearchFilter objects - or - a search filter
expression.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Search APIs
504
Note: You can further filter the returned nlobjSearch object by passing additional filter
values. You will do this using the nlobjSearch.addFilter(filter) method or
nlobjSearch.addFilters(filters) method.
•
columns {nlobjSearchColumn or nlobjSearchColumn[]} [optional] - A single
nlobjSearchColumn object - or - an array of nlobjSearchColumn objects. Note that
you can further filter the returned nlobjSearch object by passing additional search
return column values. You will do this using the nlobjSearch.setColumns(columns)
method.
Returns
•
nlobjSearch
Since
•
Version 2012.1
Example 1
This example shows how to create a new saved search. First you define any search filters and
search return columns. Next you call nlapiCreateSearch(...) to execute the search. To save the
search, you must then call the nlobjSearch.saveSearch(title, scriptId) method. Note that you are
not required to save searches that are generated through nlapiCreateSearch(...).
// Define search filters
var filters = new Array();
filters[0] = new nlobjSearchFilter( 'trandate', null, 'onOrAfter', 'daysAgo90' );
filters[1] = new nlobjSearchFilter( 'projectedamount', null, 'between', 1000, 100000 );
filters[2] = new nlobjSearchFilter( 'salesrep', 'customer', 'anyOf ', \-5, null );
// Define search columns
var columns = new Array();
columns[0] = new nlobjSearchColumn( 'salesrep' );
columns[1] = new nlobjSearchColumn( 'expectedclosedate' );
columns[2] = new nlobjSearchColumn( 'entity' );
columns[3] = new nlobjSearchColumn( 'projectedamount' );
columns[4] = new nlobjSearchColumn( 'probability' );
columns[5] = new nlobjSearchColumn( 'email', 'customer' );
columns[6] = new nlobjSearchColumn( 'email', 'salesrep' );
// Create the saved search
var search = nlapiCreateSearch( 'opportunity', filters, columns );
var searchId = search.saveSearch('My Opportunities in Last 90 Days', 'customsearch_kr');
Example 2
This example shows how to load an existing search, create a new search based on existing
criteria, define additional criteria, and then save the search as a new search.
var search = nlapiLoadSearch('opportunity', 'customsearch_blackfriday');
var newSearch = nlapiCreateSearch(search.getSearchType(), search.getFilters(),
search.getColumns());
newSearch.addFilter(new nlobjSearchFilter(...)); //Specify your own criteria here to add as a filter
newSearch.setIsPublic(true);
newSearch.saveSearch('My new opp search', 'customsearch_blacksaturday');
SuiteScript Developer and Reference Guide
SuiteScript Functions
Search APIs
505
Example 3
This example shows how to create a new saved search using a search filter expression.
//Define search filter expression
var filterExpression = [ [ 'trandate', 'onOrAfter', 'daysAgo90' ],
'and',
[ 'projectedamount', 'between', 1000, 100000 ],
'and',
[ 'customer.salesrep', 'anyOf ', -5 ] ];
//Define search columns
var columns = new Array();
columns[0] = new nlobjSearchColumn('salesrep');
columns[1] = new nlobjSearchColumn('expectedclosedate');
columns[2] = new nlobjSearchColumn('entity');
columns[3] = new nlobjSearchColumn('projectedamount');
columns[4] = new nlobjSearchColumn('probability');
columns[5] = new nlobjSearchColumn('email', 'customer');
columns[6] = new nlobjSearchColumn('email', 'salesrep');
//Create the saved search
var search = nlapiCreateSearch('opportunity', filterExpression, columns);
var searchId = search.saveSearch('My Opportunities in Last 90 Days', 'customsearch_kr');
Example 4
This example shows how to load an existing search, create a new search based on existing
criteria with the use of a search filter expression, define additional criteria, and then save the
search as a new search.
var search = nlapiLoadSearch('opportunity', 'customsearch_blackfriday');
var newSearch = nlapiCreateSearch(search.getSearchType(), search.getFilterExpression(),
search.getColumns());
newSearch.addFilter (new nlobjSearchFilter(…)); //Specify your own criteria here to add as a filter
newSearch.setIsPublic(true);
newSearch.saveSearch('My new opp search', 'customsearch_blacksaturday');
Back to Search APIs | Back to SuiteScript Functions
nlapiLoadSearch(type, id)
Loads an existing saved search. The saved search could have been created using the UI, or
created using nlapiCreateSearch(type, filters, columns) in conjunction with
nlobjSearch.saveSearch(title, scriptId).
Executing this API consumes 5 governance units.
Parameters
•
type {string} [optional] - The record internal ID of the record type you are searching
(for example, customer|lead|prospect|partner|vendor|contact). For a list of internal
IDs, in the NetSuite Help Center see SuiteScript Supported Records.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Search APIs
•
506
id {string} [required] - The internal ID or script ID of the saved search. The script ID
of the saved search is required, regardless of whether you specify the search type. If you
do not specify the search type, you must set type to null and then set the script/search
ID. See Example 3 for more details.
Returns
•
nlobjSearch
Since
•
Version 2012.1
Example 1
This sample shows how to load an existing saved search and add additional filtering criteria to
the search. The search is then designated as a public search and saved.
var s = nlapiLoadSearch('opportunity', 'customsearch_blackfriday');
s.addFilter(new nlobjSearchFilter(...));
s.setIsPublic(true);
s.saveSearch('My new opp search', 'customsearch_blackfriday');
Example 2
This sample shows how to load an existing search, create a new search based on existing
criteria, define additional criteria, and then save the search as a new search.
var search = nlapiLoadSearch('opportunity', 'customsearch_blackfriday');
var newSearch = nlapiCreateSearch(search.getSearchType(), search.getFilters(),
search.getColumns());
newSearch.addFilter(new nlobjSearchFilter(...));
newSearch.setIsPublic(true);
newSearch.saveSearch('My new opp search', 'customsearch_blacksaturday');
Example 3
With the type parameter optional, developers have the flexibility to load existing searches, or
execute new or existing searches without knowing the record type of the search.
In the following figure, a user selects a saved search from a custom saved search field. As a
developer, you can have a user event script that loads or re-executes the selected search once
the user saves the record. In this scenario, your script does not have access to the record type of
the saved search. Your code has access only to the saved search ID, which is the value of My
Saved Search Field. Once you get the ID of the search, you can then pass in the ID to either
nlapiLoadSearch(...) or nlapiSearchRecord(...), depending on whether you want to load an
existing search or re-execute it.
The snippet shows how to get the ID of the saved search and then re-execute it, without having
to specify the record type of the search.
Important: If you do not specify the search type, you must set type to null and then set
the search ID.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Search APIs
507
var searchID = nlapiGetFieldValue('custentity_mysavedsearch');
var results = nlapiSearchRecord(null, searchID);
Back to Search APIs | Back to SuiteScript Functions
nlapiLookupField(type, id, fields, text)
See nlapiLookupField(type, id, fields, text) - also listed in the section Field APIs.
Back to Search APIs | Back to SuiteScript Functions
nlapiSearchDuplicate(type, fields, id)
Performs a search for duplicate records based on the account's Duplicate Detection
configuration. Note that this API only works for records that support duplicate record
detection. These records include customers, leads, prospects, contacts, partners, and vendors.
This API is supported in client, user event, scheduled, portlet, and Suitelet scripts.
Parameters
•
type {string} [required] - The record internal ID name you are checking duplicates for
(for example, customer|lead|prospect|partner|vendor|contact). In the NetSuite Help
Center, see SuiteScript Supported Records.
•
fields {string[]} [optional] - The internal ID names of the fields used to detect duplicate
(for example, companyname|email|name|phone|address1|city|state|zipcode).
Depending on the use case, fields may or may not be a required argument. If you are
searching for duplicates based on the fields that appear on a certain record type, fields
would be a required argument. If you are searching for the duplicate of a specific
record (of a specifed type), you would set id and not set fields.
•
id {int} [optional] - internalId of existing record. Depending on the use case, id may or
may not be a required argument. If you are searching for a specific record of a specified
type, you must set id. If you are searching for duplicates based on field names, you will
not set id; you will set fields.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Search APIs
508
Returns
•
{nlobjSearchResult[]} - An Array of nlobjSearchResult objects corresponding to the
duplicate records. Important: Results are limited to 1000 records. Note that if there are
no search results, null is returned.
Example
The following example performs a duplicate detection search for all customer records using the
“email” field of the currently submitted record.
var fldMap = new Array();
fldMap['email'] = nlapiGetFieldValue('email')
var duplicateRecords = nlapiSearchDuplicate( 'customer', fldMap );
for ( var i = 0; i < duplicateRecords.length; i++ )
{
var duplicateRecord = duplicateRecords[ i ];
var record = duplicateRecord.getId( );
var rectype = duplicateRecord.getRecordType( );
}
Back to Search APIs | Back to SuiteScript Functions
nlapiSearchGlobal(keywords)
Performs a global search against a single keyword or multiple keywords. This API is supported
in client, user event, scheduled, portlet, and Suitelet scripts. Usage metering allowed for
nlapiSearchGlobal is 10 units.
Parameters
•
keywords {string} [required] - Global search keywords string or expression
Returns
•
{nlobjSearchResult[]} - An Array of nlobjSearchResult objects containing the
following four columns: name, type (as shown in the UI), info1, and info2.
Important: Results are limited to 1000 rows. Note that if there are no search results,
null is returned.
Example
The following example performs a global search for all records with the keyword simpson.
var searchresults = nlapiSearchGlobal( 'simpson' );
for ( var i = 0; i < searchresults.length; i++ )
{
var searchresult = searchresults[ i ];
var record = searchresult.getId( );
var rectype = searchresult.getRecordType( );
SuiteScript Developer and Reference Guide
SuiteScript Functions
Search APIs
509
var name = searchresult.getValue( 'name' );
var type = searchresult.getValue( 'type' );
var info1 = searchresult.getValue( 'info1' );
var info2 = searchresult.getValue( 'info2' );
}
In the UI, the results returned from the snippet would look similar to the following:
[UE=HELP_TOPIC_OUT_OF_DATE_ALERT=UE]
Note that as with global search functionality in the UI, you can programmatically filter the
global search results that are returned. In the snippet above, if your first line of code looked like
this:
var searchresults = nlapiSearchGlobal( 'cu: simpson' );
only the three Abe Simpson customer records will be returned in your search. For more general
information about global search in NetSuite, see Global Search in the NetSuite Help Center.
Back to Search APIs | Back to SuiteScript Functions
nlapiSearchRecord(type, id, filters, columns)
Performs a search using a set of criteria (your search filters) and columns (the results).
Alternatively, you can use this API to execute an existing saved search. Results are limited to
1000 rows. Also note that in search/lookup operations, long text fields are truncated at 4,000
characters. Usage metering allowed for nlapiSearchRecord is 10 units.
This API is supported in client, user event, scheduled, portlet, and Suitelet scripts.
Note: This API can also be used to search custom lists. In the NetSuite Help Center, see
Searching Custom Lists for an example.
You can extract the desired information from the search results using the methods available on
the returned nlobjSearchResult object.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Search APIs
510
Note that results returned by nlapiSearchRecord are not sortable. However, you can
accomplish sorting using either of the following methods:
1.
Reference a saved search that is sorted by internalid or internalidnumber
2.
Sort the array of results that is returned in JavaScript using a custom Array sorting
function. See the topic called “Creating, displaying, and sorting an array” at
http://developer.mozilla.org/
Note: This function is agnostic in terms of its filters argument. It can accept input of either
a search filter (nlobjSearchFilter), a search filter list (nlobjSearchFilter[]), or a search
filter expression (Object[]).
Parameters
•
type {string} [optional] - The record internal ID of the record type you are searching.
For a list of internal IDs, in the NetSuite Help Center see SuiteScript Supported
Records.
•
id {int | string} [optional] - The internalId or custom scriptId for the saved search. To
obtain the internalId, go to Lists > Search > Saved Searches. The internalId appears in
the Internal ID column. If you have created a custom scriptId when building your
search, this ID will appear in the ID column.
Note the following about how this argument is validated:
• If the internalId or scriptId is valid, the saved search is executed (assuming the
search has no user or role restrictions applied to it).
• If you do not specify the search type, the id parameter becomes REQUIRED. In
this case, you must set type to null and then specify the scriptId for the saved
search. See Example 3 for an example of when and type you might create this type
of script.
• If there is no internalId or scriptId (null or empty string or left out altogether), an
ad-hoc search will be executed and this argument will be ignored.
• If the internalId or scriptId is invalid, the following user error is thrown: That
search or mass updates does not exist.
•
filters {nlobjSearchFilter | nlobjSearchFilter[] | Object[]} [optional] - A single
nlobjSearchFilter object - or - an array of nlobjSearchFilter objects - or - a search filter
expression.
Note: You can further filter the returned saved search by passing additional filter
values.
•
columns {nlobjSearchColumn or nlobjSearchColumn[]} [optional] - A single
nlobjSearchColumn object - or - an array of nlobjSearchColumn objects. Note that
you can further filter the returned saved search by passing additional search return
column values.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Search APIs
511
Returns
•
{nlobjSearchResult[]} - An array of nlobjSearchResult objects corresponding to the
searched records.
Important: The array returned by this API is read-only. Note that if there are no
search results, null is returned.
Throws
•
SSS_INVALID_RECORD_TYPE
•
SSS_TYPE_ARG_REQD
•
SSS_INVALID_SRCH_ID
•
SSS_INVALID_SRCH_FILTER
•
SSS_INVALID_SRCH_FILTER_JOIN
•
SSS_INVALID_SRCH_OPERATOR
•
SSS_INVALID_SRCH_COL_NAME
•
SSS_INVALID_SRCH_COL_JOIN
•
SSS_INVALID_SRCH_FILTER_EXPR
•
SSS_INVALID_SRCH_FILTER_EXPR_DANGLING_OP
•
SSS_INVALID_SRCH_FILTER_EXPR_OBJ_TYPE
•
SSS_INVALID_SRCH_FILTER_EXPR_PAREN_DEPTH
•
SSS_INVALID_SRCH_FILTER_LIST_PARENS
•
SSS_INVALID_SRCH_FILTER_LIST_TERM
Examples
For code samples showing the kinds of searches you can execute using the nlapiSearchRecord
function, see Search Samples in the NetSuite Help Center. If you are new to searching with
SuiteScript, also see Searching Overview.
Back to Search APIs | Back to SuiteScript Functions
nlobjSearchColumn
See nlobjSearchColumn - defined in the section on Standard Objects.
Back to Search APIs | Back to SuiteScript Functions
SuiteScript Developer and Reference Guide
SuiteScript Functions
Scheduling APIs
512
nlobjSearchFilter
See nlobjSearchFilter - defined in the section on Standard Objects.
Back to Search APIs | Back to SuiteScript Functions
nlobjSearchResult
See nlobjSearchResult - defined in the section on Standard Objects.
Back to Search APIs | Back to SuiteScript Functions
Scheduling APIs
The scheduling APIs are used to start, gather information about, and pause, scripts until a
more appropriate time.
•
nlapiScheduleScript(scriptId, deployId, params)
•
nlapiSetRecoveryPoint()
•
nlapiYieldScript()
For a complete overview of working with scheduled scripts in NetSuite, see Scheduled Scripts.
nlapiScheduleScript(scriptId, deployId, params)
Schedules a long-running script for immediate execution if its current status appears as
Completed or Not Scheduled on the Script Deployment page. If the deployment status is set to
Scheduled, the script cannot be executed immediately. The script will run at the time(s)
specified on the Script Deployment page.
The nlapiScheduleScript API consumes 20 units per call. This API is supported in user event,
scheduled, and Suitelet scripts.
Important: There is no unit metering if you are re-queueing the current script (see
Example 1 - Rescheduling a Script). Note, however, nlapiScheduleScript is still
20 units per call if you are trying to schedule other scripts.
One or more calls to nlapiScheduleScript can be made from Suitelet, User Event, and Portlet
scripts. Note that you can also call nlapiScheduleScript from within a scheduled script to:
1.
place the currently executing scheduled script back into the scheduled script
workqueue.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Scheduling APIs
513
2.
call another scheduled script. When the new script is called, it is then put in the
scheduled script workqueue.
3.
place a scheduled script into the queue from another script type, such as a user event
script or a suitelet.
Note: Only administrators can run scheduled scripts. If a user event script calls
nlapiScheduleScript, the user event script has to be deployed with admin
permissions.
For additional details on running scheduled scripts in NetSuite, see Scheduled Scripts.
Parameters
•
scriptId {string | int} [required] - The script internalId or custom scriptId
•
deployId {string | int} [optional] - The deployment internal ID or script ID. If empty,
the first “free” deployment will be used. Free means that the script’s deployment status
appears as Not Scheduled or Completed. If there are multiple “free” scripts, the
NetSuite scheduler will take the first free script that appears in the scheduling queue.
Important: deployId is a required argument if you are calling nlapiScheduleScript to
requeue a scheduled script that is currently executing. This argument is also required
if, from within a scheduled script, you are calling nlapiScheduleScript to queue another
scheduled script that may be multiple deployments (and therefore multiple
deployment IDs). In this case you must specify which of the script’s deployments you
want to schedule.
•
params {Object} [optional] - Object of name/values used in this schedule script
instance - used to override the script parameters values for this execution.
Note that name values are the script parameter internal IDs. If you are not familiar
with what a script parameter is in the context of SuiteScript, see Creating Script
Parameters Overview in the NetSuite Help Center.
Returns
•
A string whose value is QUEUED if the script was successfully queued by this call, or it
returns the script's current status. Valid status values are:
• INQUEUE - The script you requested is already in a queue and waiting to be run.
This script cannot be requested again until it finishes processing. If the script is
INQUEUE, you must try again later if you want to run the script.
• INPROGRESS - The scheduled script is currently running.
• SCHEDULED - The script’s deployment status is set to scheduled and will be
picked up and put into the execution queue.
Important: This API returns NULL if the scheduled script is undeployed or invalid.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Scheduling APIs
514
Example 1 - Rescheduling a Script
Use nlapiScheduleScript, nlobjContext.getScriptId() and nlobjContext.getDeploymentId() to
reschedule the currently executing scheduled script if there are more sales orders to update
when the unit usage limit is reached.
Important: There is no unit metering if you are re-queueing the current script. In the
following sample, for example, nlapiScheduleScript consumes no units. Note, however, that
nlapiScheduleScript is still 20 units per call if you are trying to schedule other scripts.
function updateSalesOrders()
{
var context = nlapiGetContext();
var searchresults = nlapiSearchRecord('salesorder', 'customscript_orders_to_update')
if ( searchresults == null )
return;
for ( var i = 0; i < searchresults.length; i++ )
{
nlapiSubmitField('salesorder', searchresults[i].getId(), 'custbody_approved', 'T')
if ( context.getRemainingUsage() <= 0 && (i+1) < searchresults.length )
{
var status = nlapiScheduleScript(context.getScriptId(), context.getDeploymentId())
if ( status == 'QUEUED' )
break;
}
}
}
Example 2
See more examples in the section Scheduled Script Samples.
Back to Scheduling APIs | Back to SuiteScript Functions
nlapiSetRecoveryPoint()
Creates a recovery point saving the state of the script’s execution. When NetSuite resumes the
execution of the script, it resumes the script at the specified recovery point. Also note that
when the script is resumed, its governance units are reset. Be aware, however, all scheduled
scripts have a 50 MB memory limit. For complete details on scheduled script memory limits,
see Understanding Memory Usage in Scheduled Scripts.
A typical implementation for this API might be as follows. Based on the status returned by
nlapiSetRecoveryPoint(), the script executes different logic.
res = nlapiSetRecoveryPoint()
if (res.status == ‘FAILURE’)
examine the reason and either cleanup/try again OR exit
else if (res.status == ‘SUCCESS’)
do X
SuiteScript Developer and Reference Guide
SuiteScript Functions
Scheduling APIs
515
else if (res.status == ‘RESUME’)
examine the reason and react appropriately
do Z
do A
Note you can use nlapiSetRecoveryPoint() in conjunction with nlapiYieldScript() to effectively
pause the script until a later time when it is more appropriate to run the script.
Important: This API can only be called from scheduled scripts; calling this API from any
other script type will result in an error.
The nlapiSetRecoveryPoint() API consumes 100 units per call.
For an overview of possible use cases for setting recovery points in your scheduled scripts, see
Setting Recovery Points in Scheduled Scripts.
Returns
•
Native Javascript Object
• status {string}
•
SUCCESS – Save point was created.
•
FAILURE – The recovery point was unable to be created. Returns the reason
for the failure and the footprint size of the script.
•
RESUME – Script is being resumed.
• reason {string}
•
SS_NLAPIYIELDSCRIPT - Yield was called.
•
SS_ABORT -The JVM unintentionally stopped (native error, no response,
etc.) --mimics normal "ABORT" states.
•
SS_MAJOR_RELEASE – A major NetSuite release is pending, processes are
being stopped.
•
SS_EXCESSIVE_MEMORY_FOOTPRINT – The saved object is too big.
•
SS_CANCELLED – A user requested that the script stop.
•
SS_DISALLOWED_OBJECT_REFERENCE – The script is attempting to
serialize an object that is not serializable (see Supported Objects).
• size {integer} – The size of the saved object.
• information {string} – Additional information about the status.
Important: If an nlapiYieldScript() or nlapiSetRecoveryPoint() returns a FAILURE with
SS_DISALLOWED_OBJECT_REFERENCE, the object type will be stored in the information
property. To fix this problem, find the offending reference and set it to null.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Scheduling APIs
516
Supported Objects:
All JavaScript native types, plus:
•
nlobjConfiguration
•
nlobjContext
•
nlobjFile
•
nlobjRecord
•
nlobjSubrecord
•
nlobjSearchColumn
•
nlobjSearchFilter
•
nlobjSearchResult
•
nlobjSearchResultCell
•
all 3rd party XML Library objects
Important: All other object types are not supported.
Example – Setting a recovery point, handling errors, and resuming a script
The following sample shows a scheduled script that runs a customer search. The script iterates
through the results of the customer search, and after every five records, sets a recovery point. If
there is an unexpected server failure, the script will resume from the current "i" index of the
search results.
Note: The handleCustomer(...) function in this script is not defined. The function is there only
to demonstrate generic processing you could do with search results.
This script also checks the governance of the script. If the script goes above the governance
threshold, the script is yielded. Based on the status returned by setRecoveryPoint(), an
execution log is created to document the reason this scrip was resumed. And based on the
reason, a more descriptive text message is thrown to the user. Note that if the reason is
SS_EXCESSIVE_MEMORY_FOOTPRINT the cleanUpMemory() function is executed and an
additional recovery point is set.
function runScheduledScript(status, queueid)
{
var records = nlapiSearchRecord('customer', 15);
for( var i = 0; i < records.length; i++ )
{
handleCustomer(records[i].getRecordType(), records[i].getId());
if( (i % 5) == 0 ) setRecoveryPoint(); //every 5 customers, we want to set a recovery point so that, in case of an
unexpected server failure, we resume from the current "i" index instead of 0
SuiteScript Developer and Reference Guide
SuiteScript Functions
Scheduling APIs
517
checkGovernance();
}
}
function setRecoveryPoint()
{
var state = nlapiSetRecoveryPoint(); //100 point governance
if( state.status == 'SUCCESS' ) return; //we successfully create a new recovery point
if( state.status == 'RESUME' ) //a recovery point was previously set, we are resuming due to some unforeseen
error
{
nlapiLogExecution("ERROR", "Resuming script because of " + state.reason+". Size = "+ state.size);
handleScriptRecovery();
}
else if ( state.status == 'FAILURE' ) //we failed to create a new recovery point
{
nlapiLogExecution("ERROR","Failed to create recovery point. Reason = "+state.reason + " / Size = "+
state.size);
handleRecoveryFailure(state);
}
}
function checkGovernance()
{
var context = nlapiGetContext();
if( context.getRemainingUsage() < myGovernanceThreshold )
{
var state = nlapiYieldScript();
if( state.status == 'FAILURE'
{
nlapiLogExecution("ERROR","Failed to yield script, exiting: Reason = "+state.reason + " / Size = "+
state.size);
throw "Failed to yield script";
}
else if ( state.status == 'RESUME' )
{
nlapiLogExecution("AUDIT", "Resuming script because of " + state.reason+". Size = "+ state.size);
}
// state.status will never be SUCCESS because a success would imply a yield has occurred. The equivalent
response would be yield
}
}
function handleRecoverFailure(failure)
{
if( failure.reason == 'SS_MAJOR_RELEASE" ) throw "Major Update of NetSuite in progress, shutting down all
processes";
if( failure.reason == 'SS_CANCELLED' ) throw "Script Cancelled due to UI interaction";
if( failure.reason == 'SS_EXCESSIVE_MEMORY_FOOTPRINT ) { cleanUpMemory(); setRecoveryPoint(); }//
avoid infinite loop
if( failure.reason == 'SS_DISALLOWED_OBJECT_REFERENCE' ) throw "Could not set recovery point
because of a reference to a non-recoverable object: "+ failure.information;
}
SuiteScript Developer and Reference Guide
SuiteScript Functions
Scheduling APIs
518
function cleanUpMemory(){...set references to null, dump values seen in maps, etc}
Back to Scheduling APIs | Back to SuiteScript Functions
nlapiYieldScript()
Creates a recovery point and then reschedules the script. The newly rescheduled script has its
governance units reset, and is then placed at the back of the scheduled script queue. To
summarize, nlapiYieldScript works as follows:
1.
Creates a new recovery point.
2.
Creates a new scheduled script with a governance reset.
3.
Associates the recovery point to the scheduled script
4.
Puts the script at the back of the scheduled script queue.
Note: If the yield call fails, a FAILURE status will be returned. On success, the call does
not return until the script is resumed.
Calling this function consumes no governance units. Note also, calling this API resets the unit
counter for the currently executing script. Be aware, however, all scheduled scripts have a 50
MB memory limit. Calling this API will not reset the memory size of the script to 0. It only
resets the governance units. For complete details on scheduled script memory limits, see
Understanding Memory Usage in Scheduled Scripts.
Important: This API can only be called from scheduled scripts. Calling this API from any
other script type will result in an error.
Returns
•
Native Javascript Object
• status {string}
•
FAILURE – The recovery point was unable to be created. Returns the reason
for the failure and the footprint size of the script.
•
RESUME – Script is being resumed.
• reason {string}
•
SS_NLAPIYIELDSCRIPT - Yield was called.
•
SS_ABORT -The JVM unintentionally stopped (native error, no response,
etc.) --mimics normal "ABORT" states.
•
SS_MAJOR_RELEASE – A major NetSuite release is pending, processes are
being stopped.
•
SS_EXCESSIVE_MEMORY_FOOTPRINT – The saved object is too big.
•
SS_CANCELLED – A user requested that the script stop.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Execution Context APIs
•
519
SS_DISALLOWED_OBJECT_REFERENCE – The script is attempting to
serialize an object that is not serializable (see Supported Objects).
• size {integer} – The size of the saved object.
• information {string} – Additional information about the status.
Important:
•
Be careful if using this API within try / catch / finally. On a successful yield, all the
finally blocks will be called, but catches will be ignored.
•
It is advisable to use the finally block for code which is not going to affect program
flow, for example - writing log entries.
•
If you have a yield in the try block, it is possible that some instructions in the finally
block will execute before the yield takes place. The same instructions will execute again
on resume.
Back to Scheduling APIs | Back to SuiteScript Functions
Execution Context APIs
Context APIs are used to get system information or metadata about a script that is running, a
user in a NetSuite account, or certain settings that have been applied to account.
All APIs listed below are in alphabetical order.
•
nlapiGetContext()
•
nlapiGetDepartment()
•
nlapiGetLocation()
•
nlapiGetRole()
•
nlapiGetSubsidiary()
•
nlapiGetUser()
•
nlapiLogExecution(type, title, details)
•
nlobjContext
nlapiGetContext()
Used to branch scripts depending on the metadata or context of the execution. For example,
you may want the script to perform in one way when a form is accessed via the UI and another
when the form is accessed via Web services.
This API is supported in client, user event, scheduled, portlet, and Suitelet scripts.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Execution Context APIs
520
Returns
•
nlobjContext object containing information (metadata) about the current user or
script context.
You must use the nlobContext.getSetting method on nlapiGetContext to reference script
parameters. For example, to obtain the value of a script parameter called custscript_case_field,
you must use the following code:
nlapiGetContext().getSetting('SCRIPT', 'custscript_case_field')
Specifying Web Services Context
To cause a form to behave differently in Web Services versus the UI, you can do one of the
following:
•
Write context-specific SuiteScript code and use the nlapiGetContext function to
branch the code
•
Disable SuiteScript in Web services
However, both Client and Server SuiteScripts are written to enforce customized business rules
that may need to be enforced regardless of the mechanism by which a record is created or
updated within NetSuite. This is particularly true for customers who deploy a SuiteCloud
partner application and want to be sure their business rules are still respected. Since Client
SuiteScript often has browser-specific behavior that requires user action and cannot
automatically run during a Web Services call, NetSuite recommends that you disable Client
SuiteScript and deploy Server SuiteScript for those business conditions that need to be
enforced in all cases.
To specify that Server SuiteScript should never execute during a Web services call, enable the
Disable Server-side Scripting preference on the Web Services Preference page at Setup >
Integration > Web Services.
Important: Only enable this preference when data submitted via Web services does NOT
need to adhere to custom business logic and workflows that may be executed via Server
SuiteScript.
Back to Execution Context APIs | Back to SuiteScript Functions
nlapiGetDepartment()
This API is supported in client, user event, scheduled, portlet, and Suitelet scripts.
Returns
•
The integer value of the current user’s department (for example, 3, 9, or 1)
SuiteScript Developer and Reference Guide
SuiteScript Functions
Execution Context APIs
521
Back to Execution Context APIs | Back to SuiteScript Functions
nlapiGetLocation()
Returns the integer value of the current user’s location. This API is supported in client, user
event, scheduled, portlet, and Suitelet scripts.
Returns
•
The integer value of the current user’s location (for example, 5, 7, -2). Note that if a
location has not been set, the value of -1 is returned.
Back to Execution Context APIs | Back to SuiteScript Functions
nlapiGetRole()
Returns the internalId for the current user's role. This API is supported in client, user event,
scheduled, portlet, and Suitelet scripts.
Returns
•
The integer value of the current user’s role (for example: 1, 3, or 5). Note that the value
of -31 is returned if a user cannot be properly identified by NetSuite. This occurs when
the user has not authenticated to NetSuite, for example when using externally available
(Available without Login) Suitelets or online forms.
Back to Execution Context APIs | Back to SuiteScript Functions
nlapiGetSubsidiary()
Returns the internalId for the current user's subsidiary. This API is supported in client, user
event, scheduled, portlet, and Suitelet scripts.
Returns
•
The integer value for the current user’s subsidiary (for example 1, 3, or 5). Note that if a
subsidiary has not been set (for example, the subsidiaries feature is not turned on in
the user’s account), the value of 1 is returned if this function is called.
Back to Execution Context APIs | Back to SuiteScript Functions
nlapiGetUser()
Returns the internalId of the current NetSuite user. This API is supported in client, user event,
scheduled, portlet, and Suitelet scripts.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Execution Context APIs
522
Returns
•
The integer value of the current user (for example, 195, 25, 21). Note that the value of
-4 is returned if a user cannot be properly identified by NetSuite. This occurs when the
user has not authenticated to NetSuite, for example when using externally available
(Available without Login) Suitelets or online forms.
Example
The following sample shows how to use nlapiGetUser in conjunction with nlapiSendEmail. In
this sample, the internal ID of the currently logged in user is passed to the author argument in
nlapiSendEmail, which is a required argument in this API.
function afterSubmitEmail(type)
{
//User event script deployed to purchase orders.
//Set the afterSubmit type to approve. As soon as the PO is
//approved, an email is sent.
if (type == 'approve')
//Get the user ID of the person approving the PO. This will be the email author.
var userId = nlapiGetUser();
//Send an email to the supervisor, K. Wolfe in this case.
var sendEmail = nlapiSendEmail(userId, 'kwolfe@netsuite.com', 'Purhase Order Notification', 'Purchase
order approved', null, null, 'transaction', null);
}
See also
nlapiSendEmail(author, recipient, subject, body, cc, bcc, records, attachments)
Back to Execution Context APIs | Back to SuiteScript Functions
nlapiLogExecution(type, title, details)
This API is supported in Suitelet, scheduled, portlet, user event, and record-level (global) client
scripts.
Use this API to log an entry on the Execution Log subtab. The Execution Log subtab appears
on the Script Deployment page for a script. See Using the Script Execution Log to learn more
about writing logs to the Execution Log subtab.
Note: When you are debugging a script in the SuiteScript Debugger, log details appear
on the Execution Log tab of the SuiteScript Debugger, NOT the script’s Script
Deployment page.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Execution Context APIs
523
The log type argument is used in conjunction with the Log Level field on the Script
Deployment to determine whether to log an entry on the Execution Log subtab. If a log level is
defined on a Script Deployment, then only nlapiLogExecution calls with a log type equal to or
greater than this log level will be logged. This is useful during the debugging of a script or for
providing useful execution notes for auditing or tracking purposes. See Setting Script
Execution Log Levels for more information using the Log Level field.
Important: Be aware that NetSuite governs the amount of logging that can be done by a
company in any given 60 minute time period. For complete details, see
Governance on Script Logging.
Also note that if the script’s deployment status is set to Released, then the default Log Level is
ERROR. If the status is set to Testing, the default Log Level is DEBUG.
Note: The Execution Log tab also lists notes returned by NetSuite such as error messages.
For additional information on using the Execution Log, see Using the Script
Execution Log in the NetSuite Help Center.
Parameters
•
type {string} [required] - One of the following log types:
• DEBUG
• AUDIT
• ERROR
• EMERGENCY
•
title {string} [optional] - A title used to organize log entries (max length: 99
characters). If you set title to null or empty string (''), you will see the word “Untitled”
appear in your log entry.
•
details {string} [optional] - The details of the log entry (max length: 3000 characters)
Throws
•
SSS_MISSING_REQD_ARGUMENT - if no value is specified for title.
Returns
•
void
Example 1
This sample creates a new Customer record. When this script runs, execution details are logged
on the Execution Log subtab on the Script Deployment page.
//Create a new Customer record
var newCust = nlapiCreateRecord('customer');
//Set the title field on the Customer record
SuiteScript Developer and Reference Guide
SuiteScript Functions
UI Builder APIs
524
newCust.setFieldValue('title', 'My New Customer');
var custId = nlapiSubmitRecord(newCust, true);
nlapiLogExecution('DEBUG', 'customer record created successfully', 'ID = ' + custId);
Example 2
This snippet shows a search against sales orders, based on specified search filters and search
columns. After the search is complete, the remaining units for the script will be logged on the
Execution Log tab. If you are worried that your script will exceed unit governance limits, it is
useful to track unit usage in the Execution Log.
//Search for the sales orders with trandate of today
var todaySO = nlapiSearchRecord('salesorder', null, todaySOFilters, todaySOColumns);
nlapiLogExecution('DEBUG', 'Remaining usage after searching sales orders from today',
context.getRemainingUsage());
Back to Execution Context APIs | Back to SuiteScript Functions
nlobjContext
See nlobjContext - defined in the section on Standard Objects.
Back to Execution Context APIs | Back to SuiteScript Functions
UI Builder APIs
UI builder APIs allow developers to programmatically create various componets of a the
NetSuite UI (for example, forms, fields, sublists, tabs, portlets). You can also use the UI builder
APIs to create NetSuite-looking assistant wizards.
For more details on working with UI builder APIs, see also UI Objects Overview.
All APIs listed below are in alphabetical order.
•
nlapiCreateAssistant(title, hideHeader)
•
nlapiCreateForm(title, hideNavbar)
•
nlapiCreateList(title, hideNavbar)
•
nlobjAssistant
•
nlobjAssistantStep
•
nlobjButton
SuiteScript Developer and Reference Guide
SuiteScript Functions
UI Builder APIs
•
nlobjColumn
•
nlobjField
•
nlobjFieldGroup
•
nlobjForm
•
nlobjList
•
nlobjPortlet
•
nlobjSubList
•
nlobjTab
525
nlapiCreateAssistant(title, hideHeader)
Use this function to return a reference to an nlobjAssistant object, which is the basis for
building your own custom assistant. This API is supported in Suitelets.
Parameters
•
title {string} [required] - The name of the assistant. This name will appear at the top of
all assistant pages.
•
hideHeader {boolean} [optional] - If not set, defaults to false. If set to true, the header
(navbar/logo) on the assistant is hidden from view.
Returns
•
nlobjAssistant object
Since
•
Version 2009.2
Example
This snippet shows how to call nlapiCreateAssistant to return a reference to the nlobjAssistant
object. With the nlobjAssistant object instantiated, you can then define the steps of the
assistant.
var assistant = nlapiCreateAssistant("Small Business Setup Assistant");
assistant.setOrdered(true); // indicate that all steps must be completed sequentially
assistant.addStep('companyinformation', 'Setup Company Information').setHelpText("Setup your
<b>important</b> company information in the fields below.")
assistant.addStep('entercontacts', 'Enter Contacts').setHelpText("Manually add contacts
into your account.")
SuiteScript Developer and Reference Guide
SuiteScript Functions
UI Builder APIs
526
assistant.addStep('importdata', 'Import Data').setHelpText("Finally, import records
into your account via CSV.);
Back to UI Builder APIs | Back to SuiteScript Functions
nlapiCreateForm(title, hideNavbar)
Creates an nlobjForm object which can be used to generate an entry form page. This API is
available to Suitelets only.
Parameters
•
title {string} [required] - The title for the form
•
hideNavbar {boolean} [optional] - Set to true if the navigation bar should be hidden on
the Suitelet. Setting to true enables “popup page” use cases in which the popup can be
created with the UI Objects API rather than just HTML.
When hideNavbar is set to false, the standard NetSuite navigation appears on the form
or popup. Note that this navigation bar contains links to pages that require users to be
logged in to access.
Returns
•
An nlobjForm object
Back to UI Builder APIs | Back to SuiteScript Functions
nlapiCreateList(title, hideNavbar)
Creates an nlobjList object used to generate an internal standalone list. This API is available to
Suitelets only.
SuiteScript Developer and Reference Guide
SuiteScript Functions
UI Builder APIs
527
Parameters
•
title {string} [required] - The title for the list
•
hideNavbar {boolean} [optional] - Set to true if the navigation bar should be hidden on
the Suitelet. Setting to true enables “popup page” use cases in which the popup can be
created with the UI Objects API rather than just HTML.
When hideNavbar is set to false, the standard NetSuite navigation appears on the form
or popup. Note that this navigation bar contains links to pages that require users to be
logged in to access.
Returns
•
An nlobjList object
Back to UI Builder APIs | Back to SuiteScript Functions
nlobjAssistant
See nlobjAssistant - defined in the section on UI Objects.
Back to UI Builder APIs | Back to SuiteScript Functions
nlobjAssistantStep
See nlobjAssistantStep - defined in the section on UI Objects.
Back to UI Builder APIs | Back to SuiteScript Functions
nlobjButton
See nlobjButton - defined in the section on UI Objects.
Back to UI Builder APIs | Back to SuiteScript Functions
nlobjColumn
See nlobjColumn - defined in the section on UI Objects.
Back to UI Builder APIs | Back to SuiteScript Functions
SuiteScript Developer and Reference Guide
SuiteScript Functions
UI Builder APIs
nlobjField
See nlobjField - defined in the section on UI Objects.
Back to UI Builder APIs | Back to SuiteScript Functions
nlobjFieldGroup
See nlobjFieldGroup - defined in the section on UI Objects.
Back to UI Builder APIs | Back to SuiteScript Functions
nlobjForm
See nlobjForm - defined in the section on UI Objects.
Back to UI Builder APIs | Back to SuiteScript Functions
nlobjList
See nlobjList - defined in the section on UI Objects.
Back to UI Builder APIs | Back to SuiteScript Functions
nlobjPortlet
See nlobjPortlet - defined in the section on UI Objects.
Back to UI Builder APIs | Back to SuiteScript Functions
nlobjSubList
See nlobjSubList - defined in the section on UI Objects.
Back to UI Builder APIs | Back to SuiteScript Functions
nlobjTab
See nlobjTab - defined in the section on UI Objects.
SuiteScript Developer and Reference Guide
528
SuiteScript Functions
Application Navigation APIs
529
Back to UI Builder APIs | Back to SuiteScript Functions
Application Navigation APIs
The following APIs let you define a navigation path for your users within NetSuite. Through
these APIs you can redirect users to other standard or custom records within NetSuite. You can
also direct them to custom Suitlets or other web sites outside of NetSuite.
All APIs listed below are in alphabetical order.
•
nlapiRequestURL(url, postdata, headers, callback, httpMethod)
•
nlapiResolveURL(type, identifier, id, displayMode)
•
nlapiSetRedirectURL(type, identifier, id, editmode, parameters)
•
nlobjRequest
•
nlobjResponse
nlapiRequestURL(url, postdata, headers, callback, httpMethod)
Requests an HTTP(s) URL (internal or external). Note a timeout occurs if the initial
connection takes > 5 seconds and/or the request takes > 45 to respond.
nlapiRequestURL(...) automatically encodes binary content using base64 representation, since
JavaScript is a character-based language with no support for binary types. This means you can
take the contents returned and save them in the NetSuite file cabinet as a file or stream them
directly to a response.
Also note that if you call nlapiRequestURL(...), passing in the header with a content type,
NetSuite respects only the following two types:
•
"application/json"
•
"application/soap+xml"
Otherwise, NetSuite will overwrite the content type with our default type as if the type had not
been specified. NetSuite default types are:
•
"text/xml; charset=UTF-8"
•
"application/x-www-form-urlencoded; charset=UTF-8"
Additionally, nlapiRequestURL(...) calls from the server do not include the current user's
session information. This means you can only use this API to request Suitelets that are set to
available without login using the external URL.
Usage metering allowed is 10 units. This API is supported in client, user event, scheduled,
portlet, and Suitelet scripts.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Application Navigation APIs
530
Parameters
•
url {string} [required] - The HTTP(s) URL being requested - (fully qualified unless
NetSuite page)
•
postdata {string | hashtable} [optional] - Body used for a POST request. It can either be
an associative array of form parameters or a string. If set to null, then a GET request is
used.
•
headers {hashtable} [optional] - An associative array of name (header) value (header
value) pairs
•
callback {function} [optional] - A callback function called when the request is
completed (Client SuiteScript only). If you specifiy a callback in Client SuiteScript, the
request is processed asynchronously, and once it is processed, the callback is called/
invoked.
If you know your request may take a long time and you do not want to impair user
experience, it is recommended that you set the callback function within
nlapiRequestURL so that the request is processed asynchronously. If a callback
function is specified, then the response will be passed, instead to the callback function,
upon completion.
However, if validation is needed, nlapiRequestURL should run synchronously and the
callback function should be omitted from nlapiRequestURL. For example:
var response = nlapiRequestURL(URL, postdata, header);
// callback function outside of the API call - will only execute after
// nlapiRequestURL has processed
function foo(response) {
...
}
•
httpMethod {string} [optional] - Specify the appropriate http method to use for your
integration. Supported http methods are HEAD, DELETE and PUT. This parameter
allows for easier integration with external RESTful services using the standard REST
functions. Note that if the httpMethod parameter is empty or not specified, this
behavior is followed: the method is POST if postdata is not empty. The method is GET
if it is.
Be aware that the httpMethod parameter overrides, so you can specify GET and
specify postdata, NetSuite will do a GET and ignore the postdata.
Returns
•
nlobjResponse object (or void if a callback function has been specified)
Important: NetSuite supports the same list of trusted third-party certificate authorities
(CAs) as Microsoft. Click the following link for a list of these CAs:
http://social.technet.microsoft.com/wiki/contents/articles/1658.windows-rootcertificate-program-members.aspx
SuiteScript Developer and Reference Guide
SuiteScript Functions
Application Navigation APIs
531
Throws
•
SSS_REQUEST_TIME_EXCEEDED (if the connection exceeds the 45 second timeout
period)
Example 1
Request an XML document from a server and also include a header.
var a = new Array();
a['User-Agent-x'] = 'SuiteScript-Call';
var response = nlapiRequestURL( 'https://webservices.netsuite.com/wsdl/v1_2_0/netsuite.wsdl', null, a );
var body = response.getBody();
var headers = response.getAllHeaders();
Example 2
The next example shows how to make an asynchronous request.
var a = new Array();
a['User-Agent-x'] = 'SuiteScript-Call';
nlapiRequestURL( 'https://webservices.netsuite.com/wsdl/v1_2_0/netsuite.wsdl', null, a, handleResponse);
function handleResponse( response )
{
var headers = response.getAllHeaders();
var output = 'Code: '+response.getCode()+'\n';
output += 'Headers:\n';
for ( var i in headers )
output += i + ': '+headers[i]+'\n';
output += '\n\nBody:\n\n';
output += response.getBody();
alert( output );
}
Example 3
The final example shows how to make a request using a new browser window.
nlapiRequestURL( 'https://webservices.netsuite.com/wsdl/v1_2_0/netsuite.wsdl', null, a, null);
Back to Application Navigation APIs | Back to SuiteScript Functions
nlapiRequestURLWithCredentials(credentials, url, postdata, headers,
httpMethod)
Allows you to send credentials outside of NetSuite. This API securely accesses a handle to
credentials users specify in a NetSuite credential field.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Application Navigation APIs
532
Note: NetSuite credential fields can be added to Suitelets using the
nlobjForm.addCredentialField(id, label, website, scriptId, value, entityMatch, tab)
method.
Note a timeout occurs if the internal connections takes > 5 seconds and/or the request takes
> 45 seconds to respond.
Also note that if you call nlapiRequestURLWithCredentials(...), passing in the header with a
content type, NetSuite respects only the following two types:
•
"application/json"
•
"application/soap+xml"
Otherwise, NetSuite will overwrite the content type with our default type as if the type had not
been specified. NetSuite default types are:
•
"text/xml; charset=UTF-8"
•
"application/x-www-form-urlencoded; charset=UTF-8"
Usage metering allowed is 10 units. This API is supported in client, user event, scheduled,
portlet, and Suitelet scripts.
Parameters
•
credentials {string} [required] - List of credential handles. This API does not know
where you have stored the data, it only knows the credentials to use by handle.
Therefore, if you have multiple credentials for a single call, you will need a list. The
handles are 32 byte, globally unique strings (GUIDs).
•
url {string} [required] - The HTTP(s) URL being requested - (fully qualified unless
NetSuite page)
•
postdata {string | hashtable} [optional] - Body used for a POST request. It can either be
an associative array of form parameters or a string. If set to null, then a GET request is
used.
•
headers {hashtable} [optional] - An associative array of name (header) value (header
value) pairs
•
httpMethod {string} [optional] - Specify the appropriate http method to use for your
integration. Supported http methods are HEAD, DELETE and PUT. This parameter
allows for easier integration with external RESTful services using the standard REST
functions. Note that if the httpMethod parameter is empty or not specified, this
behavior is followed: the method is POST if postdata is not empty. The method is GET
if it is.
Be aware that the httpMethod parameter overrides, so you can specify GET and
specify postdata, NetSuite will do a GET and ignore the postdata.
Returns
•
nlobjResponse object
SuiteScript Developer and Reference Guide
SuiteScript Functions
Application Navigation APIs
533
Since
•
Version 2012.1
Example
The following shows a general process for creating credential fields and then, later, getting their
handles and passing them on using nlapiRequestURLWithCredentials(...).
1. Two custom fields with username and passwords are added to a form:
var credField = form.addCredentialField('custpage_credname', 'password', null, valueFromCustomField,
'cert.merchante-solutions.com', 'customscript_usecredentialfield');
var usrfield = form.addCredentialField('custpage_username', 'username', null, valuefromusernamecustfield,
'cert.merchante-solutions.com', 'customscript_usecredentialfield');
2. During a beforeSubmit user event, we obtain the values from credential fields and store them
in two custom fields, which are not visible on the form:
var credValue = nlapiGetFieldValue('custpage_credname');
var username = nlapiGetFieldValue('custpage_username');
nlapiSetFieldValue('custentity_custompassword', credValue);
nlapiSetFieldValue('custentity_customusername', username);
3. Before using the credentials, we copy them as a list in a variable. At this point, uname and
pwd will contain the GUIDS (credentials handle):
var uname = rec.getFieldValue('custentity_customusername');
var pwd = rec.getFieldValue('custentity_custompassword');
var creds = [uname, pwd];
4. Use credentials in an external call:
var connect = nlapiRequestURLWithCredentials(creds, url);
Back to Application Navigation APIs | Back to SuiteScript Functions
nlapiResolveURL(type, identifier, id, displayMode)
Creates a URL on-the-fly by passing URL parameters from within your SuiteScript. For
example, when creating a SuiteScript Portlet script, you may want to create and display the
record URLs for each record returned in a search.
When creating the URL, you can use either the RECORD reference as retrieved in a search
result or a known TASKLINK. Each page in NetSuite has a unique Tasklink Id associated with
it for a given record type. Refer to the SuiteScript Reference Guide for a list of available NetSuite
tasklinks.
This API is supported in client, user event, scheduled, portlet, and Suitelet scripts.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Application Navigation APIs
534
Note: You can also discover the Tasklink for a page within NetSuite by viewing the HTML page
source. Search for a string similar to the following, where LIST_SCRIPT refers to the
TASKLINK.
onclick="nlPopupHelp('LIST_SCRIPT','help')
Parameters
•
type {string} [required] - The base type for this resource. These types include:
• RECORD - Record Type
• TASKLINK - Task Link
• SUITELET - Suitelet
•
identifier {string} [required] - The primary id for this resource (recordType for
RECORD, scriptId for SUITELET)
•
id {string} [optional] - The secondary id for this resource (recordId for RECORD,
deploymentId for SUITELET). Important: This argument is required if type has been
set to RECORD and you are trying to resolve to a specific NetSuite record. In the
scenario, you must set id to the id of the target record.
•
displayMode {string | boolean} [optional] - If the type argument is set to RECORD, set
displayMode to either VIEW or EDIT to return a URL for the record in EDIT mode or
VIEW mode. Note that even for RECORD calls, the displayMode argument is optional.
The default value is VIEW.
Important: If the type argument is set to SUITELET, set displayMode to either true or
false to return either an internal or external Suitelet URL. Set to true to return an
external URL. Set to false, or simply omit the argument, to return an internal URL.
For Suitelets, displayMode automatically defaults to false.
Returns
•
Depending on the values specified for the type and displayMode arguments, returns
URL string to an internal NetSuite resource or an external/internal URL to a Suitelet.
Throws
•
SSS_INVALID_URL_CATEGORY
•
SSS_CATEGORY_ARG_REQD
•
SSS_INVALID_TASK_ID
•
SSS_TASK_ID_REQD
•
SSS_INVALID_INTERNAL_ID
•
SSS_INVALID_EDITMODE_ARG
SuiteScript Developer and Reference Guide
SuiteScript Functions
Application Navigation APIs
535
Example
The following lines of code show 5 different approaches for resolving to a record or Suitelet.
//resolve to a new Event record
var url_new_event = nlapiResolveURL('RECORD', 'calendarevent');
//resolve to a specific Event record page in view mode
var url_view_event = nlapiResolveURL('RECORD', 'calendarevent', 1000);
//resolve to a specific Event record in edit mode
var url_edit_event = nlapiResolveURL('RECORD', 'calendarevent', 1000, 'EDIT');
//resolve to a specified tasklink
var url_job_search = nlapiResolveURL('TASKLINK', 'SRCH_JOB');
//resolve to a specific Suitelet by specifying the Suitelet scriptId and deploymentId
var_url_servlet = nlapiResolveURL('SUITELET', 10, 5);
Back to Application Navigation APIs | Back to SuiteScript Functions
nlapiSetRedirectURL(type, identifier, id, editmode, parameters)
Sets the redirect URL by resolving to a NetSuite resource. Note that all parameters must be
prefixed with custparam otherwise an SSS_INVALID_ARG error will be thrown.
This API is supported in user event and Suitelet scripts.
You can use nlapiSetRedirectURL to customize navigation within NetSuite. In a user event
script, you can use nlapiSetRedirectURL to send the user to a NetSuite page based on a specific
user event. For example, under certain conditions you may choose to redirect the user to
another NetSuite page or custom Suitelet to complete a workflow.
Note: You cannot redirect a user to an external URL, unless the type parameter is set to
EXTERNAL. See the documentation for this type (below).
If you redirect a user to a record, the record must first exist in NetSuite. If you want to redirect
a user to a new record, you must first create and submit the record before redirecting them. You
must also ensure that any required fields for the new record are populated before submitting
the record.
Parameters
•
type {string} [required] - The base type for this resource. The types include:
• RECORD: Record type - - Note that when you set type to RECORD, and the third
param (id) to null, the redirection is to the “create new” record page, not an
existing record page.
• TASKLINK: Tasklink
• SUITELET: Suitelet
SuiteScript Developer and Reference Guide
SuiteScript Functions
Application Navigation APIs
536
• EXTERNAL: The URL of a Suitelet that is available externally (for example,
Suitelets that have been set to “Available without Login” on the Script Deployment
page)
•
identifier {string} [required] - The primary id for this resource (recordType for
RECORD, scriptId for SUITELET, taskId for TASKLINK, url for EXTERNAL)
•
id {string} [optional]- The secondary id for this resource (recordId for RECORD,
deploymentId for SUITELET). Important: This argument is required if type has been
set to RECORD and you are trying to redirect to a specific NetSuite record. In the
scenario, you must set id to the id of the target record.
•
editmode {boolean} [optional] - For RECORD calls, this determines whether to return
a URL for the record in edit mode or view mode. If set to true, returns the URL to an
existing record in edit mode. Important: The values for this parameter can be true or
false, not T or F.
•
parameters {hashtable} [optional] - An associative array of additional URL parameters.
Important: All parameters must be prefixed with custparam.
Returns
•
void
Throws
•
SSS_INVALID_ARG
•
SSS_INVALID_URL_CATEGORY
•
SSS_CATEGORY_ARG_REQD
•
SSS_INVALID_TASK_ID
•
SSS_TASK_ID_REQD
•
SSS_INVALID_INTERNAL_ID
•
SSS_INVALID_EDITMODE_ARG
Example 1
The following example sets the redirect URL following the creation of an opportunity to a new
task page. This script executes on an afterSubmit in a user event script.
if ( type == 'create' )
{
var opportunity_id = nlapiGetRecordId();
var params = new Array();
params['opportunity'] = opportunity_id;
nlapiSetRedirectURL('RECORD','task', null, null, params);
}
SuiteScript Developer and Reference Guide
SuiteScript Functions
Date APIs
537
Example 2
This script sets the redirect URL to a newly created task record. Note that the record must exist
and be submitted so the ID from the record can be used to set the redirect. This function is also
executed on an afterSubmit in a user event script.
function redirectTaskRecord()
{
var taskTitle = 'New Opportunity';
var record = nlapiCreateRecord( 'task');
record.setFieldValue( 'title', taskTitle );
id = nlapiSubmitRecord(record, true);
nlapiSetRedirectURL( 'RECORD', 'task', id, false );
}
Back to Application Navigation APIs | Back to SuiteScript Functions
nlobjRequest
See nlobjRequest - defined in the section on Standard Objects.
Back to Application Navigation APIs | Back to SuiteScript Functions
nlobjResponse
See nlobjResponse - defined in the section on Standard Objects.
Back to Application Navigation APIs | Back to SuiteScript Functions
Date APIs
Use these APIs to manipulate standard JavaScript Date and String objects.
All APIs listed below are in alphabetical order.
•
nlapiAddDays(d, days)
•
nlapiAddMonths(d, months)
•
nlapiDateToString(d, format)
•
nlapiStringToDate(str, format)
SuiteScript Developer and Reference Guide
SuiteScript Functions
Date APIs
nlapiAddDays(d, days)
Adds/subtracts a number of days to or from a Date object
Parameters
•
d {date} [required] - Date object
•
days {int} [required] - Number of days being added to the date
Returns
•
Date object corresponding to date that was passed in, plus the days you added or
subtracted
Back to Date APIs | Back to SuiteScript Functions
nlapiAddMonths(d, months)
Adds/subtracts a number of months to or from a Date object
Parameters
•
d {date} [required] - Date object
•
months {int} [required] - number of months being added to the date
Returns
•
Date object corresponding to date that was passed in, plus the months you added or
subtracted
Back to Date APIs | Back to SuiteScript Functions
nlapiDateToString(d, format)
Converts a Date object into a String using the current user's date format
Parameters
•
d {date} [required] - Date object being converted into a String
•
format {string} [optional] - Format type to use: date|timeofday with date being the
default
Returns
•
String format of the date that was passed
Back to Date APIs | Back to SuiteScript Functions
SuiteScript Developer and Reference Guide
538
SuiteScript Functions
Currency APIs
539
nlapiStringToDate(str, format)
Converts a String to a Date object using the current user's NetSuite date format, or to one of the
formats passed in the format parameter. Be aware that leading zeroes in the month and day
values are not supported.
Parameters
•
str {string} [required] - String being converted to a Date
•
format {string} [optional] - Use any one of the following format types:
• datetimetz - converts the date that is passed to a datetimetz format
• timeofday - converts the date that is passed to a timeofday format
• datetime - converts the date that is passed to a datetime format
Returns
•
Date object. Returns NaN if date includes a leading zero.
Example
var myDate = nlapiStringToDate('8.5.2008'); // supported
var myDate = nlapiStringToDate('8/5/2008'); // supported
var myDate = nlapiStringToDate('08.5.2009'); // not supported
var myDate = nlapiStringToDate('08/5/2009'); // not supported
var myDate = nlapiStringToDate('8.05.2009'); // not supported
var myDate = nlapiStringToDate('8/05/2009'); // not supported
Back to Date APIs | Back to SuiteScript Functions
Currency APIs
Use these APIs to work with currency, as it pertains to your NetSuite account.
All APIs listed below are in alphabetical order.
•
nlapiExchangeRate(sourceCurrency, targetCurrency, effectiveDate)
•
nlapiFormatCurrency(str)
nlapiExchangeRate(sourceCurrency, targetCurrency, effectiveDate)
Use this API to get the exchange rate between two currencies based on a certain date. The
exchange rate values you are getting are those that appear in the Exchange Rate column of the
Currency Exchange Rates record (see figure).
SuiteScript Developer and Reference Guide
SuiteScript Functions
Currency APIs
540
Note: The Currency Exchange Rate record itself is not a scriptable record.
The usage metering allowed for this API is 10 units. This API is supported in client, user event,
scheduled, portlet, and Suitelet scripts.
When using this API, the first currency (sourceCurrency) is the one to look up relative to the
second (targetCurrency), which MUST be a base currency. The date (effectiveDate) is the rate in
effect on that date. If there are multiple rates, it is the latest entry on that date.
For example, if you call nlapiExchangeRate('GBP', 'USD', '04/22/2010') and it returns '2', this
means that if you were to enter an invoice on 4/22/10 for a GBP customer in your USD
subsidiary, the rate would be 2.
Parameters
•
sourceCurrency {string|int} [required] - The currency internal ID or symbol. For
example, you can use either 1 (currency ID) or USD (currency symbol). If you have
the Multiple Currencies feature enabled in your account, you can see all currency IDs
and symbols by going to Lists > Accounting > Currencies.
•
targetCurrency {string|int} [required] - The currency internal ID or symbol. Note that
the targetCurrency must be the base currency. For information on setting a base
currency in your NetSuite account, see Setting a Base Currency in the NetSuite Help
Center. If the value you provide for targetCurrency parameter is not the base currency,
null will be returned when the API is executed.
•
effectiveDate {string|int} [optional] - If not supplied, then effectiveDate reflects the
current date.
Returns
•
The exchange rate (as a float) in the same precision that is displayed in the NetSuite UI.
Note that null is returned if the targetCurrency is not set to a base currency.
Throws
•
SSS_INVALID_CURRENCY_ID (if an invalid currency (from or to) is specified)
Since
•
Version 2009.1
SuiteScript Developer and Reference Guide
SuiteScript Functions
Encryption APIs
541
Example
This sample shows how to obtain the exchange rate between the Canadian dollar and the US
dollar on March 17, 2009. The returned rate is applied against the Canadian dollar amount to
obtain the amount in US dollars.
var canadianAmount = 100;
//specify source and target currencies as well as the exchange rate date
var rate = nlapiExchangeRate('CAD', 'USD', '03/17/2009');
var usdAmount = canadianAmount * rate;
Back to Currency APIs | Back to SuiteScript Functions
nlapiFormatCurrency(str)
Formats a String into a currency field value
Parameters
•
str {string} [required] - String being formatted into currency
Returns
•
String
Back to Currency APIs | Back to SuiteScript Functions
Encryption APIs
nlapiEncrypt(s, algorithm, key)
Encrypts a clear text String using a SHA-1 hash function. This is the same encryption used for
password fields.
Parameters
•
s {string} [required] - String being encrypted
•
algorithm {string} [optional] - algorithm to use
•
key {string} [optional] - secret key to use
SuiteScript Developer and Reference Guide
SuiteScript Functions
XML APIs
Algorithm
Description
sha1
Hash function using SHA-1 Algorithm
from NSA (default)
aes
Symmetric encryption using AES
Algorithm
base64
Base-64 encoding
xor
Exclusive-OR obfuscation
Key
128-bit, 192-bit, or 256-bit hex key
Returns
•
String
Back to Encryption APIs | Back to SuiteScript Functions
XML APIs
Use these APIs when working with XML documents.
All APIs listed below are in alphabetical order.
•
nlapiEscapeXML(text)
•
nlapiSelectNode(node, xpath)
•
nlapiSelectNodes(node, xpath)
•
nlapiSelectValue(node, xpath)
•
nlapiSelectValues(node, path)
•
nlapiStringToXML(text)
•
nlapiXMLToString(xml)
•
nlapiXMLToPDF(xmlstring)
nlapiEscapeXML(text)
Prepares a String for use in XML by escaping XML markup (for example, angle brackets,
quotation marks, and ampersands)
Parameters
•
text {string} [required] - String being escaped
Returns
•
String
SuiteScript Developer and Reference Guide
542
SuiteScript Functions
XML APIs
543
Example
In this line, nlapiEscapeXML is being used to escape special characters, such as an ampersand
(&), that may appear in the names of items that are returned in an Item search. For the
complete code sample, see Example 2 in the API documentation for nlapiXMLToPDF.
strName += nlapiEscapeXML(searchresult.getValue( 'name' ) );
Back to XML APIs | Back to SuiteScript Functions
nlapiSelectNode(node, xpath)
Selects a node from an XML document using an XPath expression
Parameters
•
node {node} [required] - XML node being queried
•
xpath {string} [required] - XPath expression used to query node
Returns
•
Node
Back to XML APIs | Back to SuiteScript Functions
nlapiSelectNodes(node, xpath)
Selects an array of nodes from an XML document using an XPath expression
Parameters
•
node {node} [required] - XML node being queried
•
xpath {string} [required] - XPath expression used to query node
Returns
•
Node[]
Back to XML APIs | Back to SuiteScript Functions
nlapiSelectValue(node, xpath)
Selects a value from an XML document using an XPath expression
Parameters
•
node {node} [required] - XML node being queried
SuiteScript Developer and Reference Guide
SuiteScript Functions
XML APIs
•
544
xpath {string} [required] - XPath expression used to query node
Returns
•
String
Back to XML APIs | Back to SuiteScript Functions
nlapiSelectValues(node, path)
Selects an array of values from an XML document using an XPath expression
Parameters
•
node {node} [required] - XML node being queried
•
path {string} [required] - XPath expression used to query node
Returns
•
String[]
Back to XML APIs | Back to SuiteScript Functions
nlapiStringToXML(text)
Parses a String into a w3c XML document. This API is useful if you want to navigate/query a
structured XML document more effectively using either the Document API or NetSuite builtin XPath functions.
Parameters
•
text {string} [required] - String being converted
Returns
•
W3C Document object
Back to XML APIs | Back to SuiteScript Functions
nlapiXMLToString(xml)
Converts (serializes) an XML document into a String. This API is useful if you want to serialize
and store a Document in a custom field (for example).
Parameters
•
xml {W3C Document} [required] - XML document being serialized
SuiteScript Developer and Reference Guide
SuiteScript Functions
XML APIs
545
Returns
•
String
Back to XML APIs | Back to SuiteScript Functions
nlapiXMLToPDF(xmlstring)
Use this API in conjunction with the Big Faceless Report Generator built by Big Faceless
Organization (BFO). The BFO Report Generator is a third-party library used for converting
XML to PDF documents. Using nlapiXMLToPDF in combination with the BFO report library,
SuiteScript developers can now generate PDF reports from Suitelets.
Note: SuiteScript developers do not need to install any BFO-related files or components to use
the Report Generator functionality.
The nlapiXMLToPDF API passes XML to the BFO tag library (which is stored by NetSuite),
and returns a PDF nlobjFile object. Note that there is a 5MB limitation to the size of the file
that can be created.
The following list includes just some of the output styles that can be generated using
nlapiXMLToPDF and BFO tags:
•
Consolidated data from multiple transactions into one (for example, a virtual
consolidated invoice)
•
Highly tailored transaction output with images
•
Product labels with bar codes
•
Pallet labels with bar codes (custom records)
•
Custom-formatted product catalogs with images
•
Proposals
Important: For details on BFO, available tags, and BFO examples, see the following links:
•
http://faceless.org/products/report/docs/userguide.pdf
•
http://faceless.org/products/report/docs/tags/
Parameters
•
xmlstring {string} [required] – XML
Returns
•
PDF nlobjFile object
Throws
•
Error: ERROR_PARSING_XML (thrown as a user error when XML is badly formed)
SuiteScript Developer and Reference Guide
SuiteScript Functions
XML APIs
546
Since
•
Version 2009.1
Example 1
This sample shows how to generate a PDF from a Suitelet. The output is a PDF that reads Hello
World! See also, Working with BFO (the Basics).
function helloWorld()
{
var xml = "<?xml version=\"1.0\"?>\n<!DOCTYPE pdf PUBLIC \"-//big.faceless.org//report\" \"report1.1.dtd\">\n<pdf>\n<body font-size=\"18\">\nHello World!\n</body>\n</pdf>";
var file = nlapiXMLToPDF( xml );
response.setContentType('PDF','helloworld.pdf ');
response.write( file.getValue() );
}
Example 2
This sample shows how to create a PDF of a pricing list. All data for the pricing list is pulled
from NetSuite, organized into tables, and then transformed into a PDF.
function priceListPDF(request, response)
{
// set search filters for pricing list search
var filters = new Array();
// against pricing lists, search for a specific customer
filters [0] = new nlobjSearchFilter('customer', 'pricing', 'is', '121');
// against pricing lists, look for lists that have currency defined as USA
filters [1] = new nlobjSearchFilter('currency', 'pricing', 'is', '1');
// set search return columns for pricing list search
var columns = new Array();
columns[0] = new nlobjSearchColumn('pricelevel', 'pricing');
columns[1] = new nlobjSearchColumn('unitprice', 'pricing');
columns[2] = new nlobjSearchColumn('name');
// when doing a pricing list search you must specify ‘item’ as the search type
var searchresults = nlapiSearchRecord('item', null, null, columns);
// create a table to present the results of the search
var strName = "<table>";
// iterate through the results
for ( var i = 0; searchresults != null && i < searchresults.length; i++ )
{
searchresult = searchresults[ i ];
strName += "<tr><td>";
SuiteScript Developer and Reference Guide
SuiteScript Functions
XML APIs
547
// note the use of nlapiEscapeXML to escape any special characters,
// such as an ampersand (&) in any of the item names
strName += nlapiEscapeXML(searchresult.getValue( 'name' ) );
strName += "</td>";
strName += "<td>";
strName += searchresult.getValue( 'unitprice', 'pricing' );
strName += "</td>";
strName += "<td>";
strName += "<barcode codetype=\"code128\" showtext=\"true\" value=\"";
strName += searchresult.getValue( 'unitprice', 'pricing' );
strName += "\"/>";
strName += "</td></tr>";
}
strName += "</table>";
// build up BFO-compliant XML using well-formed HTML
var xml = "<?xml version=\"1.0\"?>\n<!DOCTYPE pdf PUBLIC \"-//big.faceless.org//
report\" \"report-1.1.dtd\">\n";
xml += "<pdf>\n<body font-size=\"12\">\n<h3>My Pricing List</h3>\n";
xml += "<p></p>";
xml += strName;
xml += "</body>\n</pdf>";
// run the BFO library to convert the xml document to a PDF
var file = nlapiXMLToPDF( xml );
// set content type, file name, and content-disposition (inline means display in browser)
response.setContentType('PDF','Pricing List.pdf ', 'inline');
// write response to the client
response.write( file.getValue() );
}
Example 3
For NetSuite customers who want to print a PDF that includes Cyrillic characters (Russin text),
this sample shows how to point to a Russian font set hosted by NetSuite. To print Russian text,
SuiteScript Developer and Reference Guide
SuiteScript Functions
XML APIs
548
you must include the <link> tag within the <head>. The path in your <link> tag must be the
exact path that is specified here in this sample.
function main(Request, Response)
{
var xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<!DOCTYPE pdf PUBLIC \"-//big.faceless.org//report\" \"report-1.1.dtd\">\n" +
"<pdf lang=\"ru-RU\" xml:lang=\"ru-RU\">\n" +
"<head>\n" +
"<link name=\"russianfont\" type=\"font\" subtype=\"opentype\" " +
"src=\"NetSuiteFonts/verdana.ttf\" " +
"src-bold=\"NetSuiteFonts/verdanab.ttf\" " +
"src-italic=\"NetSuiteFonts/verdanai.ttf\" " +
"src-bolditalic=\"NetSuiteFonts/verdanabi.ttf\" " +
"bytes=\"2\"/>\n" +
"</head>\n" +
"<body font-family=\"russianfont\" font-size=\"18\">\n" +
"<p>Russian: Русский текст</p>\n" +
"<p>Russian Italic: <i>Русский текст</i></p>\n" +
"<p>Russian Bold: <b>Русский текст</b></p>\n" +
"<p>Russian Bold Italic: <b><i>Русский текст</i></b></p>\n" +
"</body>\n" +
"</pdf>";
var file = nlapiXMLToPDF( xml );
Response.setContentType('PDF','helloworld.pdf ', 'inline');
Response.write( file.getValue() );
}
Working with BFO (the Basics)
For convenience, the following basic coding details regarding BFO are here for SuiteScript
developers. For more detailed explanations, see the section called “Creating the XML - A
Simple Example” in the BFO User Guide (http://faceless.org/products/report/docs/
userguide.pdf).
1.
The XML declaration <?xml version="1.0"?> must always be included as the very first
line of the file.
2.
The DOCTYPE declaration tells the XML parser which DTD to use to validate the
XML against.
3.
The top level element of the XML document must always be <pdf>.
4.
Like HTML, the document consists of a “head”, containing information about the
document, and a “body” containing the contents of the document.
5.
In XML an element must always be “closed” - this means that <pdf> must always be
matched by </pdf>, <b> by </b> and so on. When an element has no content, like
<br>, <img> or <meta>, it may close itself.
SuiteScript Developer and Reference Guide
SuiteScript Functions
File APIs
6.
549
The <body> element can have some attributes set - background-color and font-size. In
XML, every attribute value must be quoted - this can be frustrating for HTML authors
used to typing <table width=100%>.
Back to XML APIs | Back to SuiteScript Functions
File APIs
Use these APIs to work with files that currently exist in the NetSuite file cabinet. These APIs
can also be used to create files to load into NetSuite or to send as attachments in email.
All APIs listed below are in alphabetical order.
•
nlapiCreateFile(name, type, contents)
•
nlapiDeleteFile(id)
•
nlapiLoadFile(id)
•
nlapiSubmitFile(file)
•
nlobjFile
nlapiCreateFile(name, type, contents)
Instantiates and returns an nlobjFile object. The file object can be used as an email or fax
attachement. The file object can also be saved to the file cabinet using nlapiSubmitFile(file).
Note: There is a 5MB limitation to the size of the document that can be created using this
API.
The nlapiCreateFile API can also be used for streaming to clients (via Suitelets). For streaming
or attaching binary content, you can call the following. Note that each of these APIs can load or
generate binary content, provided that the contents argument is base-64 encoded.
•
nlapiLoadFile(id)
•
nlapiPrintRecord(type, id, mode, properties)
•
nlapiMergeRecord(id, baseType, baseId, altType, altId, fields)
This API is supported in user event, scheduled, portlet, mass update, and Suitelet scripts.
Important: Be aware that the nlapiCreateFile function does not support the creation of
non-text file types such as PDFs, unless the contents argument is base-64
encoded.
Parameters
•
name {string} [required] - The name of the file
SuiteScript Developer and Reference Guide
SuiteScript Functions
File APIs
550
•
type {string} [required] - The file type. For a list of supported file types, see Supported
File Types in the NetSuite Help Center. Note that when specifiying the type for an adhoc email or fax attachment, only non-binary types are supported (for example,
PLAINTEXT, HTMLDOC, XMLDOC), unless the contents argument is base-64
encoded.
•
contents {string} [required] - The contents of the file
Returns
•
An nlobjFile object
Since
•
Version 2008.1
Example 1
This example shows how to create a simple text file to use as an email attachment. Note that
once created, the file object will not be stored in the file cabinet.
function sendAttachment()
{
var newAttachment = nlapiCreateFile('helloworld.txt', 'PLAINTEXT', 'Hello World\nHello World');
var newEmail = nlapiSendEmail(210, 'kwolfe@netsuite.com', 'Sample email and attachment',
'Please see the attached file', null, null, null, newAttachment);
}
Example 2
This example shows how to turn a file merge into a PDF document object. The PDF can then
be used as an email attachment.
var pdfcontents = nlapiMergeRecord(.....)
var fileObj = nlapiCreateFile('mypdf.pdf ', 'PDF', pdfcontents)
Back to File APIs | Back to SuiteScript Functions
nlapiDeleteFile(id)
Deletes a file and returns the internal ID of the file that was deleted. Usage metering allowed for
this function is 20 units. This API is supported in user event, scheduled, portlet, and Suitelet
scripts.
Parameters
•
id {int} [required] - The internal ID for the file you want to delete
SuiteScript Developer and Reference Guide
SuiteScript Functions
File APIs
551
Returns
•
The internal ID for the file that was deleted as an integer
Since
•
Version 2009.1
Back to File APIs | Back to SuiteScript Functions
nlapiLoadFile(id)
Loads a file from the NetSuite file cabinet (using the file’s internal ID or path). Returns an
nlobjFile containing the file's metadata (name and type) and contents in the form of a String
(base-64 encoded if the file's type is binary). The script context must have privileges to the file
(based on folder permissions), and the file cannot be a hidden (bundled) file.
Usage metering allowed for nlapiLoadFile is 10 units. This API is supported in user event,
scheduled, portlet, and Suitelet scripts.
Note: There is a 5MB limitation to the size of the document that can be accessed using this
API.
Parameters
•
id {string | int} [required] - The internal id of the file in the file cabinet. Can also be a
relative path to the file in the file cabinet (for example: SuiteScript/myfile.js).
Returns
•
An nlobjFile object
Example
This example shows how to load a jpeg that is currently in the Images folder in the File Cabinet.
The script will return the file as a NetSuite nlobjFile object, which allows you to use nlobjFile
methods to interact with the file.
function logEvent(type)
{
var f = nlapiLoadFile('Images/logo_goat.jpg');
if (f)
{
nlapiLogExecution('AUDIT', 'Event', 'Type:'+type+' file;'+f.getId());
}
else
nlapiLogExecution('AUDIT', 'Event', 'No file;');
}
Back to File APIs | Back to SuiteScript Functions
SuiteScript Developer and Reference Guide
SuiteScript Functions
Error Handling APIs
552
nlapiSubmitFile(file)
Submits a file and returns the internal ID to the file that was added to (or updated in) the
NetSuite file cabinet. Note that if a file with the same name exists in the folder that this file is
added to, then that file will be updated.
Note: There is a 5MB limitation to the size of the document that can be submitted using this
API.
Usage metering allowed for this function is 20 units. This API is supported in user event,
scheduled, portlet, and Suitelet scripts.
Parameters
•
file {nlobjFile} [required] - The nlobjFile that will be updated
Returns
•
The integer value of the file ID.
Since
•
Version 2009.1
Example
•
See the code sample in Uploading Files to the File Cabinet Using SuiteScript.
Back to File APIs | Back to SuiteScript Functions
nlobjFile
See nlobjFile - defined in the section on Standard Objects.
Back to File APIs | Back to SuiteScript Functions
Error Handling APIs
All APIs listed below are in alphabetical order.
•
nlapiCreateError(code, details, suppressNotification)
•
nlobjError
SuiteScript Developer and Reference Guide
SuiteScript Functions
Communication APIs
553
nlapiCreateError(code, details, suppressNotification)
Creates an nlobjError (complete with stacktrace) that can be thrown to abort script execution.
This API is supported in user event, scheduled, portlet, and Suitelet scripts.
Parameters
•
code {string} [required] - A user-defined error code
•
details {string} [required] - The error details
•
suppressNotification {boolean} [optional] - If not set, defaults to false and an email
notification with error details is sent after script execution. If set to true, the error
email notification is suppressed. Note: The values for this parameter can be true or
false, not T or F.
Returns
•
An nlobjError object
Back to Error Handling APIs | Back to SuiteScript Functions
nlobjError
See nlobjError - defined in the section on Standard Objects.
Back to Error Handling APIs | Back to SuiteScript Functions
Communication APIs
Use these APIs to communicate to external systems from within NetSuite.
All APIs listed below are in alphabetical order.
•
nlapiSendCampaignEmail(campaigneventid, recipientid)
•
nlapiSendEmail(author, recipient, subject, body, cc, bcc, records, attachments)
•
nlapiSendFax(author, recipient, subject, body, records, attachments)
•
nlapiOutboundSSO(id)
nlapiSendCampaignEmail(campaigneventid, recipientid)
Use this function to send a single “on-demand” campaign email to a specified recipient and
return a campaign response ID to track the email. Note that this function works in conjunction
SuiteScript Developer and Reference Guide
SuiteScript Functions
Communication APIs
554
with the Lead Nurturing (campaigndrip) sublist only; it does not work with the E-mail
(campaignemail) sublist.
Usage metering allowed is 10 units. This API is supported in user event, scheduled, Suitelet,
mass update, and workflow action scripts.
Parameters
•
campaigneventid {int} [required] - The internal ID of the campaign event. The
campaign must be of type campaigndrip, which is referred to as Lead Nurturing in the
UI.
•
recipientid {int} [required] - The internal ID of the recipient. Note that the recipient
must have an email.
Returns
•
A campaign response ID (tracking code) as an integer, or -1 if the send fails.
Since
•
Version 2010.1
Example
This sample shows how to create a new campaign event and email the event to a specified
recipient. Once the email is sent, the sender can use the campaign response ID that is returned
for tracking purposes.
// Create the new campaign record in dynamic mode so all field values can be dynamically sourced.
// For information on dynamic scripting, see Working with Records in Dynamic Mode.
var campaign1 = nlapiCreateRecord('campaign', {recordmode: dynamic});
campaign1.setFieldValue('title', 'Sample Lead Nurturing Campaign');
//Set values on the Lead Nurturing (campaigndrip) sublist
campaign1.selectNewLineItem('campaigndrip');
// 4 is a sample ID representing an existing marketing campaign
campaign1.setCurrentLineItemValue('campaigndrip', 'template', 4);
campaign1.setCurrentLineItemValue('campaigndrip', 'title', 'Sample Lead Nurturing Event');
// 1 is a sample ID representing an existing subscription
campaign1.setCurrentLineItemValue('campaigndrip', 'subscription', 1);
// 2 is a sample ID representing an existing channel
campaign1.setCurrentLineItemValue('campaigndrip', 'channel', 2);
// 1 is a sample ID representing an existing promocode
campaign1.setCurrentLineItemValue('campaigndrip', 'promocode', 1);
campaign1.commitLineItem('campaigndrip');
// Submit the record
var campaign1Key = nlapiSubmitRecord(campaign1);
// Load the campaign record you just created. Determine the internal ID of the campaign event
SuiteScript Developer and Reference Guide
SuiteScript Functions
Communication APIs
555
// to the variable campaign2_campaigndrip_internalid_1.
var campaign2 = nlapiLoadRecord('campaign', campaign1Key, {recordmore: dynamic});
var campaign2_campaigndrip_internalid_1 = campaign2.getLineItemValue('campaigndrip', 'internalid', 1);
// 142 is a sample ID representing the ID of a recipient with a valid email address
var campaignResponseId = nlapiSendCampaignEmail(campaign2_campaigndrip_internalid_1, 142);
Back to Communication APIs | Back to SuiteScript Functions
nlapiSendEmail(author, recipient, subject, body, cc, bcc, records,
attachments)
Sends and records outgoing email to an individual or to a group of individuals. This function
can be used for automatic email notifications of critical events or for message logging. Note
that you can also send multiple attachments of any media type using this function. Email
attachment size cannot exceed 5 MB. In other words, you can send as many attachments as you
like, but collectively, all attachments cannot exceed 5 MB.
This function also allows email to be attached to custom records if the user references the
custom record by either its internalId or scriptId.
Usage metering allowed is 10 units. This API is supported in client, user event, scheduled,
portlet, and Suitelet scripts.
Note: You can use NetSuite email templates to construct the body of the email using
nlapiMergeRecord(id, baseType, baseId, altType, altId, fields), which performs a
merge operation using a NetSuite email template and up to two business records.
Parameters
•
author {int} [required] - The internalId of an employee record (this is the sender). To
get the internal ID for an employee, go Lists > Employees > Employees (you must have
admin access to the account in order to access the Employees list page). The employee’s
ID will appear in the Internal ID column on the list page. Note, however, you must
have the Show Internal IDs preference enabled in your account. To enable this
preference, go to Home > Set Preferences > General tab > under Defaults > click Show
Internal IDs > click Save.
•
recipient {string | int} [required] - You can set the following for this parameter:
• A single external email address, or
• A list of external addresses (comma separated), or
• The internal ID of a single entity in NetSuite. Note that if the internal ID of the
recipient entity record is used, the email message is automatically attached to the
entity record.
•
subject {string} [required] - Subject of the outgoing mail.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Communication APIs
556
Important: The subject argument is required. A JavaScript exception is thrown if this
argument is left blank, set to null, or set to an empty string.
•
body {string} [required] - Body of the outgoing email.
Important: The body argument is required. A JavaScript exception is thrown if this
argument is left black, set to null, or set to an empty string.
•
cc {string | string[]} [optional] - An array of email addresses or a single email address
to copy
•
bcc {string | string[]} [optional] - An array of email addresses or a single email address
to blind copy.
•
records {hashtable} [optional] - An associative array of internal records to associate/
attach this email with. The following table lists valid keys -> values.
Key
Value (examples)
records['transaction'] = '1000';
transaction
(use for transaction and opportunity record types)
records['activity'] = '50';
activity
(use for Case and Campaign record types)
records['entity'] = '555';
entity
(use for all Entity record types, for example, customer,
contact, etc.)
record
(custom record internalId - for custom records you must
also specify both the record ID and the record type ID)
records['recordtype'] = 'customrecord11';
recordtype
(custom recordtype internalId or scriptId)
•
attachments {nlobjFile | nlobjFile[]} [optional] - A single nlobjFile object - or - an array
of nlobjFile objects to attach to outgoing email (not supported in Client SuiteScript).
Returns
•
void
Throws
•
SSS_AUTHOR_MUST_BE_EMPLOYEE
•
SSS_AUTHOR_REQD
•
SSS_INVALID_RECIPIENT_ID
•
SSS_MISSING_REQD_ARG
•
SSS_RECIPIENT_REQD
SuiteScript Developer and Reference Guide
SuiteScript Functions
Communication APIs
•
SSS_INVALID_CC_EMAIL
•
SSS_INVALID_BCC_EMAIL
557
Example 1
// Merge, send, and associate an email with an opportunity record (id=1000)
function testMergeAndSendEmail()
{
var records = new Object();
records['transaction'] = '1000';
var emailBody = nlapiMergeRecord( 25, 'customer', '100' ).getValue();
nlapiSendEmail( -5, 'customer@customer.com', 'Promotion Notification',
emailBody , null, null, records );
}
Example 2
This example shows how to send an email that includes an attachment.
var newAttachment = nlapiLoadFile(67);
nlapiSendEmail(author, recipient, subject, body, null, null, records, newAttachment);
Example 3
This example shows how to associate an outgoing email with a custom record.
var records = new Object();
records['recordtype'] = InternalIdOfCustomRecordType; // for example 55
records['record'] = InternalIdOfCustomRecord;
nlapiSendEmail(1, custemail, emailsubj, emailtext, null, null, records);
Back to Communication APIs | Back to SuiteScript Functions
nlapiSendFax(author, recipient, subject, body, records, attachments)
Sends and records an outgoing fax using the fax settings already defined in the user’s account.
This API is supported in client, user event, scheduled, portlet, and Suitelet scripts.
Parameters
•
author {int} [required] - InternalId of an employee record (this is the sender)
•
recipient {string} [required] - InternalId of the recipient entity -or- a free-form fax (if
set to an internalId the fax will be saved)
SuiteScript Developer and Reference Guide
SuiteScript Functions
Communication APIs
558
•
subject {string} [required] - Subject of the outgoing fax
•
body {string} [optional] - Body of the outgoing fax
•
records {hashtable} [optional] - Name/value pairs of internal records to associate this
fax with (if set, fax will be saved)
• transaction - transaction/opportunity internalid
• activity - case/campaign internalid
• entity - entity internalid
• record - custom record internalId
• recordtype - custom recordType internalId (or script id)
•
attachments {nlobjFile} [optional] - array of nlobjFile objects or a single nlobjFile
object to attach to outgoing fax (not supported in Client SuiteScript)
Returns
•
void
Since
•
Version 2008.1
Example
// Merge, send, and associate a fax with an customer record (id=1000)
function testMergeAndSendFax()
{
var records = new Object();
records['entity'] = '1000';
var faxBody = nlapiMergeRecord( 25, 'customer', '100' ).getValue();
nlapiSendFax( -5, '650.555.4455', 'Promotion Notification', faxBody, records );
}
Back to Communication APIs | Back to SuiteScript Functions
nlapiOutboundSSO(id)
Use this API to generate a new OAuth token for a user. Currently this API can be called from
portlet scripts, user event scripts, and Suitelets only. This API consumes 20 usage units per call.
Note that you must have the SuiteSignOn feature enabled in your account before you can use
SuiteSignOn functionality. (To enable these features, go to Setup > Company > Enable Features.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Communication APIs
559
On the SuiteCloud tab, select the Web Services check box and the SuiteSignOn check box, then
click Save.)
Important: For complete details on NetSuite’s SuiteSignOn feature, see the SuiteSignOn
Guide in the NetSuite Help Center.
Parameters
•
id {string} [required] - The custom scriptId specified on the SuiteSignOn record (see
figure). NetSuite recommends you create a custom scriptId for each SuiteSignOn
record to avoid naming conflicts should you decide use SuiteBundler to deploy your
scripts into other accounts.
If you do not create a custom scriptId, a system-generated ID will be generated for you
once the SuiteSignOn record is saved. You can also use the system-generated ID as the
id value.
Note: Once the SuiteSignOn record is saved, both the scriptId and system-generated ID
are prefixed with customsso.
To see a list of IDs for all SuiteSignOn records, go to the SuiteSignOn list page (Setup >
Integration > SuiteSignOn).
Returns
•
URL, OAuth token, and any integration variables as a string
Throws
•
SSS_SUITESIGNON_NOT_CONFIGURED
•
SSS_INVALID_SUITESIGNON
Since
•
Version 2009.2
Example 1
This sample shows how to use nlapiOutboundSSO(id) in a portlet script to create a reference to
the SuiteSignOn record. Once the portlet is added to the dashboard, the script is executed. The
SuiteScript Developer and Reference Guide
SuiteScript Functions
Communication APIs
560
value of the nlapiOutboundSSO variable is passed to an iframe, which makes the http request
to load the source.
// create a portlet object
function buildPortlet(portlet, column)
{
// set a portlet title
title = 'My Custom SSO Portlet!'
portlet.setTitle(title)
// pass the scriptId of the SuiteSignOn record
var url = nlapiOutboundSSO('customsso_wlf_sso_partner_portlet');
// create an iframe. It is the iframe that makes the http request to
// load the content of the portlet.
var content = '<iframe src="'+url+'" align="center" style="width: 100%; height: 600px;
margin:0; border:0; padding:0"></iframe>';
// render the content in your portlet
portlet.setHtml( content );
}
Example 2
This sample shows how to use nlapiOutboundSSO(id) in a Suitelet to create a reference to the
SuiteSignOn record. When the Suitelet opens and the content of the iframe is generated, the
URL specified on the SignSignOn record will render.
function buildSuitelet(request, response)
{
if ( request.getMethod() == 'GET' )
{
//create a form
var form = nlapiCreateForm('SSO Suitelet');
var label = form.addField('custpage_label', 'inlinehtml', 'SSO1');
label.setDefaultValue ('<B>Check out my SSO Suitelet!!</B>');
var url = nlapiOutboundSSO('customsso_wlf_sso_partner_suitelet');
var content = '<iframe src="'+url+'" align="center" style="width: 1000px; height: 800px;
margin:0; border:0; padding:0"></iframe>';
var iFrame = form.addField('custpage_sso', 'inlinehtml', 'SSO2');
iFrame.setDefaultValue (content);
iFrame.setLayoutType('outsidebelow', 'startcol');
response.writePage( form );
}
}
Example 3
This sample shows how to use nlapiOutboundSSO(id) in a user event script to integrate with
an external application. At the point indicated by the user event script record (Before Load,
Before Submit, or After Submit), the script gets the SuiteSignOn record that has this script
SuiteScript Developer and Reference Guide
SuiteScript Functions
Configuration APIs
561
defined as a connection point. The script returns the external application URL and any
integration variables associated with this SuiteSignOn record and sends an http request to this
URL. The external application can respond.
The most common usage of this type of script is to save a record in an external application
when a record is saved in NetSuite.
function syncWithExternalApp(type)
{
var url = nlapiOutboundSSO('customsso_my_external_app');
nlapiRequestURL(url);
}
Back to Communication APIs | Back to SuiteScript Functions
Configuration APIs
NetSuite allows developers to programmatically obtain, and in some cases, change the values
on certain account configuration pages. The internal IDs for SuiteScript-supported
configuration pages are provided below. For the IDs that represent specific preferences on a
configuration page, see Preference Names and IDs in the NetSuite Help Center.
All APIs listed below are in alphabetical order.
•
nlapiLoadConfiguration(type)
•
nlapiSubmitConfiguration(name)
•
nlobjConfiguration
nlapiLoadConfiguration(type)
Use this API to load a NetSuite configuration page. The following configuration pages support
SuiteScript: Company Information, General Preferences, Accounting Preferences, Accounting
Periods, Tax Periods.
Once a page is loaded, you can set configuration values using
nlobjConfiguration.setFieldValue(name, value).
The nlapiLoadConfiguration function is available in scheduled and Suitelet scripts only. It
consumes 10 usage units per call.
Parameters
•
type - {string} [required] - The internal ID of the configuration page. Available IDs are:
• companyinformation - The internal ID for the Company Information page
(Setup > Company > Company Information).
• companypreferences - The internal ID for the General Preferences page
(Setup > Company > General Preferences).
SuiteScript Developer and Reference Guide
SuiteScript Functions
Configuration APIs
562
• accountingpreferences - The internal ID for the Accounting Preferences page
(Setup > Accounting > Accounting Preferences).
• accountingperiods - The internal ID for the Accounting Periods page (Setup >
Accounting > Manage Accounting Periods).
• taxperiods - The internal ID for the Tax Periods page (Setup > Accounting >
Manage Tax Periods).
• companyfeatures - The internal ID for looking up which features are enabled in
an account.
Returns
•
nlobjConfiguration object
Since
•
Version 2009.2
Example
This example shows how to load the Company Information configuration page and then set
the values for the Employer Identification Number (EIN) (employerid) field and the SSN or
TIN (Social Security Number, Tax ID Number) (taxid) field.
// load the NetSuite configuration page
var companyInfo = nlapiLoadConfiguration( 'companyinformation' );
// set field values
companyInfo.setFieldValue( 'employerid', '123456789' );
companyInfo.setFieldValue( 'taxid', '1122334455' );
// save changes to the configuration page
nlapiSubmitConfiguration( companyInfo );
Back to Configuration APIs | Back to SuiteScript Functions
nlapiSubmitConfiguration(name)
Use this API to submit changes to a configuration page that was loaded into the system using
nlapiLoadConfiguration(type). The following configuration pages support SuiteScript:
Company Information, General Preferences, Enable Features, Accounting Preferences,
Accounting Periods, Tax Periods.
The nlapiSubmitConfiguration function is available in scheduled and Suitelet scripts only. It
consumes 20 usage units per call.
Parameters
•
name - {nlobjConfiguration} [required] - nlobjConfiguration object containing the
data record
SuiteScript Developer and Reference Guide
SuiteScript Functions
SuiteFlow APIs
Returns
•
void
Since
•
Version 2009.2
Example
This example shows how to load the Company Information configuration page and then set
the values for the Employer Identification Number (EIN) (employerid) field and the SSN or
TIN (Social Security Number, Tax ID Number) (taxid) field.
// load the NetSuite configuration page
var companyInfo = nlapiLoadConfiguration( 'companyinformation' );
// set field values
companyInfo.setFieldValue( 'employerid', '123456789' );
companyInfo.setFieldValue( 'taxid', '1122334455' );
// save changes to the configuration page
nlapiSubmitConfiguration( companyInfo );
Back to Configuration APIs | Back to SuiteScript Functions
nlobjConfiguration
See nlobjConfiguration - defined in the section on Standard Objects.
Back to Configuration APIs | Back to SuiteScript Functions
SuiteFlow APIs
Use these APIs to interact with the NetSuite SuiteFlow Manager.
All APIs listed below are in alphabetical order.
•
nlapiInitiateWorkflow(recordtype, id, workflowid)
•
nlapiTriggerWorkflow(recordtype, id, workflowid, actionid)
SuiteScript Developer and Reference Guide
563
SuiteScript Functions
SuiteFlow APIs
564
nlapiInitiateWorkflow(recordtype, id, workflowid)
Use this function to initiate a workflow on-demand. This function is the programmatic
equivalent of the Initiate Workflow action in the SuiteFlow Manager. The function returns the
workflow instance ID for the workflow-record combination. A user error is thrown if the
record in the workflow is invalid or not supported for that workflow.
Usage metering allowed is 20 units. This API is supported in user event, scheduled, portlet,
Suitelet, mass update, and workflow action scripts.
Parameters
•
recordtype {string} [required] - The record type ID of the workflow base record (for
example, 'customer', 'salesorder', 'lead'). In the Workflow Manager this is the record
type that is specified in the Record Type field.
•
id {int} [required] - The internal ID of the base record (for example 55 or 124).
•
workflowid {int | string} [required] - The internal ID (int) or script ID (string) for the
workflow definition. This is the ID that appears in the ID field on the Workflow
Definition Page.
Returns
•
The internal ID (int) of the workflow instance used to track the workflow against the
record.
Since
•
Version 2010.1
Back to SuiteFlow APIs | Back to SuiteScript Functions
nlapiTriggerWorkflow(recordtype, id, workflowid, actionid)
Use this API to trigger a workflow on a record. The actions and transitions of the workflow will
be evaluated for the record based on the current state that it is in.
Usage metering allowed is 20 units. This API is supported in user event, scheduled, portlet,
Suitelet, mass update, and workflow action scripts.
Parameters
•
recordtype {string} [required] - The record type ID of the workflow base record (for
example, 'customer', 'salesorder', 'lead'). In the Workflow Manager this is the record
type that is specified in the Record Type field.
•
id {int} [required] - The internal ID of the base record (for example 55 or 124).
•
workflowid {int | string } [required] - The internal ID (int) or script ID (string) for the
workflow definition. This is the ID that appears in the ID field on the Workflow
Definition Page.
SuiteScript Developer and Reference Guide
SuiteScript Functions
Portlet APIs
•
565
actionid {string | int} [optional] - The internal ID of a button that appears on the
record in the workflow. Using this parameter triggers the workflow as if the specified
button were pressed.
Returns
•
The internal ID (int) of the workflow instance used to track the workflow against the
record.
Since
•
Version 2010.1
Back to SuiteFlow APIs | Back to SuiteScript Functions
Portlet APIs
Use these APIs to work with NetSuite dashboard portlets.
All APIs listed below are in alphabetical order.
•
nlapiRefreshPortlet()
•
nlapiResizePortlet()
nlapiRefreshPortlet()
Causes a FORM type nlobjPortlet to immediately reload.
This API is available within a client SuiteScript associated with a custom FORM portlet, or
from JavaScript event handlers attached to portlet elements. This API cannot be called directly
from within a FORM portlet script.
Parameters
•
None
Returns
•
Void
Since
•
Version 2011.1
Example
The following code adds a link that can be clicked to refresh a portlet on demand:
fld = portlet.addField('refrfield','inlinehtml','Refresh');
fld.setDefaultValue("<a onclick='nlapiRefreshPortlet()' href='#'>Refresh Now!</a>");
Back to Portlet APIs | Back to SuiteScript Functions
SuiteScript Developer and Reference Guide
SuiteScript Functions
Portlet APIs
566
nlapiResizePortlet()
Causes a FORM type nlobjPortlet to be resized.
This API can be used to ensure that a custom form portlet’s embedded iframe resizes when the
size of its contents change. This type of iframe does not resize automatically as its contents
change, so when a form portlet’s contents shrink they are surrounded by white space, and when
contents grow they are cut off. A call to this API prevents these display issues.
This API is available within a client SuiteScript associated with a custom FORM portlet, or
from JavaScript event handlers attached to portlet elements. This API cannot be called directly
from within a FORM portlet script.
Parameters
•
None
Returns
•
Void
Since
•
Version 2011.1
Example
The following example creates a small custom form portlet with a "Mutate!" link. When this
link is clicked, a div element in the portlet is randomly resized and nlapiResizePortlet() is
called to adjust the portlet to match.
function demoSimpleFormPortlet(portlet, column)
{
portlet.setTitle('nlapiResizePortlet demo');
var txtField = portlet.addField('text','text','Random text field');
txtField.setLayoutType('normal','startcol');
var fld = portlet.addField('divfield','inlinehtml');
fld.setDefaultValue("<div id='divfield_elem' style='border: 1px dotted red; height: 32px; width: 32px'></
div>");
fld = portlet.addField('growlink','inlinehtml');
fld.setDefaultValue("<a onclick='mutate()' href='#'>Mutate!</a>");
portlet.setScript('customscriptclienta');
}
function mutate()
{
var div = document.getElementById('divfield_elem');
var h = 32 + Math.floor(Math.random() * 128);
div.style.height = h + 'px';
nlapiResizePortlet();
}
SuiteScript Developer and Reference Guide
SuiteScript Functions
SuiteAnalytics APIs
567
Back to Portlet APIs | Back to SuiteScript Functions
SuiteAnalytics APIs
Use these APIs to work with NetSuite Analytics.
All APIs listed below are in alphabetical order.
•
nlapiCreateReportDefinition()
•
nlapiCreateReportForm(title)
•
nlobjPivotColumn
•
nlobjPivotRow
•
nlobjPivotTable
•
nlobjPivotTableHandle
•
nlobjReportColumn
•
nlobjReportColumnHierarchy
•
nlobjReportDefinition
•
nlobjReportForm
•
nlobjReportRowHierarchy
nlapiCreateReportDefinition()
Creates an instance of a report definition object. The report is built on this object using
subsequent methods. The report definition can be used to create a form for rendering the pivot
table report in a browser, or the pivot table APIs can be used to extract the values of the
individual rows and columns of the pivot table.
Returns
•
nlobjReportDefinition
Since
•
Version 2012.2
Example
•
See the code sample in Building a Pivot Report Using SuiteScript.
Back to SuiteAnalytics APIs | Back to SuiteScript Functions
SuiteScript Developer and Reference Guide
SuiteScript Functions
SuiteAnalytics APIs
nlapiCreateReportForm(title)
Creates an nlobjReportForm object to render the report definition.
Parameters
•
title {string} [required] - The title of the form.
Returns
•
nlobjReportForm
Since
•
Version 2012.2
Example
•
See the code sample in Building a Pivot Report Using SuiteScript.
Back to SuiteAnalytics APIs | Back to SuiteScript Functions
nlobjPivotColumn
See nlobjPivotColumn - defined in the section on Standard Objects.
Back to SuiteAnalytics APIs | Back to SuiteScript Functions
nlobjPivotRow
See nlobjPivotRow - defined in the section on Standard Objects.
Back to SuiteAnalytics APIs | Back to SuiteScript Functions
nlobjPivotTable
See nlobjPivotTable - defined in the section on Standard Objects.
Back to SuiteAnalytics APIs | Back to SuiteScript Functions
nlobjPivotTableHandle
See nlobjPivotTableHandle - defined in the section on Standard Objects.
SuiteScript Developer and Reference Guide
568
SuiteScript Functions
User Credentials APIs
569
Back to SuiteAnalytics APIs | Back to SuiteScript Functions
nlobjReportColumn
See nlobjReportColumn - defined in the section on Standard Objects.
Back to SuiteAnalytics APIs | Back to SuiteScript Functions
nlobjReportColumnHierarchy
See nlobjReportColumnHierarchy - defined in the section on Standard Objects.
Back to SuiteAnalytics APIs | Back to SuiteScript Functions
nlobjReportDefinition
See nlobjReportDefinition - defined in the section on Standard Objects.
Back to SuiteAnalytics APIs | Back to SuiteScript Functions
nlobjReportForm
See nlobjReportForm - defined in the section on Standard Objects.
Back to SuiteAnalytics APIs | Back to SuiteScript Functions
nlobjReportRowHierarchy
See nlobjReportRowHierarchy - defined in the section on Standard Objects.
Back to SuiteAnalytics APIs | Back to SuiteScript Functions
User Credentials APIs
Use these APIs to change the NetSuite login credentials of the currently logged-in user. In
NetSuite, a user’s login credentials consists of a user’s email address and a password.
Important: When building a custom UI outside of the standard NetSuite UI (such as
building a custom mobile page using Suitelet or building E-Commerce pages
SuiteScript Developer and Reference Guide
SuiteScript Functions
User Credentials APIs
570
using SSP), use these APIs to help users manage their credentials within the
custom UI.
All APIs listed below are in alphabetical order.
•
nlapiGetLogin()
•
nlobjLogin
nlapiGetLogin()
Returns the NetSuite login credentials of currently logged-in user.
This API is supported in user event, portlet, Suitelet, RESTlet, and SSP scripts. For information
about the unit cost associated with this API, see API Governance.
Returns
•
nlobjLogin
Since
•
Version 2012.2
Example
This example shows how to get the credentials of the currently logged-in user.
//Get credentials of currently logged-in user
var login = nlapiGetLogin();
Back to User Credentials APIs | Back to SuiteScript Functions
nlobjLogin
See nlobjLogin - defined in the section on Standard Objects.
Back to User Credentials APIs | Back to SuiteScript Functions
SuiteScript Developer and Reference Guide
Chapter 57 SuiteScript Objects
SuiteScript Objects Overview
SuiteScript objects are classified into the following two categories. Click the links below to see
which objects are assigned to each category. From there you can also access API
documentation for each method on the object.
•
Standard Objects
•
UI Objects
Standard Objects
The objects in this list are standard objects. Unlike UI Objects, they are not used to build
NetSuite UI components such as buttons, forms, fields, sublists, etc. Standard objects are used
more for manipulating backend data and to handle form GET and POST processing.
Each standard object has methods that can be performed against it once it is returned in the
script. The following is a list of all standard NetSuite objects.
•
nlobjConfiguration
•
nlobjContext
•
nlobjCSVImport
•
nlobjError
•
nlobjFile
•
nlobjLogin
•
nlobjPivotColumn
•
nlobjPivotRow
•
nlobjPivotTable
•
nlobjPivotTableHandle
•
nlobjRecord
•
nlobjReportColumn
•
nlobjReportColumnHierarchy
•
nlobjReportDefinition
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
•
nlobjReportForm
•
nlobjReportRowHierarchy
•
nlobjRequest
•
nlobjResponse
•
nlobjSearch
•
nlobjSearchColumn
•
nlobjSearchFilter
•
nlobjSearchResult
•
nlobjSearchResultSet
•
nlobjSelectOption
•
nlobjSubrecord
572
nlobjConfiguration
Primary object used to encapsulate a NetSuite configuration/setup page. Note that
nlapiLoadConfiguration(type) returns a reference to this object. Once the nlobjConfiguration
object has been modified, changes can be submitted to the database using
nlapiSubmitConfiguration(name).
For a list of configuration pages that support SuiteScript, see Preference Names and IDs in the
NetSuite Help Center.
Methods:
•
getAllFields()
•
getField(fldnam)
•
getFieldText(name)
•
getFieldTexts(name)
•
getFieldValue(name)
•
getFieldValues(name)
•
getType()
•
setFieldText(name, text)
•
setFieldTexts(name, text)
•
setFieldValue(name, value)
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
•
573
setFieldValues(name, value)
getAllFields()
Use this method to return a normal keyed array of all the field names on a configuration page.
Returns
•
String[] of field names
Since
•
Version 2009.2
Standard Objects | UI Objects | SuiteScript Functions
getField(fldnam)
Use the method to return field metadata for a field
Parameters
•
fldnam {string} [required] - The internal ID of the field
Returns
•
The nlobjField object
Since
•
Version 2009.2
Standard Objects | UI Objects | SuiteScript Functions
getFieldText(name)
Use this method to return the UI display value for a select field. This API is supported in select
fields only.
Parameters
•
name {string} [required] - The internal ID of the field
Returns
•
String - The UI display value corresponding to the current selection for a select field.
Returns null if field does not exist on the configuration page or if the field is restricted.
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
574
Since
•
Version 2009.2
Example
This sample shows how to use getFieldText(name) to return the UI display value for the First
Day of Week configuration preference. In this account, First Day of Week has been set to
Sunday. This is the value that will be returned.
var configpage = nlapiLoadConfiguration('companypreferences');
var valtext = configpage.getFieldText('firstdayofweek'); // returns Sunday
Standard Objects | UI Objects | SuiteScript Functions
getFieldTexts(name)
Use this method to return the UI display values for a multiselect field
Parameters
•
name {string} [required] - The name of the multiselect field whose field display values
are being returned
Returns
•
Returns the selected text values of a multiselect field as an Array
Since
•
Version 2009.2
Standard Objects | UI Objects | SuiteScript Functions
getFieldValue(name)
Use this method to return the internal ID value of a field
Parameters
•
name {string} [required] - The internal ID of the field
Returns
•
The internal ID (string) value for the field
Since
•
Version 2009.2
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
Example
// load an Accounting Periods configuration page
var configpage = nlapiLoadConfiguration('accountingpreferences');
// get value of the Cash Basis field. The value F will be returned since this is a
//check box field that is not selected.
var value = configpage.getFieldValue('cashbasis');
Standard Objects | UI Objects | SuiteScript Functions
getFieldValues(name)
Returns a read-only array of multi-select field values. This API is supported on multi-select
fields only.
Parameters
•
name {string} [required]- The internal ID of the field
Returns
•
String[] of field IDs. Returns null if field is not on the configuration page.
Since
•
Version 2009.2
Standard Objects | UI Objects | SuiteScript Functions
getType()
Use this method to return the internal ID of a configuration page, for example,
accountingpreferences or taxperiods.
Returns
•
The internal ID of the configuration page as a string
Since
•
Version 2009.2
Standard Objects | UI Objects | SuiteScript Functions
SuiteScript Developer and Reference Guide
575
SuiteScript Objects
Standard Objects
576
setFieldText(name, text)
Use this method to set the value of a select field using its corresponding display value. This API
is supported on select fields only.
Parameters
•
name {string} [required] - The internal ID of the field being set
•
text {string} [required] - The field display name as it appears in the UI
Returns
•
void
Since
•
Version 2009.2
Standard Objects | UI Objects | SuiteScript Functions
setFieldTexts(name, text)
Use this method to set the values (via the UI display values) of a multi-select field. This API is
supported on multi-select fields only.
Parameters
•
name {string} [required] - The internal ID of the field being set
•
texts {string[]} [required] - Array of field display values
Returns
•
void
Since
•
Version 2009.2
Standard Objects | UI Objects | SuiteScript Functions
setFieldValue(name, value)
Use this method to set the value of a field
Parameters
•
name {string} [required] - The internal ID of the field being set
•
value {string} [required] - The value the field is being set to
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
577
Returns
•
void
Since
•
Version 2009.2
Standard Objects | UI Objects | SuiteScript Functions
setFieldValues(name, value)
Use this method to set the value of a multi-select field. This API is supported on multi-select
fields only.
Parameters
•
name {string} [required] - The internal ID of the field being set
•
value {string[]} [required]- The value the field is being set to
Returns
•
void
Since
•
Version 2009.2
Standard Objects | UI Objects | SuiteScript Functions
nlobjContext
Encapsulates user information as well as script execution context at runtime. Note that the
nlapiGetContext() function returns a reference to this object.
nlobjContext Methods
•
getColorPreferences()
•
getCompany()
•
getDepartment()
•
getDeploymentId()
•
getEmail()
•
getEnvironment()
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
•
getExecutionContext()
•
getFeature(name)
•
getLocation()
•
getLogLevel()
•
getName()
•
getPercentComplete()
•
getPermission(name)
•
getPreference(name)
•
getRemainingUsage()
•
getRole()
•
getRoleCenter()
•
getScriptId()
•
getSessionObject(name)
•
getSetting(type, name)
•
getSubsidiary()
•
getUser()
•
getVersion()
•
setPercentComplete(pct)
•
setSessionObject(name, value)
•
setSetting(type, name, value)
578
getColorPreferences()
Returns an Object containing name-value pairs of color groups to their corresponding RGB
hex color based on the currently logged in user’s color theme preferences.
Using this method, developers can get a user’s color theme and apply the entire color theme
map (or just individual attributes) to bundled Suitelets that have been installed into a user’s
account. Doing so ensures that the look-and-feel of each Suitelet matches all other records/
pages running in the account.
Note: NetSuite color themes are read-only. Developers cannot programmatically create
new color themes or add additional attributes to NetSuite’s existing color theme
template. In NetSuite, color themes can be set by going to Home > Set Preferences
> Appearances tab.
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
Returns
•
Object array (map), for example:
values = {array} length=16
buttonbackground = {string} D2D2C8
text = {number} 000000
portlet = {string} 70A837
portletlabel = {string} FFFFFF
crumbtext = {string} #FFD11A
inactivetab = {string} FFCC00
link = {number} 000000
backgroundrequiredfld = {string} FFFFE5
inactivetextontab = {number} 000000
textontab = {string} FFFFFF
bodybackground = {string} FFFFFF
headbackground = {string} FFFFFF
shadedbackground = {string} F8E7A5
headerbar = {string} 70A837
shadedborder = {string} D4BE63
activetab = {string} 70A837
Since
•
Version 2010.1
Example
var ctx = nlapiGetContext();
var colorPrefs = ctx.getColorPreferences();
Color Preference Values
The following table provides the names of available NetSuite color theme attributes and a
description of what each attribute affects.
Attribute
Description
buttonbackground
Background color of colored buttons
text
Text color for all text on the page body
portlet
Portlet trim (header background) color
portletlabel
Text in portlet heading
crumbtext
Text color of breadcrumbs on the header bar (color may be
synthesized by page looks)
inactivetab
Inactive tab color
link
Text color for all links on the page body
SuiteScript Developer and Reference Guide
579
SuiteScript Objects
Standard Objects
Attribute
Description
backgroundrequiredfld
Background color for required fields in entry forms
inactivetextontab
Text color on the inactive tab
textontab
Text color on the active tab
bodybackground
Page background color
headbackground
Page header area background color
shadedbackground
Shaded area background color
headerbar
Header bar color
shadedborder
Border/header color around shaded areas
activetab
Active tab color
Standard Objects | UI Objects | SuiteScript Functions
getCompany()
Returns the currently logged in user's account ID
Returns
•
The string value of user’s account ID, for example NL555ABC
Since
•
Version 2007.0
Example
var context = nlapiGetContext();
var userAccountId = context.getCompany();
Standard Objects | UI Objects | SuiteScript Functions
getDepartment()
Returns the internal ID of the currently logged in user's department
Returns
•
The logged in user’s department ID as an integer
Since
•
Version 2007.0
SuiteScript Developer and Reference Guide
580
SuiteScript Objects
Standard Objects
Example
var context = nlapiGetContext();
var userDeptId = context.getDepartment();
Standard Objects | UI Objects | SuiteScript Functions
getDeploymentId()
Returns the deploymentId for the current script deployment (ie., the currently executing
script)
Returns
•
The deploymentId as a string
Since
•
Version 2009.1
Example
•
In the API documentation for nlapiScheduleScript(scriptId, deployId, params), see
Example 1 - Rescheduling a Script.
Standard Objects | UI Objects | SuiteScript Functions
getEmail()
Returns the currently logged in user's e-mail address. The email field on the user’s employee
record must contain an email address.
Note: In a shopping context where the shopper is recognized but not logged in, this
method can be used to return the shopper's email, instead of getting it from the
customer record.
Returns
•
An email address as a string
Since
•
Version 2007.0
Example
var context = nlapiGetContext();
var userEmail = context.getEmail();
Standard Objects | UI Objects | SuiteScript Functions
SuiteScript Developer and Reference Guide
581
SuiteScript Objects
Standard Objects
582
getEnvironment()
Returns the environment in which the current script is being executed. Valid values are
SANDBOX | PRODUCTION | BETA | INTERNAL.
Returns
•
The name of the environment as a string
Standard Objects | UI Objects | SuiteScript Functions
getExecutionContext()
Returns context information about what triggered the current script. Available values are:
•
userinterface - Client SuiteScript or user event triggers invoked from the UI
•
webservices - User event triggers invoked from webservice calls
•
csvimport - User event triggers invoked during CSV imports
•
offlineclient - User event triggers invoked during offlineclient
•
smbxml - User event triggers invoked during SMBXML calls
•
portlet - Portlet script or user event triggers invoked via portlet scripts
•
scheduled - Scheduled script or user event triggers invoked via scheduled scripts
•
suitelet - Suitelet or user event triggers invoked via suitelets
•
custommassupdate - Mass update script triggers invoked via custom Mass Update
scripts
•
workflow - Workflow action script triggers invoked via Workflow Action scripts
•
webstore - User event triggers invoked from the web store (for example to determine if
sales orders or customers were created in the web store).
•
userevent - This context type represents cases in which records are generated in the
backend (as opposed to being generated by the UI). For example, the 'userevent'
context distinguishes the case wherein a Bill Payment is submitted as part of a nonrecord page. Whereas the 'userinterface' context identifies when a single Bill Payement
record is submitted from the UI.
Returns
•
The execution context as a string
Since
•
Version 2007.0
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
583
Example
This is a user event script deployed to a Case record. Setting getExecutionContext() to
userinterface ensures that this script is ONLY invoked from a user event occurring through the
UI. When invoked, a tab is added to the Case record.
function caseBeforeLoad(type, form)
{
var currentContext = nlapiGetContext();
if( (currentContext.getExecutionContext() == 'userinterface') && (type == 'edit' | type == 'view'))
{
var SampleTab = form.addTab('custpage_sample_tab', 'SampleTab123');
}
}
Standard Objects | UI Objects | SuiteScript Functions
getFeature(name)
Use this method to determine if a particular feature is enabled in a NetSuite account. These are
the features that appear on the Enable Features page (Setup > Company > Enable Features).
Parameters
•
name {string} [required] - The internal ID of the feature. For a list of feature IDs, see
Feature Names and IDs in the NetSuite Help Center.
Returns
•
Returns true if a feature is enabled in the current account
Since
•
Version 2009.2
Example
This sample shows how to determine whether the Advanced Billing feature is enabled in your
account.
var ctx = nlapiGetContext();
context.getFeature('ADVBILLING');
Standard Objects | UI Objects | SuiteScript Functions
getLocation()
Returns the internal ID of the currently logged in user's location
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
584
Returns
•
The logged in user’s location ID as an integer
Since
•
Version 2007.0
Standard Objects | UI Objects | SuiteScript Functions
getLogLevel()
Returns the script logging level for the current script execution. This method is not supported
on client scripts.
Returns
•
The string value of the script log level. Possible values are DEBUG, AUDIT, ERROR,
EMERGENCY
Since
•
Version 2008.2
See also
•
nlapiLogExecution(type, title, details)
Standard Objects | UI Objects | SuiteScript Functions
getName()
Returns the currently logged in user's name
Note: In a shopping context where the shopper is recognized but not logged in, this
method can be used to return the shopper's name, instead of getting it from the
customer record.
Returns
•
The logged in user’s name as a string
Since
•
Version 2007.0
Standard Objects | UI Objects | SuiteScript Functions
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
585
getPercentComplete()
Return the % complete specified for the current scheduled script execution. The return value
will appear in the %Complete column in the Scheduled Script Status page. Note that this
method can only be called from scheduled scripts.
Returns
•
The integer value of the percent complete field
Since
•
Version 2009.1
Example
The following script is a scheduled script that performs a customer search. Use the
setPercentComplete and getPercentComplete methods to define percentage complete values
and then get the values. When getPercentComplete is called, the value appears in the
%Complete column in the Scheduled Script Status page. Access this page by going to Setup >
Customization > Script Deployments > Status.
function customerSearch(type)
{
var ctx = nlapiGetContext(); // instantiate the nlobjContext object
var searchresults = nlapiSearchRecord('customer', 21); // execute a specific saved search
ctx.setPercentComplete(0.00); // set the percent complete parameter to 0.00
for ( i = 0; i < searchresults.length; i++ ) // loop through the search results
{
// get the internal ID of each returned record, otherwise you cannot update the results
var recid = searchresults[i].getValue('internalid');
var record = nlapiLoadRecord('customer', recid); // load each record from the search
record.setFieldText('salesrep', 'John Doe'); // set a field display value for Sales Rep
var id = nlapiSubmitRecord(record, true); // submit the record
ctx.setPercentComplete( (100* i)/ searchresults.length ); // calculate the results
// displays the percentage complete in the %Complete column on
// the Scheduled Script Status page
ctx.getPercentComplete(); // displays percentage complete
}
}
Standard Objects | UI Objects | SuiteScript Functions
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
586
getPermission(name)
Use this method to get a user’s permission level for a given permission. For information on
working with NetSuite permissions, see the topic Understanding NetSuite Permissions in the
NetSuite Help Center.
Parameters
•
name {string} [required] - The internal ID of a permission. For a list of permission IDs,
see Permission Names and IDs in the SuiteScript Reference Guide.
Returns
•
The integer value of user's permission level for a given permission. Values 4 through 0
can be returned:
• 4 (FULL)
• 3 (EDIT)
• 2 (CREATE)
• 1 (VIEW)
• 0 (NONE)
Since
•
Version 2009.2
Example
This sample shows how to determine a user’s permission level for the Set Up Accounting
permission.
var ctx = nlapiGetContext();
context.getPermission('ADMI_ACCOUNTING ');
Standard Objects | UI Objects | SuiteScript Functions
getPreference(name)
Use this method to get the value of a NetSuite preference. Currently only General Preferences
and Accounting Preferences are exposed in SuiteScript. (You can view General Preferences by
going to Setup > Company > General Preferences. View Accounting Preferences by going to
Setup > Accounting > Accounting Preferences.)
Note: If you want to change the value of a General or Accounting preference using SuiteScript,
you must load each preference page using nlapiLoadConfiguration(type), where name is either
'companypreferences' (for the General Preferences page) or 'accountingpreferences' (for the
Accounting Preferences page). The nlapiLoadConfiguration API returns an nlobjRecord
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
587
object, which lets you change preference values using the setFieldValue() method. For
additional details, see nlapiLoadConfiguration.
Parameters
•
name {string} [required] - The internal ID of the preference. For a list of preference
IDs, see Preference Names and IDs in the NetSuite Help Center.
Returns
•
The value of a system or script preference for the current user. The value can be T or F
if the preference is a NetSuite checkbox field. The value can also be a string if the
preference is a NetSuite dropdown field.
Since
•
Version 2009.2
Example
This sample shows how to get the value of a NetSuite preference called Email Employee on
Approvals.
var ctx = nlapiGetContext();
context.getPreference('emailemployeeonapproval');
Standard Objects | UI Objects | SuiteScript Functions
getRemainingUsage()
Returns the remaining amount of unit usage for the current script
Returns
•
The integer value of the remaining unit count
Since
•
Version 2007.0
See also
•
SuiteScript Governance in the NetSuite Help Center
•
nlapiGetContext()
Example
var context = nlapiGetContext();
var usageRemaining = context.getRemainingUsage();
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
588
Standard Objects | UI Objects | SuiteScript Functions
getRole()
Returns the internal ID of the currently logged in user's role
Returns
•
The logged in user’s role ID as a string
Since
•
Version 2007.0
Standard Objects | UI Objects | SuiteScript Functions
getRoleCenter()
Returns the internal ID of the currently logged in user's center type (role center)
Returns
•
The string value of the logged in user’s center - for example, SALES, ACCOUNTING,
CLASSIC. Note that the string value of a custom center can also be returned.
Since
•
Version 2008.2
Standard Objects | UI Objects | SuiteScript Functions
getScriptId()
Returns the scriptId for the currently executing script
Returns
•
The scriptId as a string
Since
•
Version 2009.1
Example
•
In the API documentation for nlapiScheduleScript(scriptId, deployId, params), see
Example 1 - Rescheduling a Script.
Standard Objects | UI Objects | SuiteScript Functions
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
getSessionObject(name)
Use this method to get the value of a user-defined session object for the current user.
Parameters
•
name {string} [required] - The key used to store the session object
Returns
•
Returns the string value of a user-defined session object for the current user
Since
•
Version 2009.2
Example
This example shows how to get the value of the current user’s session, and then create a new
“Contact” session for the user to gather information about the user’s scope, budget, and
business problem.
function displayContact(request, response)
{
var ctx = nlapiGetContext();
var step = ctx.getSessionObject('stage');
if( step == null || step == "")
{
step = "create";
ctx.setSessionObject('stage', 'Contact');
}
if(step == "create");
{
ctx.setSessionObject('scope', request.getParameter('scope') );
ctx.setSessionObject('approved', request.getParameter('budget') );
ctx.setSessionObject('problem', request.getParameter('businessproblem') );
}
}
Standard Objects | UI Objects | SuiteScript Functions
getSetting(type, name)
Use this API to get a system or script setting. Note that if you want to get session, feature, or
permission settings directly, you can also use these nlobjContext methods:
•
getSessionObject(name)
•
getFeature(name)
•
getPermission(name)
SuiteScript Developer and Reference Guide
589
SuiteScript Objects
Standard Objects
590
Parameters
•
type{string}[required] - The type of script/system setting. Possible values include:
• SESSION - session variable (volatile setting defined per session). Supported in
server scripts only. Important: The SESSION type value is not supported in Client
SuiteScript.
• FEATURE - returns T (enabled) or F (disabled) depending on whether a feature is
enabled. Supported in client and server SuiteScript.
In the NetSuite Help Center, see Feature Names and IDs for feature names and
internal IDs.
• PERMISSION - returns permission level: 0 (none), 1 (view), 2 (create), 3 (edit), 4
(full). Supported in client and server SuiteScript.
In the NetSuite Help Center, see Permission Names and IDs for permission names
and internal IDs.
• SCRIPT - script parameter (defined per script). Supported in client and server
SuiteScript. If you do not know what script parameters are in NetSuite, see
Creating Script Parameters Overview.
•
name {string} [required]- The name of the script/system setting
Important: You must use the nlobContext.getSetting method to reference script parameters.
For example, to obtain the value of a script parameter called custscript_case_field, you use the
following code:
nlapiGetContext().getSetting('SCRIPT', 'custscript_case_field')
If you do not know what script parameters are in NetSuite, see Creating Script Parameters
Overview.
Returns
•
If type is specified as SCRIPT, SESSION, or FEATURE, a string value is returned. If
type is specified as PERMISSION, an integer value is returned.
Standard Objects | UI Objects | SuiteScript Functions
getSubsidiary()
Returns the internal ID of the currently logged in user's subsidiary
Returns
•
The logged in user’s subsidiary ID as an integer
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
591
Since
•
Version 2007.0
Standard Objects | UI Objects | SuiteScript Functions
getUser()
Returns the currently logged in user's internal ID
Returns
•
The logged in user’s ID as a string
Since
•
Version 2007.0
Standard Objects | UI Objects | SuiteScript Functions
getVersion()
Returns the version of NetSuite that the method is called in. For example, if getVersion() is
executed in an account running NetSuite 2010.2, the value returned is 2010.2. If getVersion() is
executed in an account running NetSuite 2010.1, the value returned is 2010.1.
This method may be helpful to those installing SuiteBundles in other NetSuite accounts, and
wish to know the version number before installing the bundle.
Returns
•
The NetSuite account version as a number - for example: 2010.2
Since
•
Version 2010.2
Standard Objects | UI Objects | SuiteScript Functions
setPercentComplete(pct)
Sets the percent complete for the currently executing scheduled script. Note that this method
can only be called from scheduled scripts.
Parameters
•
pct {float} [required] - The percentage of records completed
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
592
Returns
•
void
Since
•
Version 2009.1
Example
The following script is a scheduled script that performs a customer search. Use the
setPercentComplete and getPercentComplete methods to define percentage complete values
and then get the values. When getPercentComplete is called, the value appears in the
%Complete column in the Scheduled Script Status page. Access this page by going to Setup >
Customization > Script Deployments > Status. See Using the Scheduled Script Status Page for
more information about this page.
function customerSearch(type)
{
var ctx = nlapiGetContext(); // instantiate the nlobjContext object
var searchresults = nlapiSearchRecord('customer', 21); // execute a specific saved search
ctx.setPercentComplete(0.00); // set the percent complete parameter to 0.00
for ( i = 0; i < searchresults.length; i++ ) // loop through the search results
{
// get the internal ID of each returned record, otherwise you cannot update the results
var recid = searchresults[i].getValue('internalid');
var record = nlapiLoadRecord('customer', recid); // load each record from the search
record.setFieldText('salesrep', 'John Doe'); // set a field display value for Sales Rep
var id = nlapiSubmitRecord(record, true); // submit the record
ctx.setPercentComplete( (100* i)/ searchresults.length ); // calculate the results
// displays the percentage complete in the %Complete column on
// the Scheduled Script Status page
ctx.getPercentComplete(); // displays percentage complete
}
}
Standard Objects | UI Objects | SuiteScript Functions
setSessionObject(name, value)
Use this method to add or set the value of a user-defined session object for the current user.
This value is valid during the current user's login.
This call allows the user to temporarily save something to the session before persisting it in a
custom record.
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
Parameters
•
name {string} [required] - The key used to store the session object
•
value {string} [required] - The value to associate with this key in the user's session
Returns
•
void
Since
•
Version 2009.2
Example
This example shows how to get the value of the current user’s session, and then create a new
“Contact” session for the user to gather information about the user’s scope, budget, and
business problem.
function displayContact(request, response)
{
var ctx = nlapiGetContext();
var step = ctx.getSessionObject('stage');
if( step == null || step == "")
{
step = "create";
ctx.setSessionObject('stage', 'Contact');
}
if(step == "create");
{
ctx.setSesssionObject('scope', request.getParameter('scope') );
ctx.setSessionObject('approved', request.getParameter('budget') );
ctx.setSessionObject('problem', request.getParameter('businessproblem') );
}
}
Standard Objects | UI Objects | SuiteScript Functions
setSetting(type, name, value)
Sets the value of a script or user-defined setting. Only available in server scripts.
•
type{string} [required] - The type of script/system setting
• SESSION - session variable (volatile setting defined per session)
•
name{string} [required]- The name of the script/system setting
•
value {string} [required]- The new value for the script/system setting
SuiteScript Developer and Reference Guide
593
SuiteScript Objects
Standard Objects
594
Returns
•
void
Important: You can also use the nlobjContext.getSessionObject(name) method to set session
variable directly.
Standard Objects | UI Objects | SuiteScript Functions
nlobjCSVImport
Primary object used to encapsulate a CSV import job. This object is passed as a parameter by
nlapiSubmitCSVImport(nlobjCSVImport), which is used to asynchronously import record
data into NetSuite.
Use nlapiCreateCSVImport( ) to return an nlobjCSVImport object. You can then use the
object’s methods to populate it with the desired information.
nlobjCSVImport Methods
•
setLinkedFile(file)
•
setMapping(savedImport)
•
setOption(jobName)
•
setPrimaryFile(file)
Warning: You should execute setMapping(savedImport) before any of the other
methods. If you try to first execute setPrimaryFile(file), an error is returned.
setLinkedFile(file)
Sets the data to be imported in a linked file for a multi-file import job, by referencing a file in
the file cabinet using nlapiLoadFile, or by inputting CSV data as raw string.
If an import job requires multiple linked files, this method can be executed multiple times,
once for each linked file.
Parameters
•
file {string} [required] - Can be one of the following:
• The internal ID, as shown in the file cabinet, of the CSV file containing data to be
imported, referenced by nlapiLoadFile, preceded by an identifier for the record
sublist for which data is being imported. For example:
setLinkedFile(“item”, nlapiLoadFile(74))
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
595
A list of sublist internal IDs is available in Scriptable Sublists.
• Raw string of the data to be imported.
Returns
•
void
Since
•
Version 2012.2
Standard Objects | UI Objects | SuiteScript Functions
setMapping(savedImport)
Sets the name of the saved import map to be used for an import, by referencing the internal ID
or script ID of the import map.
Parameters
•
savedImport {string} [required] - The internal ID or script ID of the saved mapping to
use for the import job. The internal ID is system-defined and is displayed in the ID
column at Setup > Import/Export > Saved CSV Imports. The script ID can be defined
in the Import Assistant and is also displayed on this page.
Returns
•
void
Since
•
Version 2012.2
Standard Objects | UI Objects | SuiteScript Functions
setOption(jobName)
Sets the name of the import job to be shown on the status page for CSV imports.
Parameters
•
jobName {string} [required] - The text to be displayed in the Job Name column at
Setup > Import/Export > View CSV Import Status. The default job name format is:
<import type> - <csv file name> - <email address of logged-in user>.
Returns
•
void
Since
•
Version 2012.2
Standard Objects | UI Objects | SuiteScript Functions
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
596
setPrimaryFile(file)
Sets the data to be imported in the primary file for an import job, by referencing a file in the file
cabinet using nlapiLoadFile, or by inputting CSV data as raw string.
Parameters
•
file {string} [required] - Can be one of the following:
• The internal ID, as shown in the file cabinet, of the CSV file containing data to be
imported, referenced by nlapiLoadFile. For example:
setPrimaryFile(nlapiLoadFile(73))
• Raw string of the data to be imported.
Returns
•
void
Since
•
Version 2012.2
Standard Objects | UI Objects | SuiteScript Functions
nlobjError
Primary object used to encapsulate errors in the system. Note that the nlapiCreateError(code,
details, suppressNotification) function returns a reference to this object.
nlobjError Methods
•
getCode()
•
getDetails()
•
getId()
•
getInternalId()
•
getStackTrace()
•
getUserEvent()
getCode()
Returns the error code for this system or user-defined error
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
597
Returns
•
The error code as a string
Since
•
Version 2008.2
Example
The following script tries to send out an email following the submit of a new record. In the
event that an error is thrown, an execution log entry is created and the script continues (user is
redirected to the record in EDIT mode).
function afterSubmit(type)
{
if ( type == 'create' )
{
try
{
var subject = 'A '+nlaiGetRecordType()+' with id '+nlapiGetRecordId()+' was just created';
nlapiSendEmail( '-5', 'alerts@company.com', subject );
}
catch ( e )
{
if ( e instanceof nlobjError )
nlapiLogExecution( 'DEBUG', 'system error', e.getCode() + '\n' + e.getDetails() )
else
nlapiLogExecution( 'DEBUG', 'unexpected error', e.toString() )
}
nlapiSetRedirectURL('RECORD', nlapiGetRecordType(), nlapiGetRecordId(), true);
}
}
Standard Objects | UI Objects | SuiteScript Functions
getDetails()
Returns the error message (user-defined or system) associated with this error
Returns
•
The string value of the error message
Since
•
Version 2008.2
Example
See the sample for getCode().
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
598
Standard Objects | UI Objects | SuiteScript Functions
getId()
Returns an error reference ID. If you have included a catch block in your code, you can use
getId() to get the internal reference number for an unexpected error. This method is useful if
you want to keep your own log of error numbers or you want to email the value of getId() to
someone else.
Also note that if you have to call Technical Support to help you resolve a SuiteScript issue, this
ID may be helpful to your Support rep in diagnosing the problem.
Note: If you do not use getId() to programmatically get the ID, you can also view the ID in
the UI. After a script has executed, the script’s error ID (if there is an error) appears
on the Execution Log subtab of the Script Deployment page. The ID also appears
on the Execution Log subtab in the SuiteScript Debugger. Finally, if you have
chosen to be emailed whenever there is a problem with a script, the error ID is
provided in the email that is sent to you.
Returns
•
The error ID as a string
Since
•
Version 2008.2
Standard Objects | UI Objects | SuiteScript Functions
getInternalId()
Returns the internal ID of the submitted record if this error was thrown in an afterSubmit
script
Returns
•
The the internal ID of the submitted record as an integer
Since
•
Version 2008.2
Standard Objects | UI Objects | SuiteScript Functions
getStackTrace()
Returns the stacktrace containing the location of the error
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
599
Returns
•
String[]
Since
•
Version 2008.2
Standard Objects | UI Objects | SuiteScript Functions
getUserEvent()
Return the name of the user event script (if applicable) that the error was thrown from.
Returns
•
The string value of the user event that threw the error - for example, beforeLoad,
beforeSubmit, or afterSubmit
Since
•
Version 2008.2
Standard Objects | UI Objects | SuiteScript Functions
nlobjFile
Primary object used to encapsulate files (media items) in the NetSuite file cabinet. For an
example that shows how to use several the of File object methods to upload a file to the
NetSuite file cabinet and also attach the file to a record, see Uploading Files to the File Cabinet
Using SuiteScript in the NetSuite Help Center.
Important: In SuiteScript there is a 5MB limitation to the size of the file/document that
can be created, submitted, or accessed using file APIs such as nlapiLoadFile,
nlapiPrintRecord, nlapiMergeRecord, nlapiXMLToPDF, nlapiSubmitFile, and
nlapiCreateFile.
nlobjFile Methods
•
getDescription()
•
getFolder()
•
getId()
•
getName()
•
getSize()
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
•
getType()
•
getURL()
•
getValue()
•
isInactive()
•
isOnline()
•
setDescription(description)
•
setEncoding(encodingType)
•
setFolder(id)
•
setIsInactive(inactive)
•
setIsOnline(online)
•
setName(name)
600
Note: The following functions return a reference to nlobjFile:
•
nlapiCreateFile(name, type, contents)
•
nlapiLoadFile(id)
•
nlapiMergeRecord(id, baseType, baseId, altType, altId, fields)
•
nlapiPrintRecord(type, id, mode, properties)
getDescription()
Returns
•
The string description of the file. This is the description that appears in the
Description field on the folder or file record.
Since
•
Version 2009.1
Standard Objects | UI Objects | SuiteScript Functions
getFolder()
Returns
•
Integer: The internal ID of the file's folder within the NetSuite file cabinet, for example
10, 2, etc.
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
601
Since
•
Version 2009.1
Standard Objects | UI Objects | SuiteScript Functions
getId()
Returns the internal ID of the file (if the file is stored in the NetSuite file cabinet)
Returns
•
The integer value of file ID, for example 8, 108, 11, etc. This is the ID that appears in
the Internal ID column next to the file in the file cabinet.
Since
•
Version 2009.1
Standard Objects | UI Objects | SuiteScript Functions
getName()
Returns the name of the file
Returns
•
The string value of the file name
Standard Objects | UI Objects | SuiteScript Functions
getSize()
Returns the size of the file in bytes
Returns
•
The integer value of the file size
Since
•
Version 2009.1
Standard Objects | UI Objects | SuiteScript Functions
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
getType()
Returns the type of the file
Returns
•
The string value of the file type - for example, PDF, CSV, PLAINTEXT. (For a list of
supported file type IDs, see Supported File Types.)
Since
•
Version 2009.1
Standard Objects | UI Objects | SuiteScript Functions
getURL()
Returns the URL to the file if it is stored in the NetSuite file cabinet
Returns
•
The URL as a string
Since
•
Version 2009.1
Standard Objects | UI Objects | SuiteScript Functions
getValue()
Returns the contents of the file (base 64 encoded for binary files)
Returns
•
The string value of the file contents
Since
•
Version 2009.1
Standard Objects | UI Objects | SuiteScript Functions
isInactive()
Returns
•
Boolean: The file's inactive status as either true or false. Returns true if the file is
inactive.
SuiteScript Developer and Reference Guide
602
SuiteScript Objects
Standard Objects
603
Since
•
Version 2009.1
See also
•
setIsInactive(inactive)
Standard Objects | UI Objects | SuiteScript Functions
isOnline()
Returns
•
Boolean: The file's online status as either true or false. Returns true if the file is
“Available without Login.”
Since
•
Version 2009.1
See also
•
setIsOnline(online)
Standard Objects | UI Objects | SuiteScript Functions
setDescription(description)
Sets the description of the file
Parameters
•
description {string} [required] - A description of the file. This description will appear
in the Description field on the folder or file record.
Returns
•
void
Since
•
Version 2009.1
Standard Objects | UI Objects | SuiteScript Functions
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
setEncoding(encodingType)
Sets the character encoding of a file. The available encoding types are as follows:
•
UTF-8
•
windows-1252
•
ISO-8859-1
•
GB18030
•
GB2312
•
SHIFT_JIS
•
MacRoman
Parameters
•
encodingType {string} [required] - The type of encoding for the file.
Returns
•
void
Since
•
Version 2010.1
Example
var newFile = nlapiCreateFile('Chinese.csv', 'CSV', csvText);
newFile.setFolder(csvFolderId);
newFile.setEncoding('UTF-8');
nlapiSubmitFile(newFile);
Standard Objects | UI Objects | SuiteScript Functions
setFolder(id)
Sets the internal ID of the folder that the file is in
Parameters
•
id {int} [required] - The internal ID of the file’s folder, for example 10, -4, 20, etc.
Returns
•
void
Since
•
Version 2009.1
SuiteScript Developer and Reference Guide
604
SuiteScript Objects
Standard Objects
605
Standard Objects | UI Objects | SuiteScript Functions
setIsInactive(inactive)
Sets the file's inactive status. When you inactive a file or folder, it no longer appears on lists
unless (in the UI) you have selected the Show Inactives check box.
Note: The Show Inactives check box appears in the bottom-left corner of the Folders list.
Navigate to the Folders list by going to Documents > Files > File Cabinet.
Parameters
•
inactive {boolean} [required] - The file's inactive status. Set to true to inactive the file.
Set to false to make the file active.
Returns
•
void
Since
•
Version 2009.1
Standard Objects | UI Objects | SuiteScript Functions
setIsOnline(online)
Sets the file's online (“Available without Login”) status. When a file is online, other users can
download the file without a login session. This means you can upload images, MP3, or any
othe file type to the file cabinet and give other users the file URL without giving them access to
the account.
Parameters
•
online {boolean} [required] - The file’s updated online status. Set to true to make the
file available online. Set to false if you do not want the file available online.
Returns
•
void
Since
•
Version 2009.1
Standard Objects | UI Objects | SuiteScript Functions
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
setName(name)
Sets the name of the file
Parameters
•
name {string} [required]- The name of the file
Returns
•
void
Since
•
Version 2009.1
Standard Objects | UI Objects | SuiteScript Functions
Uploading Files to the File Cabinet Using SuiteScript
This sample shows how to upload a file into the NetSuite file cabinet. It also shows how to
attach this same file to a particular record. See the screenshots after this sample for more
details.
Note: There is a 5MB limitation to the size of the document that can be submitted using the
nlapiSubmitFile function.
Example
function uploader(request, response)
{
if (request.getMethod() == 'GET')
{
var form = nlapiCreateForm('Attach File to Customer');
var entityField = form.addField('entity', 'select', 'Customer', 'customer');
entityField.setLayoutType('normal', 'startcol')
entityField.setMandatory(true)
var fileField = form.addField('file', 'file', 'Select File');
fileField.setMandatory(true)
form.addSubmitButton();
form.addResetButton();
response.writePage(form);
}
else
{
var entity = request.getParameter("entity")
var file = request.getFile("file")
// set the folder where this file will be added. In this case, 10 is the internal ID
// of the SuiteScripts folder in the NetSuite file cabinet
file.setFolder(10)
SuiteScript Developer and Reference Guide
606
SuiteScript Objects
Standard Objects
607
// now create file and upload it to the file cabinet. You must use nalpiSubmitFile
// to upload a file to the file cabinet. See nlapiSubmitFile(file).
var id = nlapiSubmitFile(file)
// now attach file to customer record
nlapiAttachRecord("file", id, "customer", entity)
// now navigate to customer record
response.sendRedirect('record', 'customer', entity)
}
}
The following figure shows the output of this script. To attach a file to a particular customer,
specify the customer in the Customer field. Next, select a file from the Select File field. Click
Save when finished.
After clicking Save, you are redirected to the customer record that was specified in the
Customer field. In this case, the customer is Abe Simpson (see the following figure).
When the Abe Simpson customer record opens, click the Files subtab to verify that the file you
selected was attached to the record. In this case, the file is a txt file called sample file.
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
608
You can also go to the NetSuite file cabinet to verify that sample file.txt was uploaded to the
SuiteScripts folder. Navigate to the SuiteScripts folder by going to Documents > Files >
SuiteScripts.
The following figure shows the sample text.txt file in the SuiteScript folder.
nlobjLogin
Primary object used to encapsulate NetSuite user login credentials.
Methods
•
changeEmail(currentPassword, newEmail, justThisAccount)
•
changePassword(currentPassword, newPassword)
Note: The following function returns a reference to nlobjLogin:
•
nlapiGetLogin()
changeEmail(currentPassword, newEmail, justThisAccount)
Sets the logged-in user’s email address to a new one.
Parameters
•
currentPassword {string} [required] - The current password of the logged-in user. If a
valid value is not specified, an error will be thrown.
•
newEmail {string} [required] - The new email address for the logged-in user. If a valid
value is not specified, an error will be thrown.
•
justThisAccount {boolean} [optional] - If not set, this argument defaults to true. If set to
true, the email address change is applied only to roles within the current account. If set
to false, the email address change is applied to all accounts and roles.
Since
•
Version 2012.2
Example
This example shows how to change the logged-in user’s email address.
//Get the logged-in user’s credentials
var login = nlapiGetLogin();
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
609
//Change current email address
login.changeEmail(‘MycUrr3ntPa$$word’, ‘newemail@netsuite.com’, true);
Standard Objects | UI Objects | SuiteScript Functions
changePassword(currentPassword, newPassword)
Sets the logged-in user’s password to a new one.
Parameters
•
currentPassword {string} [required] - The current password of the logged-in user. If a
valid value is not specified, an error will be thrown.
•
newPassword {string} [required] - The new password for the logged-in user. If a valid
value is not specified, an error will be thrown.
Since
•
Version 2012.2
Example
This example shows how to change the logged-in user’s password.
//Get the currently logged-in user credentials
var login = nlapiGetLogin();
//Change current password
login.changePassword(‘MycUrr3ntPa$$word’, ‘MyNeWPaSw0rD!’);
Standard Objects | UI Objects | SuiteScript Functions
nlobjPivotColumn
Object used to encapsulate a pivot table column.
Methods
•
getAlias()
•
getParent()
•
getLabel()
•
getSummaryLine()
•
getValue()
•
getVisibleChildren()
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
•
isHidden()
getAlias()
Get the column alias.
Returns
•
string - The column alias.
Since
•
Version 2012.2
Standard Objects | UI Objects | SuiteScript Functions
getParent()
Get the parent column.
Returns
•
nlobjPivotColumn - Null if it does not exist
Since
•
Version 2012.2
Standard Objects | UI Objects | SuiteScript Functions
getLabel()
Get the column label.
Returns
•
string - Column label
Since
•
Version 2012.2
Standard Objects | UI Objects | SuiteScript Functions
getSummaryLine()
Get the summary line.
SuiteScript Developer and Reference Guide
610
SuiteScript Objects
Standard Objects
Returns
•
nlobjPivotColumn - Summary line if it exists, otherwise null
Since
•
Version 2012.2
Standard Objects | UI Objects | SuiteScript Functions
getValue()
Get the value of the column.
Returns
•
object - The value of this column
Since
•
Version 2012.2
Standard Objects | UI Objects | SuiteScript Functions
getVisibleChildren()
Get any defined children columns.
Returns
•
nlobjPivotColumn[] - Null if no children columns exist
Since
•
Version 2012.2
Standard Objects | UI Objects | SuiteScript Functions
isHidden()
Checks if the column is hidden.
Returns
•
boolean - True if the column is hidden
Since
•
Version 2012.2
SuiteScript Developer and Reference Guide
611
SuiteScript Objects
Standard Objects
Standard Objects | UI Objects | SuiteScript Functions
nlobjPivotRow
Object used to encapsulate a pivot table row.
Methods
•
getAlias()
•
getChildren()
•
getLabel()
•
getParent()
•
getSummaryLine()
•
getValue()
•
getValue(pivotColumn)
•
isDetailLine()
getAlias()
Get the row alias.
Returns
•
string - The row alias.
Since
•
Version 2012.2
Standard Objects | UI Objects | SuiteScript Functions
getChildren()
Get the children rows if there are any.
Returns
•
nlobjPivotRow[] - Null if the row is a detail line or if there are no children.
Since
•
Version 2012.2
SuiteScript Developer and Reference Guide
612
SuiteScript Objects
Standard Objects
Standard Objects | UI Objects | SuiteScript Functions
getLabel()
Get the row label.
Returns
•
string - The row label.
Since
•
Version 2012.2
Standard Objects | UI Objects | SuiteScript Functions
getParent()
Get the parent row if it exists.
Returns
•
nlobjPivotRow - Null if the row does not exist.
Since
•
Version 2012.2
Standard Objects | UI Objects | SuiteScript Functions
getSummaryLine()
Get the summary line from the report.
Returns
•
nlobjPivotRow - Null if the row is a detail line.
Since
•
Version 2012.2
Standard Objects | UI Objects | SuiteScript Functions
getValue()
Get the row value if the row is a detail line.
SuiteScript Developer and Reference Guide
613
SuiteScript Objects
Standard Objects
Returns
•
object - The value of the row hierarchy, or null if isDetailLine returns false.
Since
•
Version 2012.2
Standard Objects | UI Objects | SuiteScript Functions
getValue(pivotColumn)
Get the value of the row/column combination.
Parameters
•
pivotColumn {nlobjPivotColumn} [required] - The pivot column.
Returns
•
object - The value of the row/column combination, or null if isDetailLine returns
false.
Since
•
Version 2012.2
Standard Objects | UI Objects | SuiteScript Functions
isDetailLine()
Check if the row is a detail line.
Returns
•
boolean - True if the row is a detail line.
Since
•
Version 2012.2
Standard Objects | UI Objects | SuiteScript Functions
nlobjPivotTable
Object used to encapsulate the pivot table.
SuiteScript Developer and Reference Guide
614
SuiteScript Objects
Standard Objects
Methods
•
getColumnHierarchy()
•
getRowHierarchy()
getColumnHierarchy()
Get the column hierarchy.
Returns
•
nlobjPivotColumn
Since
•
Version 2012.2
Standard Objects | UI Objects | SuiteScript Functions
getRowHierarchy()
Get the row hierarchy.
Returns
•
nlobjPivotRow
Since
•
Version 2012.2
Standard Objects | UI Objects | SuiteScript Functions
nlobjPivotTableHandle
Handle to the pivot table object. A handle is a reference which points to the pivot table.
Methods
•
getPivotTable()
•
isReady()
getPivotTable()
Get the pivot table object from the report definition.
SuiteScript Developer and Reference Guide
615
SuiteScript Objects
Standard Objects
Note: This is a blocking call and it will wait until the report definition execution has
finished. Using isReady() is recommended to check execution state if blocking is
unacceptable.
Returns
•
nlobjPivotTable
Since
•
Version 2012.2
Standard Objects | UI Objects | SuiteScript Functions
isReady()
Returns the completion status flag of the report definition execution.
Returns
•
boolean - True if the execution has finished.
Since
•
Version 2012.2
Standard Objects | UI Objects | SuiteScript Functions
nlobjRecord
Primary object used to encapsulate a NetSuite record.
Methods
•
commitLineItem(group)
•
createCurrentLineItemSubrecord(sublist, fldname)
•
createSubrecord(fldname)
•
editCurrentLineItemSubrecord(sublist, fldname)
•
getCurrentLineItemValues(type, fldname)
•
editSubrecord(fldname)
•
findLineItemMatrixValue(group, fldnam, column, val)
•
findLineItemValue(group, fldnam, value)
SuiteScript Developer and Reference Guide
616
SuiteScript Objects
Standard Objects
•
getAllFields()
•
getAllLineItemFields(group)
•
getCurrentLineItemMatrixValue(group, fldnam, column)
•
getField(fldnam)
•
getFieldText(name)
•
getFieldTexts(name)
•
getFieldValue(name)
•
getFieldValues(name)
•
getId()
•
getLineItemCount(group)
•
getLineItemField(group, fldnam, linenum)
•
getLineItemMatrixField(group, fldnam, linenum, column)
•
getLineItemMatrixValue(group, fldnam, lineum, column)
•
getLineItemText(group, fldnam, linenum)
•
getLineItemValue(group, name, linenum)
•
getLineItemValues(type, fldname, linenum)
•
getMatrixCount(group, fldnam)
•
getMatrixField(group, fldname, column)
•
getMatrixValue(group, fldnam, column)
•
getRecordType()
•
insertLineItem(group, linenum)
•
removeLineItem(group, linenum)
•
removeCurrentLineItemSubrecord(sublist, fldname)
•
removeSubrecord(fldname)
•
selectLineItem(group, linenum)
•
selectNewLineItem(group)
•
setCurrentLineItemMatrixValue(group, fldnam, column, value)
•
setCurrentLineItemValue(group, name, value)
•
setFieldText(name, text)
•
setFieldTexts(name, text)
SuiteScript Developer and Reference Guide
617
SuiteScript Objects
Standard Objects
•
setFieldValue(name, value)
•
setFieldValues(name, value)
•
setLineItemValue(group, name, linenum, value)
•
setMatrixValue(group, fldnam, column, value)
•
viewCurrentLineItemSubrecord(sublist, fldname)
•
viewLineItemSubrecord(sublist, fldname, linenum)
•
viewSubrecord(fldname)
618
Note: The following functions return a reference to the nlobjRecord object:
•
nlapiCopyRecord(type, id, initializeValues)
•
nlapiCreateRecord(type, initializeValues)
•
nlapiGetNewRecord()
•
nlapiGetOldRecord()
•
nlapiLoadRecord(type, id, initializeValues)
•
nlapiTransformRecord(type, id, transformType, transformValues)
commitLineItem(group)
Use this method to commit the current line in a sublist.
Parameters
•
group {string} [required] - The sublist internal ID (for example, use addressbook as the
ID for the Address sublist). In the NetSuite Help Center, see Scriptable Sublists for a list
of sublists that support SuiteScript, as well as all internal IDs associated with each
sublist.
Returns
•
void
Since
•
Version 2009.2
Example
This sample shows how to create a new Vendor Bill record and then add items to the Item
sublist and expenses to the Expenses sublist. Note that because you are adding new lines to
each sublist, you must call the selectNewLineItem(group) method. You then set all values for
the new lines using the setCurrentLineItemValue(group, name, value) method. When you are
finished adding values to each sublist, you must commit all sublist updates using the
commitLineItem(group) method.
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
619
var record = nlapiCreateRecord('vendorbill');
record.setFieldValue('entity', 196);
record.setFieldValue('department', 3);
record.selectNewLineItem('item');
record.setCurrentLineItemValue('item','item', 380);
record.setCurrentLineItemValue('item', 'location', 102);
record.setCurrentLineItemValue('item', 'amount', '2');
record.setCurrentLineItemValue('item', 'customer', 294);
record.setCurrentLineItemValue('item','isbillable', 'T');
record.commitLineItem('item');
record.selectNewLineItem('expense');
record.setCurrentLineItemValue('expense','category', 3);
record.setCurrentLineItemValue('expense', 'account', 11);
record.setCurrentLineItemValue('expense', 'amount', '10');
record.setCurrentLineItemValue('expense','customer', 294);
record.setCurrentLineItemValue('expense','isbillable', 'T');
record.commitLineItem('expense');
var id = nlapiSubmitRecord(record, true);
Standard Objects | UI Objects | SuiteScript Functions
createCurrentLineItemSubrecord(sublist, fldname)
Returns a nlobjSubrecord object. Use this API to create a subrecord from a sublist field on the
parent record.
This API is currently used only in the context of the Advanced Bin / Numbered Inventory
feature. For information, see Using SuiteScript with Advanced Bin / Numbered Inventory
Management.
Also see Working with Subrecords in SuiteScript for general information on working with
subrecords in NetSuite.
Parameters
•
sublist {string} [required] - The sublist internal ID on the parent record (for example,
use item as the ID for the Items sublist).
•
fldname {string} [required] - The internal ID of the “subrecord field” on the sublist of
the parent record (for example, inventorydetail as the ID for the Inventory Details
sublist field).
Returns
•
nlobjSubrecord
Since
•
Version 2011.2
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
620
Example
See Creating a subrecord in the NetSuite Help Center.
Standard Objects | UI Objects | SuiteScript Functions
createSubrecord(fldname)
Returns a nlobjSubrecord object. Use this API to create a subrecord from a body field on the
parent record.
This API is currently used only in the context of the Advanced Bin / Numbered Inventory
feature. For information, see Using SuiteScript with Advanced Bin / Numbered Inventory
Management.
Also see Working with Subrecords in SuiteScript for general information on working with
subrecords in NetSuite.
Parameters
•
fldname {string} [required] - The internal ID of the “subrecord field” on the body of
the parent record (for example, inventorydetail as the ID for the Inventory Details body
field).
Returns
•
nlobjSubrecord
Since
•
Version 2011.2
Example
See Creating a subrecord in the NetSuite Help Center.
Standard Objects | UI Objects | SuiteScript Functions
editCurrentLineItemSubrecord(sublist, fldname)
Returns a nlobjSubrecord object. Use this API to edit a subrecord from a sublist field on the
parent record.
This API is currently used only in the context of the Advanced Bin / Numbered Inventory
feature. For information, see Using SuiteScript with Advanced Bin / Numbered Inventory
Management. Also see Working with Subrecords in SuiteScript for general information on
working with subrecords in NetSuite.
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
621
Parameters
•
sublist {string} [required] - The sublist internal ID on the parent record (for example,
use item as the ID for the Items sublist).
•
fldname {string} [required] - The internal ID of the “subrecord field” on the sublist of
the parent record (for example, inventorydetail as the ID for the Inventory Details
sublist field).
Returns
•
nlobjSubrecord
Since
•
Version 2011.2
Example
See Editing a subrecord in the NetSuite Help Center.
Standard Objects | UI Objects | SuiteScript Functions
getCurrentLineItemValues(type, fldname)
Returns the values of a multiselect sublist field on the currently selected line. One example of a
multiselect sublist field is the Serial Numbers field on the Items sublist.
This function is not supported in client SuiteScript. It is meant to be used in user event scripts.
Parameters
•
type {string} [required] - The sublist internal ID (for example, use addressbook as the
ID for the Address sublist). In the NetSuite Help Center, see Scriptable Sublists for a list
of sublists that support SuiteScript, sublist internal IDs, and sublist field IDs.
•
fldnam {string} [required] - The name of the multiselect field
Returns
•
An array of string values for the multiselect sublist field
Since
•
Version 2012.1
Standard Objects | UI Objects | SuiteScript Functions
editSubrecord(fldname)
Returns a nlobjSubrecord object. Use this API to edit a subrecord from a body field on the
parent record.
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
622
This API is currently used only in the context of the Advanced Bin / Numbered Inventory
feature. For information, see Using SuiteScript with Advanced Bin / Numbered Inventory
Management. Also see Working with Subrecords in SuiteScript for general information on
working with subrecords in NetSuite.
Parameters
•
fldname {string} [required] - The internal ID of the “subrecord field” on the body of
the parent record (for example, inventorydetail as the ID for the Inventory Details body
field).
Returns
•
nlobjSubrecord
Since
•
Version 2011.2
Standard Objects | UI Objects | SuiteScript Functions
findLineItemMatrixValue(group, fldnam, column, val)
Use this method to return the line number of a particular price in a given column. If the value
is present on multiple lines, it will return the line item of the first line that contains the value.
Use this API on a matrix sublists only.
Note: Currently the Pricing sublist is the only matrix sublist type that supports SuiteScript. For
details on working with the Pricing sublist, see Pricing Sublist in the NetSuite Help Center.
Parameters
•
group {string} [required] - The sublist internal ID. In the NetSuite Help Center, see
Pricing Sublist Internal IDs to determine the correct internal ID of your pricing list.
•
fldnam {string} [required] - The internal ID of the matrix field
•
column {int} [required] - The column number for this field. Column numbers start at
1, not 0.
•
val {string} [required] - The value of the field
Returns
•
The line number (as an integer) of a specified matrix field
Since
•
Version 2009.2
Standard Objects | UI Objects | SuiteScript Functions
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
623
findLineItemValue(group, fldnam, value)
Use this API to return the line number for the first occurrence of a field value in a sublist
column. This API can be used on any sublist type that supports SuiteScript (editor, inline
editor, and list sublists).
Parameters
•
group {string} [required] - The sublist internal ID (for example, use addressbook as the
ID for the Address sublist). In the NetSuite Help Center, see Scriptable Sublists for a list
of sublists that support SuiteScript, as well as all internal IDs associated with each
sublist.
•
fldnam {string} [required] - The field internal ID
•
value {string} [required] - The value of the field
Returns
•
The line number (as an integer) of a specific sublist field
Since
•
Version 2009.2
Standard Objects | UI Objects | SuiteScript Functions
getAllFields()
Returns a normal keyed array of all the fields on a record. Note that the number of fields
returned will differ when you call getAllFields() on the edit of a record vs. on the xedit of a
record. For details, see these topics:
•
Inline Editing and nlapiGetNewRecord()
•
Inline Editing and nlapiGetOldRecord()
•
What’s the Difference Between xedit and edit User Event Types?
Returns
•
String[] of all field names on the record
Since
•
Version 2008.1
Standard Objects | UI Objects | SuiteScript Functions
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
624
getAllLineItemFields(group)
Returns an array of all the field names of a sublist on this record
Parameters
•
group {string} [required]- The sublist internal ID (for example, use addressbook as the
ID for the Address sublist). In the NetSuite Help Center, see Scriptable Sublists for a list
of sublists that support SuiteScript, as well as all internal IDs associated with each
sublist.
Returns
•
String[] of sublist field names
Since
•
Version 2008.2
Standard Objects | UI Objects | SuiteScript Functions
getCurrentLineItemMatrixValue(group, fldnam, column)
Use this API to get the value of the currently selected matrix field. This API should be used on
matrix sublists only.
Important: Currently the Pricing sublist is the only matrix sublist type that supports
SuiteScript. For details on working with the Pricing sublist, see Pricing Sublist in the NetSuite
Help Center.
Parameters
•
group {string} [required] - The sublist internal ID. In the NetSuite Help Center, see
Pricing Sublist Internal IDs to determine the correct internal ID of your pricing list.
•
fldnam {string} [required] - The internal ID of the matrix field being set.
•
column {int} [required] - The column number for this field. Column numbers start at
1, not 0.
Returns
•
The string value of a field on the currently selected line in a matrix sublist. Returns null
if the field does not exist.
Since
•
Version 2009.2
Standard Objects | UI Objects | SuiteScript Functions
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
625
getField(fldnam)
Returns field metadata for a field
Parameters
•
fldnam {string} [required] - The internal ID of the field
Returns
•
The nlobjField object
Since
•
Version 2009.1
Standard Objects | UI Objects | SuiteScript Functions
getFieldText(name)
Returns the UI display value for a select field. This method is supported on select fields only.
Parameters
•
name {string} [required] - The internal ID of the field
Returns
•
String UI display value corresponding to the current selection for a select field.
Returns null if field does not exist on the record or if the field is restricted.
Since
•
Version 2009.1
Example
The sample below shows how to use getFieldText(name). In this sample, the script will return
the UI display value of the Sales Rep (salesrep) field. In this account, the Sales Rep has been set
to Abe Simpson. This is the value that will be returned.
var rec = nlapiLoadRecord('salesorder', 1957);
var valText = rec.getFieldText('salesrep'); // returns Abe Simpson
See also
•
nlapiGetFieldText(fldnam) - this is the form-level client-side equivalent of
nlobjRecord.getFieldText(name).
Standard Objects | UI Objects | SuiteScript Functions
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
626
getFieldTexts(name)
Returns the UI display values for a multi-select field. This method is supported on multi-select
fields only.
Parameters
•
name {string} [required] - The internal ID of the multiselect field
Returns
•
String[] - Returns the selected text values of a multi-select field
Since
•
Version 2009.1
Example
The sample below shows how to use getFieldTexts(name). In this sample, the script will return
the UI display values of a custom multiselect field that references customers in the account.
The internal ID for the multiselect field is custbody23. In this account, the multiselect field has
the display values of 104 Lou Liang and 105 Barry Springsteen. These are the values that will
be returned.
var rec = nlapiLoadRecord('salesorder', 1957); // load the sales order
var valText = rec.getFieldTexts('custbody23'); // returns 104 Lou Liang and 105 Barry Springsteen
See also
nlapiGetFieldTexts(fldnam) - this is the form-level client-side equivalent of
nlobjRecord.getFieldTexts(name).
Standard Objects | UI Objects | SuiteScript Functions
getFieldValue(name)
Returns the value of a field.
Note that NetSuite recommends you read the topic Getting Field Values in SuiteScript, which
addresses the rare instances in which the value returned by this API is inconsistent.
Parameters
•
name {string} [required] - The internal ID of the field whose value is being returned.
Returns
•
The internal ID (string) value for the field
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
627
Example
In this sample, the script returns the internal ID of the value in the Partner (partner) field. In
this particular sales order, the Partner field has been set to ABC Inc., which has an internal ID
value of 219. The value 219 will be returned in this script.
var rec = nlapiLoadRecord('salesorder', 18); // load a sales order
var value = rec.getFieldValue('partner'); // get internal ID value of the Partner field
Standard Objects | UI Objects | SuiteScript Functions
getFieldValues(name)
Returns a read-only array of multi-select field values
Parameters
•
name {string} [required]- The name of the field whose value is being returned
Returns
•
String[] of field IDs. Returns null if field is not on the record.
Example
In this sample, the script returns an array of internal ID values that are set in a custom multiselect field called Advertising Preferences. (In this account, the internal ID of the Advertising
Preferences field is custentity1.)
In the UI, the Advertising Preferences field has the values of E-mail and Mail. The internal ID
values for E-mail and Mail are 2 and 3, respectively. The values of 2 and 3 will be returned in
this script.
var rec = nlapiLoadRecord('customer', 196); // load a customer record
var values = rec.getFieldValues('custentity1'); //get array of internal ID values set in custentity1 field
Standard Objects | UI Objects | SuiteScript Functions
getId()
Use this method to get the internal ID of a record or NULL for new records.
Returns
•
Integer value of the record ID
Standard Objects | UI Objects | SuiteScript Functions
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
628
getLineItemCount(group)
Returns the number of lines on a sublist
Important: The first line number on a sublist is 1 (not 0).
Parameters
•
group {string} [required]- The sublist internal ID (for example, use addressbook as the
ID for the Address sublist). In the NetSuite Help Center, see Scriptable Sublists for a list
of sublists that support SuiteScript, as well as all internal IDs associated with each
sublist.
Returns
•
The integer value of the number of line items on a sublist
Standard Objects | UI Objects | SuiteScript Functions
getLineItemField(group, fldnam, linenum)
Returns field metadata for a line item (sublist) field
Parameters
•
group {string} [required] - The sublist internal ID (for example, use addressbook as the
ID for the Address sublist). In the NetSuite Help Center, see Scriptable Sublists for a list
of sublists that support SuiteScript, as well as all internal IDs associated with each
sublist.
•
fldnam {string} [required] - The internal ID of the line item field
•
linenum {int} [required] - The line number this field is on. Note the first line number
on a sublist is 1 (not 0). Only settable for sublists of type list.
Returns
•
An nlobjField object
Since
•
Version 2009.1
Standard Objects | UI Objects | SuiteScript Functions
getLineItemMatrixField(group, fldnam, linenum, column)
Use this API to obtain metadata for a field that appears in a matrix sublist.
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
629
Important: Currently the Pricing sublist is the only matrix sublist type that supports
SuiteScript. For details on working with the Pricing sublist, see Pricing Sublist in the NetSuite
Help Center.
Parameters
•
group {string} [required] - The sublist internal ID. In the NetSuite Help Center, see
Pricing Sublist Internal IDs to determine the correct internal ID of your pricing list.
•
fldnam {string} [required] - The internal ID of the field (line) whose value you want
returned.
•
linenum {int} [required] - The line number for this field. Note the first line number on
a sublist is 1 (not 0).
•
column {int} [required] - The column number for this field. Column numbers start at
1, not 0.
Returns
•
An nlobjField object representing this sublist field. Returns null if the field you have
specified does not exist.
Since
•
Version 2009.2
Example
record = nlapiLoadRecord('inventoryitem', 312);
var itemid = record.getFieldValue('itemid');
//Get the metadata for the price matrix field.
var matrixFieldObj = record.getLineItemMatrixField('price1', 'price', 1, 2);
var fieldLabel = matrixFieldObj.getLabel();
var fieldName = matrixFieldObj.getName();
var fieldType = matrixFieldObj.getType();
var fieldMetaInfo = 'Label: '+fieldLabel+' Name: '+fieldName+' Type: '+fieldType ;
record.setFieldValue('purchasedescription', fieldMetaInfo);
var id2 = nlapiSubmitRecord(record, true);
Standard Objects | UI Objects | SuiteScript Functions
getLineItemMatrixValue(group, fldnam, lineum, column)
Use this API to get the value of a matrix field that appears on a specific line in a specific
column. This API can be used only in the context of a matrix sublist.
Note: Currently the Pricing sublist is the only matrix sublist type that supports SuiteScript. For
details on working with the Pricing sublist, see Pricing Sublist in the NetSuite Help Center.
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
630
Parameters
•
group {string} [required] - The sublist internal ID. In the NetSuite Help Center, see
Pricing Sublist Internal IDs to determine the correct internal ID of your pricing list.
•
fldnam {string} [required] - The internal ID of the matrix field whose value you want
returned.
•
linenum {int} [required] - The line number for this field. Note the first line number on
a sublist is 1 (not 0).
•
column {int} [required] - The column number for this field. Column numbers start at 1
(not 0).
Returns
•
The string value of the matrix field
Since
•
Version 2009.2
Example
record = nlapiLoadRecord('inventoryitem', 333);
var itemid = record.getFieldValue('itemid');
var price1 = record.getLineItemMatrixValue('price1', 'price', 1, 1);
var price2 = record.getLineItemMatrixValue('price1', 'price', 2, 1);
Standard Objects | UI Objects | SuiteScript Functions
getLineItemText(group, fldnam, linenum)
Returns the display name of a select field (based on its current selection) in a sublist
Parameters
•
group {string} [required] - The sublist internal ID (for example, use addressbook as the
ID for the Address sublist). In the NetSuite Help Center, see Scriptable Sublists for a list
of sublists that support SuiteScript, as well as all internal IDs associated with each
sublist.
•
fldnam {string} [required] - The name of the field/line item being set
•
linenum {int} [required] - The line number for this field. Note the first line number on
a sublist is 1 (not 0).
Returns
•
String - The string UI display value corresponding to the current selection for a line
item select field. Returns null if field does not exist on the record or the field is
restricted.
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
631
Since
•
Version 2009.1
Example
The sample below shows how to set getLieItemText(type, fldnam, linenum). In this sample, the
script will return the UI display name value of the Item (item) field on the Item sublist. In this
account, the Item field has been set to Assorted Bandages. This is the value that will be
returned.
var rec = nlapiLoadRecord('salesorder', 1957);
var valText = rec.getFieldText('salesrep');
var line1txt= rec.getLineItemText('item', 'item', 1);
See also
•
nlapiGetLineItemText(type, fldnam, linenum) - this is the form-level client-side
equivalent of nlobjRecord.getLineItemText(...).
Standard Objects | UI Objects | SuiteScript Functions
getLineItemValue(group, name, linenum)
Returns the value of a sublist line item field.
Note that NetSuite recommends you read the topic Getting Field Values in SuiteScript, which
addresses the rare instances in which the value returned by this API is inconsistent.
Tip: Normally custom transaction column fields that are not checked to show on a custom
form are not available to get/setLineItemValue APIs. However, if you set them to show, but
then set the label to empty, they will be available on the form but will not appear on the sublist.
Note this does not apply to fields that are marked as Hidden on the custom field definition.
These fields are always available on every form.
Parameters
•
group {string} [required]- The sublist internal ID (for example, use addressbook as the
ID for the Address sublist). In the NetSuite Help Center, see Scriptable Sublists for a list
of sublists that support SuiteScript, as well as all internal IDs associated with each
sublist.
•
name {string} [required]- The name of the sublist field whose value is being returned
•
linenum {int} [required]- The line number for this field. Note the first line number on a
sublist is 1 (not 0).
Returns
•
The string value of the sublist field name
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
632
Since
•
Version 2008.1
Standard Objects | UI Objects | SuiteScript Functions
getLineItemValues(type, fldname, linenum)
Returns the values of a multiselect sublist field on a selected line. One example of a multiselect
sublist field is the Serial Numbers field on the Items sublist.
This function is not supported in client SuiteScript. It is meant to be used in user event scripts.
Parameters
•
type {string} [required] - The sublist internal ID (for example, use addressbook as the
ID for the Address sublist). In the NetSuite Help Center, see Scriptable Sublists for a list
of sublists that support SuiteScript, sublist internal IDs, and sublist field IDs.
•
fldnam {string} [required] - The internal ID of the multiselect field
•
linenum {int} [required] - The line number for this field. Note the first line number on
a sublist is 1 (not 0).
Returns
•
An array of string values for the multiselect sublist field
Since
•
Version 2012.1
Standard Objects | UI Objects | SuiteScript Functions
getMatrixCount(group, fldnam)
Use this API in a matrix sublist to get the number of columns for a specific matrix field.
Important: Currently the Pricing sublist is the only matrix sublist type that supports
SuiteScript. For details on working with the Pricing sublist, see Pricing Sublist in the NetSuite
Help Center.
Note: The first column in a matrix is 1, not 0.
Parameters
•
group {string} [required] - The sublist internal ID. In the NetSuite Help Center, see
Pricing Sublist Internal IDs to determine the correct internal ID of your pricing list.
•
fldnam {string} [required] - The field internal ID of the matrix field.
Returns
•
The integer value for the number of columns of a specified matrix field
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
633
Since
•
Version 2009.2
Example
record = nlapiLoadRecord('inventoryitem', 333);
var itemid = record.getFieldValue('itemid');
var count = record.getMatrixCount('price', 'price');
Standard Objects | UI Objects | SuiteScript Functions
getMatrixField(group, fldname, column)
Use this API to get field metadata for a matrix “header” field in a matrix sublist.
Important: Currently the Pricing sublist is the only matrix sublist type that supports
SuiteScript. For details on working with the Pricing sublist, see Pricing Sublist in the NetSuite
Help Center.
For example, if the Quantity Pricing feature is enabled in your account, you will see the Qty
fields at the top of the pricing matrix. The Qty fields are considered to be the header fields in
the pricing matrix. For more information on matrix header fields, see Matrix APIs in the
NetSuite Help Center.
Parameters
•
group {string} [required] - The sublist internal ID. In the NetSuite Help Center, see
Pricing Sublist Internal IDs to determine the correct internal ID of your pricing list.
•
fldnam {string} [required] - The internal ID of the matrix header field.
•
column {int} [required] - The column number for this field. Column numbers start at 1
(not 0).
Returns
•
nlobjField object
Since
•
Version 2009.2
Example
This sample shows how to get the metadata of the quantity (Qty) field on the USA Pricing tab.
record = nlapiLoadRecord('inventoryitem', 333);
var itemid = record.getFieldValue('itemid');
//Get the metadata of quantity field inside the USA Pricing tab
var fieldObj = record.getMatrixField('price1', 'price',1);
var fieldLabel = fieldObj.getLabel();
var fieldName = fieldObj.getName();
var fieldType = fieldObj.getType();
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
634
var fieldMetaInfo = 'Label: '+fieldLabel+' Name: '+fieldName+' Type: '+fieldType ;
record.setFieldValue('purchasedescription', fieldMetaInfo);
var id2 = nlapiSubmitRecord(record, true);
Standard Objects | UI Objects | SuiteScript Functions
getMatrixValue(group, fldnam, column)
Use this API to get the value of a matrix “header” field in a matrix sublist.
Important: Currently the Pricing sublist is the only matrix sublist type that supports
SuiteScript. For details on working with the Pricing sublist, see Pricing Sublist in the NetSuite
Help Center.
For example, if the Quantity Pricing feature is enabled in your account, you will see the Qty
fields at the top of the pricing matrix. The Qty fields are considered to be the header fields in
the pricing matrix. See Matrix APIs in the NetSuite Help Center for more information on
matrix header fields.
Parameters
•
group {string} [required] - The sublist internal ID. In the NetSuite Help Center, see
Pricing Sublist Internal IDs to determine the correct internal ID of your pricing list.
•
fldnam {string} [required] - The internal ID of the matrix header field.
•
column {int} [required] - The column number for this field. Column numbers start at 1
(not 0).
Returns
•
The string value of a matrix header field
Since
•
Version 2009.2
Example
record = nlapiLoadRecord('inventoryitem', 333);
var itemid = record.getFieldValue('itemid');
var quant1 = record.getMatrixValue('price1', 'price', '2');
record.setFieldValue('purchasedescription', quant1);
var id2 = nlapiSubmitRecord(record, true);
Standard Objects | UI Objects | SuiteScript Functions
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
635
getRecordType()
Returns the record type (for example assemblyunbuild would be returned for the Assembly
Unbuild record type; salesorder would be returned for the Sales Order record type).
Returns
•
The string value of the record name internal ID
Standard Objects | UI Objects | SuiteScript Functions
insertLineItem(group, linenum)
Inserts a new line into a sublist. This function is only supported for edit sublists (inlineeditor,
editor). Note, however, this API will work on list sublists that have been added via the UI object
nlobjSubList
Parameters
•
group {string} [required] - The sublist internal ID (for example, use addressbook as the
ID for the Address sublist). In the NetSuite Help Center, see Scriptable Sublists for a list
of sublists that support SuiteScript, as well as all internal IDs associated with each
sublist.
•
linenum {int} [required] - Line index at which to insert the line. Note that in sublists,
the first line number is 1 (not 0). If the number is greater than the number of lines on
the sublist, an error is returned.
Returns
•
void
Example
// insert line at the beginning of the item sublist
var rec = nlapiGetNewRecord();
rec.insertLineItem('item', 1);
rec.setLineItemValue('item', 'quantity', 1, 10);
// insert line at the end
// triggered in the beforeSubmit event
var rec = nlapiGetNewRecord();
var intCount = rec.getLineItemCount('item');
rec.insertLineItem('item', intCount + 1);
rec.setLineItemValue('item', 'quantity', intCount + 1, 10);
Standard Objects | UI Objects | SuiteScript Functions
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
636
removeLineItem(group, linenum)
Use this method to remove an existing line from a sublist.
Parameters
•
group {string} [required] - The sublist internal ID (for example, use addressbook as the
ID for the Address sublist). In the NetSuite Help Center, see Scriptable Sublists for a list
of sublists that support SuiteScript, as well as all internal IDs associated with each
sublist.
•
linenum {int} [required] - The line number for this field. Note the first line number on
a sublist is 1 (not 0).
Returns
•
void
Since
•
Version 2009.2
Example
for (j=1; j <= soRecord.getLineItemCount('item'); j++)
{
soRecord.removeLineItem('item','1');
}
Standard Objects | UI Objects | SuiteScript Functions
removeCurrentLineItemSubrecord(sublist, fldname)
Returns a nlobjSubrecord object. Use this API to remove a subrecord from a sublist field on the
parent record.
This API is currently used only in the context of the Advanced Bin / Numbered Inventory
feature. For information, see Using SuiteScript with Advanced Bin / Numbered Inventory
Management. Also see Working with Subrecords in SuiteScript for general information on
working with subrecords in NetSuite.
Parameters
•
sublist {string} [required] - The sublist internal ID on the parent record (for example,
use item as the ID for the Items sublist).
•
fldname {string} [required] - The internal ID of the “subrecord field” on the sublist of
the parent record (for example, inventorydetail as the ID for the Inventory Details
sublist field).
Returns
•
void
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
637
Since
•
Version 2011.2
Standard Objects | UI Objects | SuiteScript Functions
removeSubrecord(fldname)
Returns a nlobjSubrecord object. Use this API to remove a subrecord from a body field on the
parent record.
This API is currently used only in the context of the Advanced Bin / Numbered Inventory
feature. For information, see Using SuiteScript with Advanced Bin / Numbered Inventory
Management. Also see Working with Subrecords in SuiteScript for general information on
working with subrecords in NetSuite.
Parameters
•
fldname {string} [required] - The internal ID of the “subrecord field” on the body of
the parent record (for example, inventorydetail as the ID for the Inventory Details body
field).
Returns
•
void
Since
•
Version 2011.2
Example
See Removing a subrecord in the NetSuite Help Center.
Standard Objects | UI Objects | SuiteScript Functions
selectLineItem(group, linenum)
Use this method to select an existing line in a sublist.
Parameters
•
group {string} [required] - The sublist internal ID (for example, use addressbook as the
ID for the Address sublist). In the NetSuite Help Center, see Scriptable Sublists for a list
of sublists that support SuiteScript, as well as all internal IDs associated with each
sublist.
•
linenum {int} [required] - The line number for this field. Note the first line number on
a sublist is 1 (not 0).
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
638
Returns
•
void
Since
•
Version 2009.2
Example
var record = nlapiCreateRecord('inventoryitem');
record.setFieldValue('itemid', '124');
record.setFieldValue('department', 3);
record.setMatrixValue('price1', 'price', '2', 500);
record.selectLineItem('price', '1');
record.setCurrentLineItemMatrixValue('price', 'price', 1, '100');
record.setCurrentLineItemMatrixValue('price', 'price', 2, '90');
record.commitLineItem('price');
var id = nlapiSubmitRecord(record, true);
Standard Objects | UI Objects | SuiteScript Functions
selectNewLineItem(group)
Use this method to insert and select a new line in a sublist.
Parameters
•
group {string} [required] - The sublist internal ID (for example, use addressbook as the
ID for the Address sublist). In the NetSuite Help Center, see Scriptable Sublists for a list
of sublists that support SuiteScript, as well as all internal IDs associated with each
sublist.
Returns
•
void
Since
•
Version 2009.2
Example
This sample shows how to create a new Vendor Bill record and then add items to the Item
sublist and expenses to the Expenses sublist. Note that because you are adding new lines to
each sublist, you must call the selectNewLineItem(group) method. You then set all values for
the new lines using the setCurrentLineItemValue(group, name, value) method. When you are
finished adding values to each sublist, you must commit all sublist updates using the
commitLineItem(group) method.
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
639
var record = nlapiCreateRecord('vendorbill');
record.setFieldValue('entity', 196);
record.setFieldValue('department', 3);
record.selectNewLineItem('item');
record.setCurrentLineItemValue('item','item',380);
record.setCurrentLineItemValue('item', 'location', 102);
record.setCurrentLineItemValue('item', 'amount', '2');
record.setCurrentLineItemValue('item', 'customer', 294);
record.setCurrentLineItemValue('item','isbillable', 'T');
record.commitLineItem('item');
record.selectNewLineItem('expense');
record.setCurrentLineItemValue('expense','category', 3);
record.setCurrentLineItemValue('expense', 'account', 11);
record.setCurrentLineItemValue('expense', 'amount', '10');
record.setCurrentLineItemValue('expense','customer', 294);
record.setCurrentLineItemValue('expense','isbillable', 'T');
record.commitLineItem('expense');
var id = nlapiSubmitRecord(record, true);
Standard Objects | UI Objects | SuiteScript Functions
setCurrentLineItemMatrixValue(group, fldnam, column, value)
Use this API to set the value of a given matrix sublist field. Also note that it should be used on
matrix sublists only.
Important: Currently the Pricing sublist is the only matrix sublist type that supports
SuiteScript. For details on working with the Pricing sublist, see Pricing Sublist in the NetSuite
Help Center.
Parameters
•
group {string} [required] - The sublist internal ID. In the NetSuite Help Center, see
Pricing Sublist Internal IDs to determine the correct internal ID of your pricing list.
•
fldnam {string} [required] - The internal ID of the matrix field.
•
column {int} [required] - The column number for this field. Column numbers start at 1
(not 0).
•
value {string | int} [required] - The value the field is being set to.
Returns
•
void
Since
•
Version 2009.2
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
640
Example
var record = nlapiCreateRecord('inventoryitem');
record.setFieldValue('itemid', '124');
record.setFieldValue('department', 3);
record.setMatrixValue('price1', 'price', '2', 500);
record.selectLineItem('price', '1');
record.setCurrentLineItemMatrixValue('price', 'price', 1, '100');
record.setCurrentLineItemMatrixValue('price', 'price', 2, '90');
record.commitLineItem('price');
var id = nlapiSubmitRecord(record, true);
Standard Objects | UI Objects | SuiteScript Functions
setCurrentLineItemValue(group, name, value)
Use this method to set the value of a sublist line item field.
Parameters
•
group {string} [required] - The sublist internal ID (for example, use addressbook as the
ID for the Address sublist). In the NetSuite Help Center, see Scriptable Sublists for a list
of sublists that support SuiteScript, as well as all internal IDs associated with each
sublist.
•
name {string} [required] - The name of the field being set
•
value {string} [required] - The value the field is being set to. Note: Check box fields
take the values of T or F, not true or false.
Returns
•
void
Since
•
Version 2009.2
Example
This sample shows how to create a new Vendor Bill record and then add items to the Item
sublist and expenses to the Expenses sublist. Note that because you are adding new lines to
each sublist, you must call the selectNewLineItem(group) method. You then set all values for
the new lines using the setCurrentLineItemValue(group, name, value) method. When you are
finished adding values to each sublist, you must commit all sublist updates using the
commitLineItem(group) method.
var record = nlapiCreateRecord('vendorbill');
record.setFieldValue('entity', 196);
record.setFieldValue('department', 3);
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
641
record.selectNewLineItem('item');
record.setCurrentLineItemValue('item','item', 380);
record.setCurrentLineItemValue('item', 'location', 102);
record.setCurrentLineItemValue('item', 'amount', '2');
record.setCurrentLineItemValue('item', 'customer', 294);
record.setCurrentLineItemValue('item','isbillable', 'T');
record.commitLineItem('item');
record.selectNewLineItem('expense');
record.setCurrentLineItemValue('expense','category', 3);
record.setCurrentLineItemValue('expense', 'account', 11);
record.setCurrentLineItemValue('expense', 'amount', '10');
record.setCurrentLineItemValue('expense','customer', 294);
record.setCurrentLineItemValue('expense','isbillable', 'T');
record.commitLineItem('expense');
var id = nlapiSubmitRecord(record, true);
Standard Objects | UI Objects | SuiteScript Functions
setFieldText(name, text)
Sets the value of a select field using its corresponding display value
Parameters
•
name {string} [required] - The internal ID of the field being set
•
text {string} [required] - The display value corresponding to the value the field is being
set to
Returns
•
void
Since
•
Version 2009.1
Example
var record = nlapiLoadRecord('salesorder', 1955); // load the sales order
record.setFieldText('location', 'East Coast'); // set the field display value for Location to East Coast
var id = nlapiSubmitRecord(record, true); // submit the record
Standard Objects | UI Objects | SuiteScript Functions
setFieldTexts(name, text)
Sets the values for a multiselect field from their display values
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
642
Parameters
•
name {string} [required] - The internal ID of the field being set
•
texts {string[]} [required] - The display values corresponding to the values the field is
being set to
Returns
•
void
Since
•
Version 2009.1
Example
var values = new Array(); // create an array of customers who are currently in NetSuite
values[0] = 'Abe Lincoln'; // add the first customer
values[1] = 'Abe Simpson'; // add the second customer
var record = nlapiLoadRecord('salesorder', 447); // load the sales order
// set the field display values for the custom multiselect field
// called Customers Multiselect Field
record.setFieldTexts('custbody16', values);
// submit the record
var submit = nlapiSubmitRecord(record, true);
Standard Objects | UI Objects | SuiteScript Functions
setFieldValue(name, value)
Sets the value of a field
Parameters
•
name {string} [required] - The name of the field being set
•
value {string} [required] - The value the field is being set to
Returns
•
void
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
643
Standard Objects | UI Objects | SuiteScript Functions
setFieldValues(name, value)
Sets the value of a multi-select field
Parameters
•
name {string} [required] - The name of the field being set
•
value {string[]} [required]- String array containing field values
Returns
•
void
Standard Objects | UI Objects | SuiteScript Functions
setLineItemValue(group, name, linenum, value)
Sets the value of a sublist line item.
Tip: Normally custom transaction column fields that are not checked to show on a custom
form are not available to get/setLineItemValue APIs. However, if you set them to show, but
then set the label to empty, they will be available on the form but will not appear on the sublist.
Note this does not apply to fields that are marked as Hidden on the custom field definition.
These fields are always available on every form.
Parameters
•
group {string} [required] - The sublist internal ID (for example, use addressbook as the
ID for the Address sublist). In the NetSuite Help Center, see Scriptable Sublists for a list
of sublists that support SuiteScript, as well as all internal IDs associated with each
sublist.
•
name {string} [required] - The name of the field being set
•
linenum {int} [required] - The line number for this field. Note the first line in a sublist
is 1 (not 0).
•
value {string} [required] - The value the field is being set to. If a valid value is not
specified an error will be thrown.
Returns
•
void
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
644
Since
•
Version 2008.1
Example
The following example shows how to create a new record and then add a sublist to the record.
In this case a Partner sublist is being added to a newly created Sale Order.
/*Create a Sales Order record. Next, add a field to the record and then add an *item, which must be added
before a Sales Order can be saved.
*/
var record = nlapiCreateRecord('salesorder');
record.setFieldValue('entity', 87);
record.setLineItemValue('item','item', 1, 458);
record.setFieldValue('shippingcost',12);
/*Add a Partners sublist to the Sales Order. Note you must provide a valid value
*for the Partner ID. In this case, to obtain Partner IDs you can look in the UI
*under Lists > Relationships > Partners. Ensure that the Show Internal ID
*preference is enabled. IDs will appear in the ID column of the Partner list.
*/
record.setLineItemValue('partners','partner', 1,311);
record.setLineItemValue('partners','partnerrole', 1,1);
record.setLineItemValue('partners', 'isprimary',1, 'T' );
record.setLineItemValue('partners', 'contribution',1, 100 );
//Finally, submit the record to save it.
var id = nlapiSubmitRecord(record, true);
Standard Objects | UI Objects | SuiteScript Functions
setMatrixValue(group, fldnam, column, value)
This API is used to set a header field in a matrix sublist. Also note that this API should be used
on matrix sublists only.
Important: Currently the Pricing sublist is the only matrix sublist type that supports
SuiteScript. For details on working with the Pricing sublist, see Pricing Sublist in the NetSuite
Help Center.
In the case of the Pricing sublist, this API is used to set the quantity levels that appear in the
Qty fields. Note that you should use this API only if you have the Quanity Pricing feature
enabled in your account, as these header fields appear only if this feature is enabled.
Parameters
•
type {string} [required] - The sublist internal ID. In the NetSuite Help Center, see
Pricing Sublist Internal IDs to determine the correct internal ID of your pricing list.
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
645
•
fldnam {string} [required] - The name of the field being set.
•
column {int} [required] - The column number for this field. Column numbers start at 1
(not 0).
•
value {string} [required] - The value the field is being set to. Note: Check box fields
take the values of T or F, not true or false.
Returns
•
void
Since
•
Version 2009.2
Example
The following sample shows how to set pricing matrix values on a new Inventory Item record.
In this sample, setMatrixValue(...) is used to set the quantity levels in Qty columns 2, 3, 4, 5.
Note that in this account, the Multiple Currencies feature has been enabled and all pricing
matrix values are being set on the USA pricing tab (price1).
var record = nlapiCreateRecord('inventoryitem');
record.setFieldValue('itemid', '124');
record.setFieldValue('department', 3);
record.setMatrixValue('price1', 'price', '2', 500);
record.setMatrixValue('price1', 'price', '3', 600);
record.setMatrixValue('price1', 'price', '4', 700);
record.setMatrixValue('price1', 'price', '5', 800);
//Now set prices to all pricelevel and quantity level fields on the USA tab.
//Set Base prices in different columns.
record.selectLineItem('price1','1');
record.setCurrentLineItemMatrixValue('price1', 'price', 1, '100');
record.setCurrentLineItemMatrixValue('price1', 'price', 2, '200');
record.setCurrentLineItemMatrixValue('price1', 'price', 3, '300');
record.setCurrentLineItemMatrixValue('price1', 'price', 4, '400');
record.setCurrentLineItemMatrixValue('price1', 'price', 5, '500');
record.commitLineItem('price1');
Standard Objects | UI Objects | SuiteScript Functions
viewCurrentLineItemSubrecord(sublist, fldname)
Returns a nlobjSubrecord object. Use this API to view a subrecord from a sublist field on the
parent record. Calling this API analogous to doing a “get” on a subrecord, however, the
nlobjSubrecord object returned is in read-only mode. Therefore, an error is thrown if you
attempt to edit a subrecord returned by this API.
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
646
You can call this API when you want your script to read the nlobjSubrecord object of the
current sublist line you are on.
This API is currently used only in the context of the Advanced Bin / Numbered Inventory
feature. For information, see Using SuiteScript with Advanced Bin / Numbered Inventory
Management. Also see Working with Subrecords in SuiteScript for general information on
working with subrecords in NetSuite.
Parameters
•
sublist {string} [required] - The sublist internal ID on the parent record (for example,
use item as the ID for the Items sublist).
•
fldname {string} [required] - The internal ID of the “subrecord field” on the sublist of
the parent record (for example, inventorydetail as the ID for the Inventory Details
sublist field).
Returns
•
nlobjSubrecord
Since
•
Version 2011.2
Example
See Viewing a subrecord in the NetSuite Help Center.
Standard Objects | UI Objects | SuiteScript Functions
viewLineItemSubrecord(sublist, fldname, linenum)
Returns a nlobjSubrecord object. Use this API to view a subrecord from a sublist field on the
parent record. Calling this API analogous to doing a “get” on a subrecord, however, the
nlobjSubrecord object returned is in read-only mode. Therefore, an error is thrown if you
attempt to edit a subrecord returned by this function.
You can call this API when you want to read the value of a line you are not currently on. For
example, if you are editing line 2, you can call this API on line 1 to get the value of line 1.
This API is currently used only in the context of the Advanced Bin / Numbered Inventory
feature. For information, see Using SuiteScript with Advanced Bin / Numbered Inventory
Management. Also see Working with Subrecords in SuiteScript for general information on
working with subrecords in NetSuite.
Parameters
•
sublist {string} [required] - The sublist internal ID on the parent record (for example,
use item as the ID for the Items sublist).
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
647
•
fldname {string} [required] - The internal ID of the “subrecord field” on the sublist of
the parent record (for example, inventorydetail as the ID for the Inventory Details
sublist field).
•
linenum {int} [required] - The line number for the sublist field. Note the first line
number on a sublist is 1 (not 0).
Returns
•
nlobjSubrecord
Since
•
Version 2011.2
Standard Objects | UI Objects | SuiteScript Functions
viewSubrecord(fldname)
Returns a nlobjSubrecord object. Use this API to view a subrecord from a body field on the
parent record. Calling this API analogous to doing a “get” on a subrecord, however, the
nlobjSubrecord object returned is in read-only mode. Therefore, an error is thrown if you
attempt to edit a subrecord returned by this function.
This API is currently used only in the context of the Advanced Bin / Numbered Inventory
feature. For information, see Using SuiteScript with Advanced Bin / Numbered Inventory
Management. Also see Working with Subrecords in SuiteScript for general information on
working with subrecords in NetSuite.
Parameters
•
fldname {string} [required] - The internal ID of the “subrecord field” on the body of
the parent record (for example, inventorydetail as the ID for the Inventory Details body
field).
Returns
•
nlobjSubrecord
Since
•
Version 2011.2
Example
See Viewing a subrecord in the NetSuite Help Center.
Standard Objects | UI Objects | SuiteScript Functions
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
nlobjReportColumn
Object used to encapsulate a report column on a pivot report.
Methods
•
getFormula()
•
getParent()
•
isMeasure()
getFormula()
Get the formula for this column
Returns
•
string - Formula or null if it does not exist.
getParent()
Get the parent reference of this column.
Returns
•
The parent reference to the nlobjReportColumnHierarchy object.
isMeasure()
Returns the measure flag
Returns
•
boolean - True if the column is flagged as a measure.
Since
•
Version 2012.2
Standard Objects | UI Objects | SuiteScript Functions
nlobjReportColumnHierarchy
Object used to encapsulate the report column hierarchy.
Methods
•
getChildren()
SuiteScript Developer and Reference Guide
648
SuiteScript Objects
Standard Objects
•
649
getParent()
getChildren()
Get the children reference of this column hierarchy.
Returns
•
The child reference to the nlobjReportColumnHierarchy object.
Since
•
Version 2012.2
Standard Objects | UI Objects | SuiteScript Functions
getParent()
Get the parent reference of this column hierarchy.
Returns
•
Either the parent reference to the nlobjReportColumnHierarchy object or null.
Since
•
Version 2012.2
Standard Objects | UI Objects | SuiteScript Functions
nlobjReportDefinition
The primary object that contains the definition of the report. For an example that shows how to
use several of the nlobjReportDefinition object methods to programmatically render a pivot
table report in a browser, see Building a Pivot Report Using SuiteScript.
Methods
•
addColumn(alias, isMeasure, label, parent, format, formula)
•
addColumnHierarchy(alias, label, parent, format)
•
addRowHierarchy(alias, label, format)
•
addSearchDatasource(searchType, id, filters, columns, map)
•
executeReport(form)
•
setTitle(title)
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
650
addColumn(alias, isMeasure, label, parent, format, formula)
Add a column to the report definition.
Parameters
•
alias {string} [required] - The column alias.
•
isMeasure {boolean} [required] - A value of true means that the column is flagged as a
measure.
•
label {string} [required] - The column label that will be displayed on the report.
•
parent {nlobjReportColumnHierarchy} [optional] - The reference to the parent
column in the hierarchy. If null, then this column will not be associated with a parent
column.
•
format {string} [required] - The data type that this column represents.
•
formula {string} [optional] - A string which describes a mathematical formula in the
format of “F(x,y,z) = mathematical function”, where x,y,z are previously defined aliases
from addRowHierarchy, addColumnHierarchy, or addColumn calls.
Returns
•
The reference to the nlobjReportColumn object.
Since
•
Version 2012.2
Example
See the code sample in Building a Pivot Report Using SuiteScript.
Standard Objects | UI Objects | SuiteScript Functions
addColumnHierarchy(alias, label, parent, format)
Add a column hierarchy to the report definition.
Parameters
•
alias {string} [required] - The column alias.
•
label {string} [required] - The column label that will be displayed on the report.
•
parent {nlobjReportColumnHierarchy} [optional] - The reference of the parent
column in the hierarchy. If null, then this column will be the root (top level) column.
•
format {string} [required] - The data type that this column represents.
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
651
Returns
•
The reference to the nlobjReportColumnHierarchy object.
Since
•
Version 2012.2
Example
See the code sample in Building a Pivot Report Using SuiteScript.
Standard Objects | UI Objects | SuiteScript Functions
addRowHierarchy(alias, label, format)
Add a row hierarchy to the report definition.
Parameters
•
alias {string} [required] - The row alias.
•
label {string} [required] - The row label that will be displayed on the report.
•
format {string} [required] - The data type that this row represents.
Returns
•
The reference to the nlobjReportRowHierarchy object.
Since
•
Version 2012.2
Example
See the code sample in Building a Pivot Report Using SuiteScript.
Standard Objects | UI Objects | SuiteScript Functions
addSearchDatasource(searchType, id, filters, columns, map)
Attaches a search as a data source to the report definition.
Parameters
•
searchType {string} [required] - The type of records to search.
•
id {string} [optional] - The internal id (as a string) if you are using a saved search as a
data source.
•
filters {nlobjSearchFilter[]} [required] - The array of search filters.
Note: Search filter expression as filters parameter is currently not supported.
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
•
columns {nlobjSearchColumn[]} [required] - The array of search columns.
•
map {string} [required] - The mapping of rows/columns of the search to the report.
652
Since
•
Version 2012.2
Example
This snippet of code shows how a data source is set up. Observe how the columns are mapped.
var reportDefinition = nlapiCreateReportDefinition();
var columns = new Array();
var filters = new Array();
columns[0] = new nlobjSearchColumn('internalID', null, 'group');
columns[1] = new nlobjSearchColumn('entity', null, 'group');
filters[0] = new nlobjSearchFilter('status', null, 'anyof ', 'inProgress');
reportDefinition.addSearchDataSource('opportunity', null, filters, columns, {'internalID':columns[0],
'entity':columns[1]});
Standard Objects | UI Objects | SuiteScript Functions
executeReport(form)
Creates the form for rendering from the report definition.
Parameters
•
form {nlobjReportForm} [optional] - The form object created with
nlapiCreateReportForm.
If not specified the call waits until the execution is finished (synchronous) and an
nlobjPivotTable will be available from the handle. If the parameter is set, the call
returns immediately and the returned value references the nlobjReportForm - a pivot
table handle will not be available in this case.
Note: Only one synchronous pivot table execution is allowed at a time. If a second
synchronous execution is called, it will invalidate the first pivot table.
Returns
•
nlobjPivotTableHandle - The identifier of the pivot table handle, or nlobjReportForm.
Since
•
Version 2012.2
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
653
Example 1
This example shows how to create a pivot table for simple rendering as a report in a browser.
//Create a form to put the report on
var myForm = nlapiCreateReportForm('Pivot Report Sales Orders');
//Populate form here
...
//Build the form from the report definition
var myReportForm = reportDefinition.executeReport(myForm);
//Write the form back to the browser
response.writePage(myReportForm);
Example 2
This example shows how to create a pivot table for further processing with SuiteScript. The pivot table is not
rendered.
//Create a form to put the report on
var myform = nlapiCreateReportForm('Pivot Report Sales Orders');
//Populate form here
...
//Build the form from the report definition, get the pivot table handle
var myPivotTableHandle = reportDefinition.executeReport();
//Get the pivot table object
var myPivotTable = myPivotTableHandle.getPivotTable();
Standard Objects | UI Objects | SuiteScript Functions
setTitle(title)
Sets the title of the report definition.
Parameters
•
title {string} [optional] - The name of the report definition.
Since
•
Version 2012.2
Standard Objects | UI Objects | SuiteScript Functions
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
654
Building a Pivot Report Using SuiteScript
This example shows how to create a report showing the opportunities for each customer, and
opportunity status. Each opportunity status is broken down to show the projected total and the
probability of each opportunity.
Use the method executeReport() passing along an optional form parameter rather than void so
that the form definition is built onto a standard nlobjReportForm object that can be rendered
on the browser using the response.writePage method.
function runOpportunitiesPivot(request, response)
{
//Instantiate a report definition to work with
var reportDefinition = nlapiCreateReportDefinition();
//Define the rows/column hierarchy and the actual column data
var customer = reportDefinition.addRowHierarchy('entity', 'Customer', 'TEXT');
var salesrep= reportDefinition.addColumn('salesrep', false, 'Sales Rep', null, 'TEXT', null);
var entstat = reportDefinition.addColumnHierarchy('entitystatus', 'Opportunity Status', null, 'TEXT');
var total = reportDefinition.addColumn('projectedtotal', true, 'Projected Total',
entstat, 'CURRENCY', null);
var prob = reportDefinition.addColumn('probability', false, 'Probability %', entstat, 'PERCENTAGE', null);
//Create the search to feed the report
var columns = new Array();
columns[0] = new nlobjSearchColumn('internalID', null, 'group');
columns[1] = new nlobjSearchColumn('entity', null, 'group');
columns[2] = new nlobjSearchColumn('salesrep', null, 'group');
columns[3] = new nlobjSearchColumn('expectedclosedate', null, 'group');
columns[4] = new nlobjSearchColumn('entitystatus', null, 'group');
columns[5] = new nlobjSearchColumn('projectedtotal', null, 'sum');
columns[6] = new nlobjSearchColumn('probability', null, 'group');
//Add search to the report and map the search columns to the reports columns
var filters = new Array();
filters[0] = new nlobjSearchFilter('projectedtotal', null, 'greaterthan', 2000);
reportDefinition.addSearchDataSource('opportunity', null, filters, columns,
{'internalID':columns[0], 'entity':columns[1], 'salesrep':columns[2], 'expectedclosedate':columns[3],
'entitystatus':columns[4], 'projectedtotal':columns[5], 'probability':columns[6]});
//Create a form to build the report on
var form = nlapiCreateReportForm('Pivot Report Suitelet: Opportunities');
//Build the form from the report definition
var pvtTable = reportDefinition.executeReport(form);
//Write the form to the browser
response.writePage(form);
}
The following figure shows how the pivot report example is rendered in the NetSuite UI.
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
655
Moreover, the UI equivalent of defining the row/column hierarchy and the actual column data
of a pivot report is as follows:
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
656
For more information about creating a pivot report through the UI, see Creating a Pivot
Report.
In SuiteScript, this looks like:
var customer = reportDefinition.addRowHierarchy('entity', 'Customer', 'TEXT');
var salesrep= reportDefinition.addColumn('salesrep', false, 'Sales Rep', null, 'TEXT', null);
var entstat = reportDefinition.addColumnHierarchy('entitystatus', 'Opportunity Status', null, 'TEXT');
var total = reportDefinition.addColumn('projectedtotal', true, 'Projected Total',
entstat, 'CURRENCY', null);
var prob = reportDefinition.addColumn('probability', false, 'Probability %', entstat, 'PERCENTAGE', null);
nlobjReportForm
Object used to encapsulate the report form and render the report in HTML.
Since
•
Version 2012.2
Standard Objects | UI Objects | SuiteScript Functions
nlobjReportRowHierarchy
Object used to encapsulate the report row hierarchy.
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
657
Methods
•
getChild()
•
getParent()
getChild()
Get the child reference of this row hierarchy.
Returns
•
The child reference to the nlobjReportRowHierarchy object.
Since
•
Version 2012.2
Standard Objects | UI Objects | SuiteScript Functions
getParent()
Get the parent reference of this row hierarchy.
Returns
•
Either the parent reference to the nlobjReportRowHierarchy object or null.
Since
•
Version 2012.2
Standard Objects | UI Objects | SuiteScript Functions
nlobjRequest
Primary object used to encapsulate an HTTP GET or POST request. When creating Suitelets
you will pass request and response arguments to your user-defined function (see example).
With the request object instantiated, you can then call any nlobjRequest method.
Example
function demoSimpleForm(request, response)
{
//call an nlobjRequest method
if ( request.getMethod() == 'GET' )
{
var form = nlapiCreateForm('Simple Form');
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
//remainder of code...
response.writePage(form);
{
}
nlobjRequest Methods
•
getAllHeaders()
•
getAllParameters()
•
getBody()
•
getFile(id)
•
getHeader(name)
•
getLineItemCount(group)
•
getLineItemValue(group, name, line)
•
getMethod()
•
getParameter(name)
•
getParameterValues(name)
•
getURL()
getAllHeaders()
Returns an Object containing all the request headers and their values.
Returns
•
String[] of header names
Since
•
Version 2008.2
Standard Objects | UI Objects | SuiteScript Functions
getAllParameters()
Returns an Object containing all the request parameters and their values
Returns
•
String[] of parameter field names
SuiteScript Developer and Reference Guide
658
SuiteScript Objects
Standard Objects
659
Since
•
Version 2008.2
Example
The following example shows how to set or read multiple parameters from a request object by
iterating through the properties of the object
var params = request.getAllParameters()
for ( param in params )
{
nlapiLogExecution('DEBUG', 'parameter: '+ param)
nlapiLogExecution('DEBUG', 'value: '+params[param])
}
Standard Objects | UI Objects | SuiteScript Functions
getBody()
Returns the body of the POST request
Returns
•
The string value of the request body
Since
•
Version 2008.1
Standard Objects | UI Objects | SuiteScript Functions
getFile(id)
Returns a file added through the nlobjForm.addField(name, type, label, sourceOrRadio, tab)
method. When adding a file field type, you will set the type parameter of 'file'.
Returns
•
nlobjFile
Since
•
Version 2010.1
Example
See Uploading Files to the File Cabinet Using SuiteScript.
Standard Objects | UI Objects | SuiteScript Functions
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
660
getHeader(name)
Returns the value of a header in the request
Parameters
•
name {string} [required]- The name of the header
Returns
•
The request header as a string
Since
•
Version 2008.2
Standard Objects | UI Objects | SuiteScript Functions
getLineItemCount(group)
Returns the number of lines in a sublist
Important: The first line number on a sublist is 1 (not 0).
Parameters
•
group {string} [required] - The sublist internal ID (for example, use addressbook as the
ID for the Address sublist). In the NetSuite Help Center, see Scriptable Sublists for a list
of sublists that support SuiteScript, as well as all internal IDs associated with each
sublist.
Returns
•
The integer value of the number of line items in a sublist
Since
•
Version 2008.2
Standard Objects | UI Objects | SuiteScript Functions
getLineItemValue(group, name, line)
Returns the value of a sublist line item.
Tip: Normally custom transaction column fields that are not checked to show on a custom
form are not available to get/setLineItemValue APIs. However, if you set them to show, but
then set the label to empty, they will be available on the form but will not appear on the sublist.
Note this does not apply to fields that are marked as Hidden on the custom field definition.
These fields are always available on every form.
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
661
Parameters
•
group {string} [required] - The sublist internal ID (for example, use addressbook as the
ID for the Address sublist). In the NetSuite Help Center, see Scriptable Sublists for a list
of sublists that support SuiteScript, as well as all internal IDs associated with each
sublist.
•
name {string} [required] - The name of the field whose value is returned
•
line {int} [required] - The line number for this field. Note the first line number on a
sublist is 1 (not 0).
Returns
•
The string value of the line item
Since
•
Version 2008.2
Standard Objects | UI Objects | SuiteScript Functions
getMethod()
Returns the METHOD of the request.
Returns
•
The string value of the request type. Request types include GET or POST.
Since
•
Version 2008.1
Example
function demoSimpleForm(request, response)
{
if ( request.getMethod() == 'GET' )
{
var form = nlapiCreateForm('Simple Form');
//remainder of code...
response.writePage(form);
{
}
Standard Objects | UI Objects | SuiteScript Functions
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
662
getParameter(name)
Returns the value of the request parameter
Parameters
•
name {string} [required]- The name of the request parameter whose value is returned
Returns
•
The string value of the request parameter
Since
•
Version 2008.2
Standard Objects | UI Objects | SuiteScript Functions
getParameterValues(name)
Returns the values of a request parameter as an Array
Parameters
•
name {string} [required] - The name of the request parameter whose value is returned
Returns
•
String[] of parameter values
Since
•
Version 2008.2
Standard Objects | UI Objects | SuiteScript Functions
getURL()
Returns the full URL of the request
Returns
•
The string value of the request URL
Since
•
Version 2008.1
Standard Objects | UI Objects | SuiteScript Functions
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
663
nlobjResponse
Primary object used for scripting web responses in Suitelets. Note that the
nlapiRequestURL(url, postdata, headers, callback, httpMethod) function returns a reference to
this object.
When creating Suitelets you will pass request and response arguments to your user-defined
function (see example). With the response object instantiated, you can then call any
nlobjResponse method.
See Supported File Types in the NetSuite Help Center for a list of all content/media types that
can be returned through the nlobjResponse object.
Example
function demoSimpleForm(request, response)
{
if ( request.getMethod() == 'GET' )
{
var form = nlapiCreateForm('Simple Form');
//remainder of code...
//call the nlobjResponse object writePage method
response.writePage(form);
{
}
nlobjResponse Methods
•
addHeader(name, value)
•
getAllHeaders()
•
getBody()
•
getCode()
•
getError()
•
getHeader(name)
•
getHeaders(name)
•
setContentType(type, name, disposition)
•
setHeader(name, value)
•
sendRedirect(type, identifier, id, editmode, parameters)
•
write(output)
•
writeLine(output)
•
writePage(pageobject)
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
664
addHeader(name, value)
Adds a header to the response. If this header has already been set, this will add a new header to
the response. Note that all user-defined headers must be prefixed with Custom-Header
otherwise an SSS_INVALID_ARG error will be thrown ()
Parameters
•
name {string} [required] - The name of the header
•
value {string} [required] - The value used to set header
Returns
•
void
Since
•
Version 2008.2
Standard Objects | UI Objects | SuiteScript Functions
getAllHeaders()
Returns an Array containing all the headers returned in the response. Only available in the
return value of a call to nlapiRequestURL(url, postdata, headers, callback, httpMethod).
Returns
•
String[] of headers
Since
•
Version 2008.2
Standard Objects | UI Objects | SuiteScript Functions
getBody()
Returns the body returned by the server. Only available in the return value of a call to
nlapiRequestURL(url, postdata, headers, callback, httpMethod).
Returns
•
The string value of the body
Standard Objects | UI Objects | SuiteScript Functions
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
665
getCode()
Returns the response code returned by the server. Only available in the return value of a call to
nlapiRequestURL(url, postdata, headers, callback, httpMethod).
Returns
•
The string value of the response code
Standard Objects | UI Objects | SuiteScript Functions
getError()
Returns the nlobjError thrown during request. Only available in the return value of call to
nlapiRequestURL in Client SuiteScript.
Returns
•
nlobjError
Standard Objects | UI Objects | SuiteScript Functions
getHeader(name)
Returns the value for a header returned in the response. Only available in the return value of a
call to nlapiRequestURL(url, postdata, headers, callback, httpMethod).
Parameters
•
name {string} [required] - The header name
Returns
•
The string value of the header
Since
•
Version 2008.2
Standard Objects | UI Objects | SuiteScript Functions
getHeaders(name)
Returns an Array containing all the values for a header returned in the response. This is only
available in the return value of a call to nlapiRequestURL.
Parameters
•
name {string} - The header name
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
666
Returns
•
String[] of header values
Since
•
Version 2008.2
Standard Objects | UI Objects | SuiteScript Functions
setContentType(type, name, disposition)
Sets the content type for the custom responses (and an optional file name for binary output).
This API is available in Suitelet scripts only.
Parameters
•
type {string} [required]- The content/file type. For a list of supported file types, see
Supported File Types in the NetSuite Help Center.
•
name {string} [optional]- Set the name of the file being downloaded (for example
'foobar.pdf ')
•
disposition {string} [optional] - Content disposition to use for file downloads. Available
values are inline or attachment. If a value is not specified, the parameter will default to
attachment. What this means is that instead of a new browser (or Acrobat) launching
and rendering the content, you will instead be asked if you want to download and Save
the file.
Returns
•
void
Since
•
Version 2008.2
Example
See Example 2 for nlapiXMLToPDF. This sample shows how to set a file content type to PDF
and then, by specifying inline as the disposition type, having the PDF open in Acrobat.
Standard Objects | UI Objects | SuiteScript Functions
setHeader(name, value)
Sets the value of a response header. Note that all user-defined headers must be prefixed with
Custom-Header otherwise an SSS_INVALID_ARG or SSS_INVALID_HEADER error will be
thrown.
Important: This method is available only in Suitelets.
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
667
Parameters
•
name {string} [required] - The name of the header
•
value {string} [required] - The value used to set header
Returns
•
void
Since
•
Version 2008.2
Example
function demoHTML(request, response)
{
var html = '<html><body><h1>Hello World</h1></body></html>';
response.write( html );
//set a custom header
response.setHeader('Custom-Header-Demo', 'Demo');
}
Standard Objects | UI Objects | SuiteScript Functions
sendRedirect(type, identifier, id, editmode, parameters)
Sets the redirect URL by resolving to a NetSuite resource. Note that all parameters must be
prefixed with custparam otherwise an SSS_INVALID_ARG error will be thrown.
Also note that all URLs must be internal unless the Suitelet is being executed in an “Available
without Login” context. If this is the case, then within the “Available without Login” (externally
available) Suitelet, you can set the type parameter to EXTERNAL and the identifier parameter
to the external URL.
Parameters
•
type {string} [required] - The base type for this resource
• RECORD - Record Type
• TASKLINK - Task Link
• SUITELET - Suitelet
• EXTERNAL - Custom URL (external) and only available for external Suitelets (i.e.
available without login)
•
identifier {string} [required] - The primary id for this resource (record type ID for
RECORD, scriptId for SUITELET, taskId for tasklink, url for EXTERNAL)
•
id {string} [optional] - The secondary id for this resource (record type ID for
RECORD, deploymentId for SUITELET)
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
668
•
editmode {boolean} [optional] - For RECORD calls, this determines whether to return
a URL for the record in edit mode or view mode. If set to true, returns the URL to an
existing record in edit mode, otherwise the record is returned in view mode.
Important: The values for this parameter can be true or false, not T or F.
•
parameters {hashtable} [optional] - An associative array of additional URL parameters
as name/value pairs
Returns
•
void
Since
•
Version 2008.2
Standard Objects | UI Objects | SuiteScript Functions
write(output)
Write information (text/xml/html) to the response
Parameters
•
output {string | document} [required] - String or Document being written
Returns
•
void
Example
function demoHTML(request, response)
{
var html = '<html><body><h1>Hello World</h1></body></html>';
response.write( html );
response.setHeader('Custom-Header-Demo', 'Demo');
}
Since
•
Version 2008.2
Standard Objects | UI Objects | SuiteScript Functions
writeLine(output)
Write line information (text/xml/html) to the response
Parameters
•
output {string} [required] - String being written
SuiteScript Developer and Reference Guide
SuiteScript Objects
Standard Objects
669
Returns
•
void
Since
•
Version 2008.2
Standard Objects | UI Objects | SuiteScript Functions
writePage(pageobject)
Generates a page using a page element object (nlobjForm or nlobjList)
Parameters
•
pageobject {nlobjForm | nlobjList} [required] - Standalone page object: nlobjForm or
nlobjList
Returns
•
void
Since
•
Version 2008.2
Example
function demoSimpleForm(request, response)
{
if ( request.getMethod() == 'GET' ) {
var form = nlapiCreateForm('Simple Form');
//remainder