Skip to Main Content

Namespace: util

QuickNav

apex.util

The apex.util namespace contains general utility functions of Oracle Application Express.

Namespaces

delayLinger

Functions

(static) applyTemplate(pTemplate, pOptionsopt) → {string}

This function applies data to a template. It processes the template string given in pTemplate by substituting values according to the options in pOptions. The template supports Application Express server style placeholder and item substitution syntax.

This function is intended to process Application Express style templates in the browser. However it doesn't have access to all the data that the server has. When substituting page items and column items it uses the current value stored in the browser not what is in session state on the server. It does not support the old non-exact substitutions (with no trailing dot e.g. &ITEM). It does not support the old column reference syntax that uses #COLUMN_NAME#. It cannot call PREPARE_URL (this must be done on the server). Using a template to insert JavaScript into the DOM is not supported. After processing the template all script tags are removed.

The format of a template string is any text intermixed with any number of replacement tokens or directives. Two kinds of replacement tokens are supported: placeholders and data substitutions. Directives control the processing of the template. Directives are processed first, then placeholders and finally data subsitutions.

Placeholders

This is also known as a hash substitution.

Placeholder syntax is:

#<placeholder-name>#

The <placeholder-name> is an uppercase alpha numeric plus "_", and "$" string that must be a property name in option object placeholders that gets replaced with the property value. Any placeholder tokens that don't match anything in the placeholders object are left as is (searching for the next placeholder begins with the trailing # character).

Data substitutions

Substitution syntax is (any of):

&<item-name>.
&<item-name>!<escape-filter>.
&"<quoted-item-name>".
&"<quoted-item-name>"!<escape-filter>.
&APP_TEXT$<message-key>.
&APP_TEXT$<message-key>!<escape-filter>.
&"APP_TEXT$<message-key>".
&"APP_TEXT$<message-key>"!<escape-filter>.

The <item-name> is an uppercase alpha numeric plus "_", "$", and "#" string. The <quoted-item-name> is a string of any characters except "&", carriage return, line feed, and double quote. In both cases the item name is the name of a page item (unless option includePageItems is false), a column item (if model and record options are given), a built-in substitution (unless option includeBuiltinSubstitutions is false), or an extra substitution if option extraSubstitutions is given.

The <item-name> can include a property reference. A '%' character separates the item-name from the property name. For example &P1_NAME%LABEL. will return the label of the P1_NAME item. The property name is case insensitive.

The properties and the values they return for a page item are:

  • LABEL - The item label.
  • DISPLAY - The display value of the item's current value.
  • CHANGED - 'Y' if the item has been changed and 'N' otherwise.
  • DISABLED - 'Y' if the item is disabled and 'N' otherwise.

The properties for a column item are:

  • HEADING - The column heading text. The heading may include markup. If there is no heading the label will be used if there is one.
  • LABEL - The column label. If there is no label the heading will be used with markup removed.
  • DISPLAY - The display value of the column value for the current row/record.
  • HEADING_CLASS - Any CSS classes defined for the column heading.
  • COLUMN_CLASS - Any CSS classes defined for the column.
  • REQUIRED - 'Y' if the column is required and 'N' otherwise.

The <message-key> is a message key suitable for use in apex.lang.getMessage and is replaced with the localized message text for the given key. The message must already be loaded on the client by setting the Text Message attribute Used in JavaScript to On or otherwise adding it such as with apex.lang.addMessages. If no replacement for a substitution can be found it is replaced with the message key. The language specifier that is supported for server side message substitutions is not supported by the client and will be ignored if present.

When substituting a column item the given record of the given model is used to find a matching column name. If not found and if the model has a parent model then the parent model's columns are checked. This continues as long as there is a parent model. The order to resolve an item name is: page item, column item, column item from ancestor models, built-in substitutions, and finally extra substitutions. For backward compatibility column items support the "_LABEL" suffix to access the defined column label. For example if there is a column item named NOTE the substitution &NOTE_LABEL. will return the label string for column NOTE. It is better to use the label property in this case, for example: &NOTE%label..

The built-in substitution names are:

  • &APP_ID.
  • &APP_PAGE_ID.
  • &APP_SESSION.
  • &REQUEST.
  • &DEBUG.
  • &IMAGE_PREFIX.

The escape-filter controls how the replacement value is escaped or filtered. It can be one of the following values:

  • HTML the value will have HTML characters escaped using apex.util.escapeHTML.
  • ATTR the value will be escaped for an HTML attribute context (currently the same as HTML)
  • RAW does not change the value at all.
  • STRIPHTML the value will have HTML tags removed and HTML characters escaped.

This will override any default escape filter set with option defaultEscapeFilter or from the column definition escape property.

Directives

Directive syntax is:

{<directive-name>[ <directive-arguments>]/}

The directive name determines what it does as described below. Directive names are case insensitive. There can be no whitespace between the open bracket '{' and the directive name. Directives often come in sets that work together. A directive may have additional arguments.

If condition directives

Syntax:

{if [!]NAME/}
TRUE_TEMPLATE_TEXT
{elseif [!]NAME2/}
ELSE_TRUE_TEMPLATE_TEXT
{else/}
FALSE_TEMPLATE_TEXT
{endif/}

The entire text from the if directive to the matching endif directive is replaced with the processed template text following the first if or elseif directive that evaluates to true or the template text following the else directive if none are true. There must be an if and endif directive. The elseif and else directives are optional. There can be any number of elseif directives. The directives must go in the order shown. If directives can be nested. That means any of the template texts can contain another if directive.

The if and elseif directives test the value of NAME and if it is true process the following template text. The NAME can be an item-name, quoted-item-name, or placeholder-name. The value of an item-name or quoted-item-name is the value of that page item or column item. The value of a placeholder-name is the text of the placeholder. If no data substitution or placeholder with that name exists then the value is empty string.

A value is false if after trimming leading and trailing spaces it is an empty string, or for a page item the item item#isEmpty method returns true, or if the value is equal to any of the values in the falseValues option. Any value that is not false is true. If the name is prefixed with exclamation mark (!) then the logic is negated and the following template text is processed if the value is false.

Example:
The page contains items P1_TITLE, P_ICON, P1_DESCRIPTION, and P1_DETAILS and all have optional values. The template outputs a default title if P1_TITLE is empty. An optional icon is shown only if there is a title. The template output includes markup for the description if it is not empty or details if it is not empty and nothing otherwise.

<h3>{if P1_TITLE/}&P1_TITLE. {if P1_ICON/}<span class="fa &P1_ICON."></span>{endif/}
{else/}Untitled{endif/}</h3>
{if P1_DESCRIPTION/}
  <p class="description">&P1_DESCRIPTION.</p>
{elseif P1_DETAILS/}
  <p class="details">&P1_DETAILS.</p>
{endif/}

Case condition directives

Syntax:

{case NAME/}
{when string1/}
TEMPLATE_TEXT1
{when string2/}
TEMPLATE_TEXT2
{otherwise/}
TEMPLATE_TEXT
{endcase/}

The entire text from the case directive to the matching endcase directive is replaced with the processed template text after the when directive that matches the NAME value. The value of NAME is compared with each of the strings in the when directive and if it is equal the following template (TEMPLATE_TEXTn) is processed. If no when directive matches then the template after the otherwise directive is processed if there is one. The otherwise directive is optional but it must come at the end and there can only be one. Case directives can be nested. That means any of the template texts can contain another case directive.

The NAME can be an item-name, quoted-item-name, or placeholder-name. The value of an item-name or quoted-item-name is the value of that page item or column item. The value of a placeholder-name is the text of the placeholder. If no data substitution or placeholder with that name exists then the value is empty string. The NAME value and each string is trimmed of leading and trailing spaces before comparison. The comparison is case sensitive.

Example:
The page contains items P1_NAME and P1_DETAILS, and P1_DETAIL_STYLE that can have a value of "FULL" or "BRIEF". The intention is to control the markup according to the detail style.

{case P1_DETAIL_STYLE/}
{when FULL/}
    <div class="full">
        <span>&P1_NAME!HTML.</span>
        <p class="description">&P1_DETAILS!HTML.</p>
    </div>
{when BRIEF/}
  <div class="brief">
      <span>&P1_NAME!HTML.</span>
  </div>
{endcase/}

Loop directives

Syntax:

{loop ["SEP"] NAME/}
TEMPLATE_TEXT
{endloop/}

The entire text from the loop directive to the matching endloop directive is replaced with the template text evaluated once for each item in the NAME value.

The NAME can be an item-name, quoted-item-name, or placeholder-name. The value of an item-name or quoted-item-name is the value of that page item or column item. The value of a placeholder-name is the text of the placeholder. If no data substitution or placeholder with that name exists then the value is empty string. The NAME value should be a separator delimited string that contains a list of items. The optional SEP argument defines the separator character. The default separator is ":". If SEP is more than one character it is treated as a regular expression.

Within the loop there are two extra data substitutions available:

  • APEX$ITEM This is the value of the current item in the list.
  • APEX$I This is 1 based index of the current item in the list.

Example:
The following example takes a page item, P1_TAGS that contains a bar '|' separated list of tags such as "apples|cherries|pears" and turns it into an HTML list that can be nicely styled.

<ul class="tags">{loop "|" P1_TAGS/}
  <li class="tag-item">APEX$ITEM</li>
{endloop/}</ul>

Comments

Syntax:

{!<comment-text>/}

This directive is substituted with nothing. It allows adding comments to templates. The comment-text can be any characters except new line and the "/}" sequence.

Example:
This example includes a comment reminding the developer to complete something. In this case replace a hard coded English string with a localizable text message.

<span>Name: &P1_NAME.</span> {!to do replace Name: with text message/}

Escape open bracket '{'

Syntax:

{{/}

In rare cases a lone open bracket '{' can be confused for the start of a directive if another directive follows it on the same line.

Example:
This is an example where the open bracket '{' has to be escaped.

<span>The coordinates {{/}c, d} = {if VAL/}&VAL.{else/}unknown{endif/}</span>

Here are similar cases that don't require an escape.

<span>The coordinates { c, d } = {if VAL/}&VAL.{else/}unknown{endif/}</span>
<span>The coordinates {c, d} =
{if VAL/}&VAL.{else/}unknown{endif/}</span>
Parameters:
Name Type Attributes Description
pTemplate string A template string with any number of replacement tokens as described above.
pOptions Object <optional>
An options object with the following properties that specifies how the template is to be processed:
Properties
Name Type Attributes Description
placeholders Object <optional>
An object map of placeholder names to values. The default is null.
directives boolean <optional>
Specify if directives are processed. If true directives are processed. If false directives are ignored and remain part of the text. The default is true.
defaultEscapeFilter string <optional>
One of the above escape-filter values. The default is HTML. This is the escaping/filtering that is done if the substitution token doesn't specify an escape-filter. If a model column definition has an escape property then it will override the default escaping.
includePageItems boolean <optional>
If true the current value of page items are substituted. The default is true.
model model <optional>
The model interface used to get column item values. The default is null.
record model.Record <optional>
The record in the model to get column item values from. Option model must also be provided. The default is null.
extraSubstitutions Object <optional>
An object map of extra substitutions. The default is an empty object.
includeBuiltinSubstitutions boolean <optional>
If true built-in substitutions such as APP_ID are done. The default is true.
falseValues Array.<string> <optional>
An array of values that are considered false in if directive tests. Empty string and an item that doesn't exist are always considered false. The default is ["F", "f", "N", "n", "0"]
Returns:
The template string with replacement tokens substituted with data values.
Type
string
Examples

This example inserts an image tag where the path to the image comes from the built-in IMAGE_PREFIX substitution and a page item called P1_PROFILE_IMAGE_FILE.

apex.jQuery( "#photo" ).html(
    apex.util.applyTemplate(
        "<img src='&IMAGE_PREFIX.people/&P1_PROFILE_IMAGE_FILE.'>" ) );

This example inserts a div with a message where the message text comes from a placeholder called MESSAGE.

var options = { placeholders: { MESSAGE: "All is well." } };
apex.jQuery( "#notification" ).html( apex.util.applyTemplate( "<div>#MESSAGE#</div>", options ) );

(static) arrayEqual(pArray1, pArray2) → {boolean}

Compare two arrays and return true if they have the same number of elements and each element of the arrays is strictly equal to each other. Returns false otherwise. This is a shallow comparison.

Parameters:
Name Type Description
pArray1 Array The first array.
pArray2 Array The second array.
Returns:
true if a shallow comparison of the array items are equal
Type
boolean
Examples

This example returns true.

apex.util.arrayEqual( [1,"two",3], [1, "two", 3] );

This example returns false.

apex.util.arrayEqual( [1,"two",3], [1, "two", "3"] );

(static) cancelInvokeAfterPaint(pId)

Wrapper around cancelAnimationFrame that can fallback to clearTimeout. Cancels the callback using the id returned from apex.util.invokeAfterPaint.

Parameters:
Name Type Description
pId * The id returned from apex.util.invokeAfterPaint.
Example

See example for function apex.util.invokeAfterPaint

(static) debounce(pFunction, pDelay) → {function}

Returns a new function that calls pFunction but not until pDelay milliseconds after the last time the returned function is called.

Parameters:
Name Type Description
pFunction function The function to call.
pDelay number The time to wait before calling the function in milliseconds.
Returns:
The debounced version of pFunction.
Type
function
Example

This example calls the function formatValue in response to the user typing characters but only after the user pauses typing. In a case like this formatValue would also be called from the blur event on the same item.

function formatValue() {
    var value = $v("P1_PHONE_NUMBER");
    // code to format value as a phone number
    $s("P1_PHONE_NUMBER_DISPLAY", value);
}
apex.jQuery( "#P1_PHONE_NUMBER" ).on( "keypress", apex.util.debounce( formatValue, 100 ) );

(static) escapeCSS(pValue) → {string}

Returns string pValue with any CSS meta-characters escaped. Use this function when the value is used in a CSS selector. Whenever possible if a value is going to be used as a selector, constrain the value so that it cannot contain CSS meta-characters making it unnecessary to use this function.

Parameters:
Name Type Description
pValue string The string that may contain CSS meta-characters to be escaped.
Returns:
The escaped string, or an empty string if pValue is null or undefined.
Type
string
Example

This example escapes an element id that contains a (.) period character so that it finds the element with id = "my.id". Without using this function the selector would have a completely different meaning.

apex.jQuery( "#" + apex.util.escapeCSS( "my.id" ) );

(static) escapeHTML(pValue) → {string}

Returns string pValue with any special HTML characters (&<>"'/) escaped to prevent cross site scripting (XSS) attacks. It provides the same functionality as sys.htf.escape_sc in PL/SQL.

This function should always be used when inserting untrusted data into the DOM.

Parameters:
Name Type Description
pValue string The string that may contain HTML characters to be escaped.
Returns:
The escaped string.
Type
string
Example

This example appends text to a DOM element where the text comes from a page item called P1_UNTRUSTED_NAME. Data entered by the user cannot be trusted to not contain malicious markup.

apex.jQuery( "#show_user" ).append( apex.util.escapeHTML( $v("P1_UNTRUSTED_NAME") ) );

(static) getDateFromISO8601String(pDateStr) → {Date}

Get a JavaScript Date object corresponding to the input date string which must be in simplified ISO 8601 format. In the future Date.parse could be used but currently there are browsers we support that don't yet support the ISO 8601 format. This implementation is a little stricter about what parts of the date and time can be defaulted. The year, month, and day are always required. The whole time including the T can be omitted but if there is a time it must contain at least the hours and minutes. The only supported time zone is "Z". This function is useful for turning the date strings returned by the APEX_JSON.STRINGIFY and APEX_JSON.WRITE procedures that take a DATE value into Date objects that the client can use.
Parameters:
Name Type Description
pDateStr string String representation of a date in simplified ISO 8601 format
Returns:
Date object corresponding to the input date string.
Type
Date
Example

This example returns a date object from the date string in result.dateString. For example "1987-01-23T13:05:09.040Z"

var date1 getDateFromISO8601String( result.dateString );

(static) getNestedObject(pRootObject, pPath) → {Object}

Returns the nested object at the given path pPath within the nested object structure in pRootObject creating any missing objects along the path as needed. This function is useful when you want to set the value of a property in a deeply nested object structure and one or more of the nested objects may or may not exist.

Parameters:
Name Type Description
pRootObject Object The root object of a nested object structure.
pPath string A dot ('.') separated list of properties leading from the root object to the desired object to return.
Returns:
Type
Object
Example

This example sets the value of options.views.grid.features.cellRangeActions to false. It works even when the options object does not contain a views.grid.features object or a views.grid object or even a views object.

var o = apex.util.getNestedObject( options, "views.grid.features" );
o.cellRangeActions = false; // now options.views.grid.features.cellRangeActions === false

(static) getScrollbarSize() → {object}

Gets the system scrollbar size for cases in which the addition or subtraction of a scrollbar height or width would effect the layout of elements on the page. The page need not have a scrollbar on it at the time of this call.

Returns:
An object with height and width properties that describe any scrollbar on the page.
Type
object
Example

The following example returns an object such as { width: 17, height: 17 }. Note the actual height and width depends on the Operating System and its various display settings.

var size = apex.util.getScrollbarSize();

(static) htmlBuilder() → {htmlBuilder}

Return an htmlBuilder interface.

Returns:
Type
htmlBuilder

(static) invokeAfterPaint(pFunction) → {*}

Wrapper around requestAnimationFrame that can fallback to setTimeout. Calls the given function before next browser paint. See also apex.util.cancelInvokeAfterPaint.

See HTML documentation for window.requestAnimationFrame for details.

Parameters:
Name Type Description
pFunction function function to call after paint
Returns:
id An id that can be passed to apex.util.cancelInvokeAfterPaint
Type
*
Example

This example will call the function myAnimationFunction before the next browser repaint.

var id = apex.util.invokeAfterPaint( myAnimationFunction );
// ... if needed it can be canceled
apex.util.cancelInvokeAfterPaint( id );

(static) showSpinner(pContaineropt, pOptionsopt) → {jQuery}

Function that renders a spinning alert to show the user that processing is taking place. Note that the alert is defined as an ARIA alert so that assistive technologies such as screen readers are alerted to the processing status.

Parameters:
Name Type Attributes Description
pContainer string | jQuery | Element <optional>
Optional jQuery selector, jQuery, or DOM element identifying the container within which you want to center the spinner. If not passed, the spinner will be centered on the whole page. The default is $("body").
pOptions Object <optional>
Optional object with the following properties:
Properties
Name Type Attributes Description
alert string <optional>
Alert text visually hidden, but available to Assistive Technologies. Defaults to "Processing".
spinnerClass string <optional>
Adds a custom class to the outer SPAN for custom styling.
fixed boolean <optional>
if true the spinner will be fixed and will not scroll.
Returns:
A jQuery object for the spinner. Use the jQuery remove method when processing is complete.
Type
jQuery
Examples

To show the spinner when processing starts.

var lSpinner$ = apex.util.showSpinner( $( "#container_id" ) );

To remove the spinner when processing ends.

lSpinner$.remove();

(static) stripHTML(pText) → {string}

Returns string pText with all HTML tags removed.

Parameters:
Name Type Description
pText string The string that may contain HTML markup that you want removed.
Returns:
The input string with all HTML tags removed.
Type
string
Example

This example removes HTML tags from a text string.

apex.util.stripHTML( "Please <a href='www.example.com/ad'>click here</a>" );
// result: "Please click here"

(static) toArray(pValue, pSeparatoropt) → {Array}

Function that returns an array based on the value passed in pValue.

Parameters:
Name Type Attributes Default Description
pValue string | * If this is a string, then the string will be split into an array using the pSeparator parameter. If it's not a string, then we try to convert the value with apex.jQuery.makeArray to an array.
pSeparator string <optional>
":" Separator used to split a string passed in pValue, defaults to colon if not specified. Only needed when pValue is a string. It is ignored otherwise.
Returns:
Type
Array
Examples

This example splits the string into an array with 3 items: ["Bags","Shoes","Shirts"].

lProducts = apex.util.toArray( "Bags:Shoes:Shirts" );

This example splits the string into an array just like in the previous example. The only difference is the separator character is ",".

lProducts = apex.util.toArray( "Bags,Shoes,Shirts", "," );

This example returns the jQuery object as an array.

lTextFields = apex.util.toArray( jQuery("input[type=text]") );