JavaScript

From AgileApps Support Wiki
(Redirected from Category:JavaScript)

This page provides instruction on the use of JavaScript in the platform.

About JavaScript

JavaScript is an object-oriented language that allows for functional programming. It is the language that drives much of the world wide web.

Learn more:

Using JavaScript in the Platform

JavaScript can be used in a variety of ways:

  • Field Scripting - Add JavaScript code to take actions on a Field (On Change or On Focus)
  • Form Scripting - Add JavaScript code to a Form (On Load or On Save)
  • Post Selection JavaScript - Perform validations on Lookup Fields using JavaScript
  • Action buttons - Add action buttons when displaying a record
  • In a JSP/HTML Page - Make things happen on the client side to reduce the load on the server.
  • Toaster Message - Add custom messages in toaster using JavaScript.
Considerations
  • When you make a change to JavaScript code, the old code is still in the browser cache. To get the new code, force-reload the page.
  • Alternatively, you can turn off browser caching while testing and re-writing code. (Some browsers let you disable caching automatically when the JavaScript console is active--in other words, when you're in test-and-debug mode.

Learn more:

Thumbsup.gif

Best Practice:
Syntax errors and other errors prevent JavaScript code from executing, and JavaScript errors aren't displayed in the platform Debug Log. To make sure you find out when an error occurs, enclose code in a try/catch block that includes an alert():

var x = 1;
var y = 2;

try {
   // Add x & y here
   ...
} catch (e) { 
   alert(e);
};

Reference Information

JavaScript Functions

Accessing Form Fields

JavaScript is a powerful language that can do many things. But one of it's most common uses is to dynamically modify the behavior of Forms, using Form Scripting and Field Scripting.

Notepad.png

Note: To reference Form fields in JavaScript for the new AgileApps UI, see JavaScript Field Type Reference for New AgileApps User Interface.

Referencing the Current Form

In the HTML document object model (DOM), the current form is named _sdForm.
This line of code gets a reference to it and puts it in the form variable:

var form = _sdForm;

Accessing Fields in the Current Form

To find the name of a field in the platform:

  1. Go to GearIcon.png > Customization > Objects > {object} > Fields
  2. Find the label of the field you're interested in
  3. Get its name from the Field Name column
    That name can then be used in the JavaScript code.

All fields can be accessed using the platform's JavaScript functions, as described in the Field Types section below. The most commonly accessed field types (TextField, TextArea, Date, DateTime, Time, and URL) can also be accessed using _sdForm[0]. For example, this line of code gets a reference to the first_name field, and puts it in the variable fName_field:

var fName_field = _sdForm[0].first_name;

Fields have two properties that you can access in JavaScript:

  • name: the name of the field
  • value: the value of the field

So this line retrieves the value of the field:

var fName = fName_field.value;

As does this longer version:

var fName = _sdForm[0].first_name.value;

Other fields can be accessed using the platform's JavaScript functions.
For a complete list, see the Field Types section below.

Updating Fields in the Current Form

The method used to update a field depends on the field type. All of the methods have the general form:

set...Value(_sdForm, field, value);

Below are some examples of common methods. (The section that follows contains a complete list.)

setTextFieldValue(_sdForm, "first_name", "Adam");

setPickListValue(_sdForm, "first_name", "Adam");

setMultiPickListValue(_sdForm, "first_name", ["new","closed"]); 
    // value is an array of strings

setRadioButtonValue(_sdForm, "first_name", "Adam");

setCheckboxState(_sdForm, "first_name", true);  // checked
setCheckboxState(_sdForm, "first_name", false); // unchecked

setLookupValue(_sdForm, "project_number", "123456", "My Project");
    // where 123456 is the record ID of the target record 
    // "My Project" is the value of the record locator field(s) for that record

Field Type Reference

Notepad.png

Note: To view the field type reference in the new AgileApps user interface, see JavaScript Field Type Reference for New AgileApps User Interface.

The following table shows how to access and update the different field types, where:

  • _sdForm is the variable that references the current form
  • field is a string containing the name of the field
    (as with all strings, literal values must be in quotes)
  • value is a value you specify (generally a string)
  • value is language keyword, typed exactly as shown--as in this line,
    for example, which gets the value from a field called email_address:
_sdForm.email_address.value

Notepad.png

Note:
Form data is in User Format. Data entered into the Form must be in that format, as well. Data going to and from the platform, on the other hand, must be in Database Format.

Learn more: Localization#JavaScript Programming

Notepad.png

Note: JavaScript functions mentioned in the table does not support Web Forms.

Type Getter Setter
Auto Number n/a n/a
Checkbox

getCheckBoxState(_sdForm, field)
Returns: true or false

setCheckboxState(_sdForm, field, state)
state: true or false

Example:
setCheckboxState(_sdForm, "item_approved", true);

Currency

getTextFieldValue(_sdForm, field)
Returns: String containing value

setTextFieldValue(_sdForm, field, value)
value: String containing new value

Date

_sdForm[0].fieldname.value
-or-
getTextFieldValue(_sdForm, field)
Returns: String containing value

setTextFieldValue(_sdForm, field, value)
value: String containing new value

Date time

_sdForm[0].fieldname.value
-or-
getTextFieldValue(_sdForm, field)
Returns: String containing value

setTextFieldValue(_sdForm, field, value)
value: String containing new value

Dependent Picklist

getPickListSelectedValue(_sdForm, field)
Returns: selected String containing value

setPickListValue(_sdForm, field, value)
value: String containing new value

Email Address

getTextFieldValue(_sdForm, field)
Returns: String containing value

setTextFieldValue(_sdForm, field, value)
value: String containing new value

External Lookup n/a n/a
File Field n/a n/a
Formula n/a n/a
Geolocation

getTextFieldValue(_sdForm, field)
Returns: A string containing a latitude and longitude,
    separated by a comma and a space.
Ex: 37.403930662906106, -121.97971165820213

setTextFieldValue(_sdForm, field, value)
value: A string containing the new geolocation value

Global Picklist

getPickListSelectedValue(_sdForm, field)
Returns: selected String containing value

setPickListValue(_sdForm, field, value)
value: String containing new value

Image Field n/a n/a
Lookup

getLookupFieldValue(_sdForm, field)
Returns: String containing record ID

getLookupFieldText(_sdForm, field)
Returns: String containing the displayed text

setLookupValue(_sdForm, field, value, text)
value: String containing record ID
text: String containing the text to display

Multiple Checkboxes

getMultiCheckBoxValue(_sdForm, field)
Returns: An array of values, one for each checked box

getMultiCheckBoxValue(_sdForm, field, index)
index: 0 for the first checkbox,
      1 for the second, and so on.
Returns: The value of the box if selected, else an empty string

setMultiCheckBoxValue(form, field, [value1, ...])
Argument: Array of values to set

Example:
setMultiCheckBoxValue(_sdForm, field, ["A", "B"])
(Checkboxes for all other values are turned off)

Multi Object Lookup n/a n/a
Multi Select Picklist

getMultiPickListSelectedValue(_sdForm, field)
Returns: Array of strings, with selected values
Example: ["A", "C"]

setMultiPickListValue(_sdForm, field, [value1, ...])
Argument: Array of values to select

Example:
setMultiPickListValue(_sdForm, field, ["A", "B"] )

Number

_sdForm[0].fieldname.value
-or-
getTextFieldValue(_sdForm, field)
Returns: String containing value

setTextFieldValue(_sdForm, field, value)
value: String containing new value, or a number

Number with decimals

sdForm[0].fieldname.value
-or-
getTextFieldValue(_sdForm, field)
Returns: String containing value

setTextFieldValue(_sdForm, field, value)
value: String containing new value, or a float

Percentage

sdForm[0].fieldname.value
-or-
getTextFieldValue(_sdForm, field)
Returns: String containing value

setTextFieldValue(_sdForm, field, value)
value: String containing new value

Phone/Fax

sdForm[0].fieldname.value
-or-
getTextFieldValue(_sdForm, field)
Returns: String containing value

setTextFieldValue(_sdForm, field, value)
value: String containing new value

Picklist

getPickListSelectedValue(_sdForm, field)
Returns: selected String containing value

setPickListValue(_sdForm, field, value)
value: String containing new value

Example:
setPickListValue(_sdForm, "status", "Closed");

Radio Buttons

getRadioButtonValue(_sdForm, field)
Returns: String containing selected value

setRadioButtonValue(_sdForm, field, value)
value: String containing new value to select

Example:
setRadioButtonValue(_sdForm, "color", "Black");

Rich Text Area n/a n/a
Rollup Summary Field n/a n/a
TextArea

_sdForm[0].fieldname.value
-or-
getTextFieldValue(_sdForm, field)
Returns: String containing value

setTextFieldValue(_sdForm, field, value)
value: String containing new value

TextField

_sdForm[0].fieldname.value
-or-
getTextFieldValue(_sdForm, field)
Returns: String containing value

setTextFieldValue(_sdForm, field, value)
value: String containing new value

Example:
setTextFieldValue(_sdForm, "first_name", "Adam");

Time

_sdForm[0].fieldname.value
-or-
getTextFieldValue(_sdForm, field)
Returns: String containing value

setTextFieldValue(_sdForm, field, value)
value: String containing new value

URL

_sdForm[0].fieldname.value
-or-
getTextFieldValue(_sdForm, field)
Returns: String containing value

setTextFieldValue(_sdForm, field, value)
value: String containing new value


Accessing User Information

This function returns information about the logged-in user in a json object.

getUserDetails()

Values availble in the json object are:

  • id - user id
  • first_name - user's first name.
  • last_name - user's last name.
  • language - user's language code. (ex: en)
  • access_profile_name - user's access profile name.
  • time_zone_name - user's time zone name. (ex:America/Indianapolis)
  • time_zone_description - localized time zone description.
    ex: (GMT-05:00) Eastern Standard Time (America/Indianapolis)
  • date_format - user's date format.
  • time_format - user's time format.
  • locale - user's locale code.
  • primary_team_name - user's primary team.
  • current_role_name - user's current role.
    Can be empty if the user has a profile that allows global access, but does not play any specific role in the application.
  • roles - list of the user's roles in the current application, with current role first.
  • teams - list of teams the user belongs to, with the primary team name first.
  • userCustomFields - an object containing values for each custom field defined on the User object, where the access key is the field name
Example

This script prefills fields in current form with data for the logged-in user, where each user record has a custom field called customer_discount:

var userDetails = getUserDetails(); 
setTextFieldValue(_sdForm, "column_id",  userDetails.id); 
setTextFieldValue(_sdForm, "first_name", userDetails.first_name); 
setTextFieldValue(_sdForm, "last_name",  userDetails.last_name); 
setTextFieldValue(_sdForm, "language",   userDetails.language); 
setTextFieldValue(_sdForm, "time_zone_name", userDetails.time_zone_name); 
setTextFieldValue(_sdForm, "time_zone_description", userDetails.time_zone_description); 
setTextFieldValue(_sdForm, "roles",      userDetails.roles) ; 
setTextFieldValue(_sdForm, "discount",   userDetails.userCustomFields.customer_discount);

Hiding Action Items and Assignment Buttons

Notepad.png

Note: To apply these functions with the new AgileApps UI, see the section Considerations for Existing Custom Script Methods in JavaScript Field Type Reference for New AgileApps User Interface.

These functions can be used to hide the actions-menu-items and record-assignment buttons, by calling them from the On Load Script section of a Form Script.

hideActionsMenuItems

Hide one or more items in the ACTIONS menu:

hideActionsMenuItems(['value-1', 'value-2', ...]);

where the parameter is an array of strings that contains the menu-item values (found by inspecting the value attribute of elements in the UI).

Example
hideActionsMenuItems(['assignOwnerShipButton','claimOwnerShipButton']);

The above example hides "assign to user" and "claim" options from actions menu.

hideClaimAndAssignButtons

Hide the Claim-record and Assign-record buttons.

hideClaimAndAssignButtons(['id-1', 'id-2', ...]);

where the parameter is an array of strings which contains ID-attributes from the respective buttons.

Example
hideClaimAndAssignButtons(['assignOwnerShipButton','assignTeamOwnerShipButton','claimOwnerShipButton']);

The above example hides "assign to user", "assign to team" and "claim" buttons from owner pop-up.

Localization

These functions are used to format and parse data.
Learn more: Localization#JavaScript Programming

L10n.formatCurrency(value, precision)
  • Format a value-string specified in Database Format with no currency character and no grouping indicators (commas), and with a decimal point for fractional amounts.
  • Return a String with the value formatted using the company's locale setting for currencies, with the number of decimal places specified for the precision. If the conversion fails, return the original string.
L10n.formatDate(value)
  • Format a date value.
  • Return a String with the date formatted using the user's date format.
Note:
As best practice, do not hardcode a date string, as that value will fail for a user in a different locale. Instead, create an instance of a JavaScript Date object and pass that value as the argument to the function.
L10n.formatDateTime(value)
  • Format a date/time value.
  • Return a String with the date formatted using the user's date format, and time formatted for the user's locale.
Note:
As best practice, do not hardcode a date or time string, as that value will fail for a user in a different locale. Instead, create an instance of a JavaScript Date object and pass that value as the argument to the function.
L10n.formatNumber(value, precision)
  • Format a value-string specified in Database Format with no grouping indicators (commas), with a decimal point for fractional amounts.
  • Return a String with the value formatted using the user's locale, with the number of decimal places specified for the precision. If the conversion fails, return the original string.
L10n.formatPercent(value, precision)
  • Convert a value-string specified in Database Format with no percent sign, no grouping indicators (commas), and with a decimal point for fractional amounts.
  • Return a String with the value formatted using the user's locale, with the number of decimal places specified for the precision. If the conversion fails, return the original string.
L10n.formatTime(value)
  • Format a date/time value.
  • Return a String with the time formatted for the user's locale
Note:
As best practice, do not hardcode a date or time string, as that value will fail for a user in a different locale. Instead, create an instance of a JavaScript Date object and pass that value as the argument to the function.
L10n.parseCurrency(value)
  • Parse a currency value-string in the format specified by the company's locale setting for currencies.
  • Return a String in Database Format format. If parsing fails, return the original string.
L10n.parseDate(value)
  • Parse a date-string in the format specified by the user's settings.
  • Return a JavaScript Date object. If parsing fails, returns null.
L10n.parseDateTime(value)
  • Parse a date/time string, where the date format is specified by the user's settings and the time format is determined by the user's locale.
  • Return a JavaScript Date object. If parsing fails, returns null.
L10n.parseNumber(value)
  • Parse a numeric value-string (with or without a fractional amount) in the format specified by the user's locale.
  • Return a String in Database Format format. If parsing fails, return the original string.
L10n.parsePercent(value)
  • Parse a percentage-string in the format specified by the user's locale.
  • Return a String in Database Format format. If parsing fails, return the original string.
L10n.parseTime(value)
  • Parse a time-string in the format specified by the user's locale setting.
  • Return a JavaScript Date object. If parsing fails, returns null.
L10n.validateCurrency(value)
  • Verify that the currency value-string is in the format specified by the company's locale setting for currencies.
  • Return true if the data is in the expected format, otherwise false.
L10n.validateDate(value)
  • Verify that the date string is in the format specified by the user's settings.
  • Return true if the data is in the expected format, otherwise false.
L10n.validateDateTime(value)
  • Verify the date/time string, where the date is in the format specified by the user's settings and the time format is determined by the user's locale.
  • Return true if the data is in the expected format, otherwise false.
L10n.validateNumber(value)
  • Verify that the numeric value-string (with or without a fractional amount) is in the format specified by the user's locale.
  • Return true if the data is in the expected format, otherwise false.
L10n.validatePercent(value)
  • Verify that the percentage-string is in the format specified by the user's locale.
  • Return true if the data is in the expected format, otherwise false.
L10n.validateTime(value)
  • Verify that the time-string is in the format specified by the user's locale.
  • Return true if the data is in the expected format, otherwise false.

Template Variables for Actions

About the Template Variable Tool

Use the Template Variable tool (shown below) to insert variables for Actions that Execute JavaScript

Template Variable Selector

Notepad.png

Note: In some contexts, variable names uses braces - { }. In other cases, they don't. The Template Variable Tool lets you quickly determine the format used in your current context.

Learn more: Template Variables

About Template Variables

AJAX and REST can be used to communicate with the platform, by writing JavaScript in an Action. The following implicit variables are available in the JavaScript:

object_id
A variable containing the identifier of the object
selectedRecords
An array containing one element - the identifier of the selected record
Examples
Identifier of the object that the user selected:
alert("You have selected object : " + object_id);
Dialog that shows the identifier of the first selected record:
alert("You have selected Record : " + selectedRecords[0];

Lookup a Template Variable

  1. Choose a Category.
    Category
    Each category contains a number of fields. The list of categories depends on your context.
  2. Choose a field from the Category.
    Fields
    Contains the available fields from the selected category.
    The Variable Field is populated with the syntax for your choice
  3. Copy the string and paste it into your work
    Variable field
    {$account.name}

Notepad.png

Note: When specifying a field, you use it's internal Field Name. Not the 'Field Label that appears in the GUI.

Template Variables for Actions that Execute JavaScript

The following JavaScript template variables are available for use in Custom Form Actions using the Execute JavaScript option. Some template variables are not evaluated when the action is executed. In the following table:

  • "Yes" indicates that the template variable is evaluated when the action is executed
  • "--" indicates that the template variable is not evaluated when the action is executed.
A warning message is displayed when a template variable is included that is of the not evaluated type.
Category Template Variable Single Record Group Action Both

Single Record

Both

Group Action

Object {$fieldname} Yes -- Yes --
$AppSessionID {$AppSessionID} Yes Yes Yes Yes
User
{$user.today} Yes Yes Yes Yes
{$user.full_name} Yes Yes Yes Yes
{$user.first_name} Yes Yes Yes Yes
{$user.last_name} Yes Yes Yes Yes
{$user.email} Yes Yes Yes Yes
{$user.phone} Yes Yes Yes Yes
{$user.city} Yes Yes Yes Yes
{$user.state} Yes Yes Yes Yes
{$user.zip} Yes Yes Yes Yes
{$user.country} Yes Yes Yes Yes
{$user.title} Yes Yes Yes Yes
{$user.division} Yes Yes Yes Yes
{$user.fax} Yes Yes Yes Yes
{$user.mobile} Yes Yes Yes Yes


AJAX and REST

The combination of JavaScript and the platform's REST APIs lets you build a lot of power into a page that displays on a client-side browser.

About AJAX

AJAX is the name given to a set of JavaScript functions that let you connect to a server, get back data, and parse the data into something usable. It originally stood for "Asynchronous JavaScript and XML", but it can also use the JSON format for data interchange.

Perhaps the best summary of AJAX comes from the w3c.schools tutorial:

"AJAX is the art of exchanging data with a server, and updating parts of a web page, without reloading the whole page."

While an arbitrary string can be passed to or from the server, the two most popular formats by far are XML and JSON. The platform understands both, so you can choose the flavor you prefer. (A common variation is to send XML data to the platform because it's easy to build up strings in XML format, and then get JSON back because that is the easiest format to parse in JavaScript.)

Learn more: AJAX Tutorial

Using AJAX in a Form

The jQuery functions included in the platform make it as simple as possible to make an AJAX call.

The code is expected to be executed as part of a Form, either as part of a Field Script or a Form Script. It builds up an XML string to send to a REST API. In this case, it creates the input XML required by the REST exec API, which executes a method in a Java class. And then tells the API to return JSON, which allows individual elements to be accessed by specifying little more than a JavaScript path.

For more information about using AJAX in a form, see the tech community article How to invoke a class from formscript using AJAX.

Using AJAX in a JSP Page

When you create a Page in the platform, you are creating a JSP page. You can embed Java code in that page, and use it to directly interact with the platform. Or you can use AJAX and the REST APIs, whichever is easiest.

For information on using AJAX in a JSP page, see the tech community article Invoking REST API Calls using AJAX in AgileApps Pages.

Example: Retrieving Data with a GET Request

To view the example on how to retrieve data using a GET request, see the tech community article Retrieving Data with a GET Request.

Example: Validating a CSRF session for POST, PUT, and DELETE

You have to validate a CSRF session for POST, PUT, and DELETE requests. For information about validating a CSRF session, see the Tech Community article at Validating a CSRF session for POST, PUT, and DELETE. This article provides sample codes for validating CSRF sessions for Form Submissions and REST APIs.

Notepad.png

Note: Ensure to add the header X-XSRF-TOKEN with value of xsrfToken from the login response.

Example: Retrieving a JSON output of Dynamic Search API on a custom object

Notepad.png

Note: This is applicable only for the legacy UI

To retrieve a JSON output of Dynamic Search API on a custom object, refer to this example:

var recordData = [];
$.ajax({
         type: 'GET',
         url: '/networking/rest/record/cases?fieldList=subject,description&alt=json',
         processData: true,
         dataType: 'json',
         async:false,
         success: function(data)
         {
if (data.platform.record instanceof Array )
{
recordData = data.platform.record ;
}
else if ( typeof data.platform.record != 'undefined' )
{
recordData.push(data.platform.record);
}
alert(recordData);
}
});


Accessing Additional Lookup Variables in a Form

When you have a Lookup field in a Form, you can select additional fields from the targeted record, and have them displayed in the Form.

For example, in the Sample Order Processing System, Order records have a lookup to the Customer that placed the order. The Lookup field shows the customer's name, by default. But you could specify additional fields to display in the form: The customer's address and contact information, for example.

When you write JavaScript for Field Scripting, Form Scripting, or Post Selection JavaScript that JavaScript can use "dot notation" to access the values in the additional fields, by following this pattern:

{current_record_lookup_field}.{target_record_field}

For example, In an Order record, then, you might access the Customer's zip code to calculate a shipping charge, like this:

var val =  document.getElementById("related_to_customer.zip_code").value;

Or, using jQuery functions to shorten the syntax:

var val = $('input[name=related_to_customer.zip_code]').val();