skuid.utils


Good news, everyone!

We are currently writing more material for our Javascript API. All of the objects and functions you see below are part of Skuid’s public API, even if they aren’t fully documented yet. Feel free to experiment while we write about them—and check back later for updates.


The skuid.utils object provides convenient functions for commonly used functionality in Skuid.

Properties

skuid.utils.isMultiCurrencyOrganization

boolean

True if this Salesforce.com organization / environment has the Multi-Currency feature enabled.

skuid.utils.userInfo

object

An object containing various fields from the running user’s User object, including but not limited to:

  • defaultCurrency (e.g. “USD”)
  • firstName (e.g. “John”)
  • language (e.g. “en_GB”)
  • lastName (e.g. “Smith”)
  • locale (the Salesforce.com key for this locale - not always ISO, e.g. “en_US” or “fr_FR”)
  • name (e.g. “John Smith”)
  • organizationId (the Id of the Salesforce.com organization / environment.)
  • profileId (the running User’s Profile’s Id)
  • userId (the running user’s Id)
skuid.utils.userLocale

object

An object containing various fields describing the running user’s Locale, including:

  • dateFormat (e.g. “m/d/yy”, where “m” is month, “d” is day in month, “y” is the year. Use multiple to force prepending zeros, if possible, or the full year)
  • decimalsSeparator (the character used to distinguish the “decimal” part of a number from the integer part, e.g. ”.”)
  • defaultCurrency (the 3-digit ISO code of the locale’s default currency, e.g. “USD”)
  • firstDay (the integer index of the first day of the locale’s calendar week, with Sunday being 0)
  • isRTL (true if dates and time are written right-to-left in this locale)
  • localeName (e.g. “English (United States)”)
  • showMonthAfterYear (true if the month should be shown after the year in datepickers)
  • showTimeBeforeDate (true if the time should be shown before the date in datepickers)
  • thousandsSeparator (the character used to separate every 3 integer digits in this locale, e.g. ”,”)
  • timeFormat (e.g. “h:mm a”, where “h” is hour, “m” is minute, “a” is the AM/PM indicator. Use multiple to force prepending zeros, if possible)

Functions

skuid.utils.convertCurrency(value, fromIsoCode, toIsoCode)

Converts a currency value from one ISO currency to another, based on the conversion rates defined in the Salesforce.com organization. (Only available for Multi-Currency organizations)

Arguments:
  • value (number) – The currency amount to convert
  • fromIsoCode (string) – The ISO code representing the currency in which value is expressed
  • toIsoCode (string) – The ISO code representing the desired currency
Returns:

The converted currency amount -or- the original value if one or both ISO codes were not recognized or no currencies were defined for the current org or the current org does not support multiple currencies.

Return type:

number

skuid.utils.createPopupFromPopupXML(popupXML, context)
Arguments:
  • popupXML (object) –

    A JQuery object containing the XML to be used for the popup, similar to what would be created by Skuid using one of the Popup action types.

    For example:

    <popup title="Editing Case: {{CaseNumber}}" width="80%">
     <components>
        <pagetitle model="CaseData">
            <maintitle>{{CaseNumber}}: {{Subject}}</maintitle>
         </pagetitle>
     </components>
    </popup>
    

    Note

    For ease of use, store the XML string as a variable, and then use that variable as your popupXML parameter.

  • context (object) –

    (Optional) JavaScript object providing Skuid with some context in which to create the popup — for instance, you might want to pass in a particular row here so that Skuid knows which row to render the popup relative to.

    For example:

    1
    2
    3
    4
    5
    6
    // Get the 14th row in our Cases Model
    var case = CasesModel.data[13];
    
    context = {
    row: case
    };
    
Returns:

jQuery UI Dialog / Popup box

Return type:

object

skuid.utils.decodeHTML(value)

Decodes html characters like &amp; into their actual character.

Arguments:
  • value (string) – An HTML string to decode.
Returns:

A decoded HTML string. For example, where “&amp;” and “&gt;” have been converted into “&” and “>”.

Return type:

string

skuid.utils.delayInputCallback(inputElement, callback)

A delayed on-change handler for an input element, which waits for a user to stop typing for 400 milliseconds before calling a callback function with the new and old values of the input element. The purpose of this function is to improve the user experience of on-change handlers, such that logic is not executed immediately upon a single change to a given field but rather only when a user “finishes” typing temporarily.

Arguments:
  • inputElement (jQuery-wrapped DOM Element) – A jQuery-wrapped input element to listen for changes on.
  • callback (function(newValue,oldValue)) – (function(newValue,oldValue)) A function that will be called after the user has stopped typing for 400 milliseconds, which will be handed the new value and the old value as its first and second parameters, respectively.
Returns:

No return value.

EXAMPLE:

The following Custom Field Renderer snippet will console log a field’s value after the user has “stopped” typing.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
{
  var field = arguments[0],
     value = skuid.utils.decodeHTML(arguments[1]);
  // Run the default renderer
  skuid.ui.getFieldRenderer(field.metadata.displaytype)[field.mode](field,value);
  if (field.mode==='edit') {
      var input = field.element.find(':input');
       skuid.utils.delayInputCallback(input,function(newValue,oldValue){
         console.log('[' + field.id + '] New value: ' + newValue +', old value: ' + oldValue);
      });
}
skuid.utils.encodeHTML(value)

Encodes html characters like & into their encoded value like &amp;.

Arguments:
  • value (string) – Any string value
Returns:

An HTML-encoded string where special characters have been escaped. For example, where “&” and “>” have been converted into “&amp;” and “&gt;”.

Return type:

string

skuid.utils.escapeSingleQuotes(value)

Escapes single quotes in a string.

Arguments:
  • values (string) – Any string value
Returns:

The input string where single quotes have been escaped with a backslash. For example, given the input “O’Reailly”, this function would return “O’Reilly”.

Return type:

string

skuid.utils.generateGUID()

Generates a Unique Identifier within a Skuid page.

Returns:A unique identifier within the current context.
Return type:string
skuid.utils.getObjectProperty(object, propertyName)
Retrieves the value of an arbitrarily nested property from a JavaScript object using a dot-notation path.
Arguments:
  • object (object) – The object to retrieve the given property from
  • propertyName (string) – The path defined using dot-notation. Array indices can also be provided for traversing array values, e.g. arrayProp.0.propOnFirstItem
Returns:

The value of the property at the given path. If no such property exists, will return undefined.

Return type:

string, number, boolean, object, null, undefined

EXAMPLE

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
var obj = {
  "Account": {
    "Parent": {
      "Name": "ACME Global",
      "Type": "Customer"
    },
    "Name": "Acme USA"
  },
  "AccountId": "001000000034632"
};

skuid.utils.getObjectProperty(obj, "Account.Name");
// => "ACME USA"
skuid.utils.getObjectProperty(obj, "Account.Parent.Name");
// => "ACME Global"
skuid.utils.getUrlFromAttachmentId(attachmentId)

Generates a URL to the raw attachment file. Useful for creating a download link or for displaying images on the page.

Arguments:
  • attachmentId (string) – A Salesforce 18-character Attachment Id
Returns:

A URL for the attachment. Useful for downloading content or displaying images within an IMG tag. The format typically looks something like this:

/servlet/servlet.FileDownload?file=<18-character Id>
Return type:string
skuid.utils.getXML(xmlNode)

Takes an XML Node / Document and outputs an XML string representation of it.

Arguments:
  • xmlNode (Node / Document) – An XML node within an XML tree, either the tree’s root node or any descendant
Returns:

A string representation of the provided XML node or document

Return type:

string

EXAMPLE

1
2
3
4
5
6
7
8
var xmlString = '<books><book name="Travels with Charley"/><book name="The Brothers Karamazov"/></books>';
var xmlDoc = skuid.utils.makeXMLDoc(xmlString);
xmlDoc.append(
  skuid.utils.makeXMLDoc('<book name="Hyperion"/>')
);
var newXmlString = skuid.utils.getXML(xmlDoc[0]);
console.log(newXmlString);
-> <books><book name="Travels with Charley"/><book name="The Brothers Karamazov"/><book name="Hyperion"/></books>
skuid.utils.hasObjectProperty(object, propertyName)
Returns true if a given JavaScript object has a property at an arbitrarily nested location, specified using a dot-notation path.
Arguments:
  • object (object) – The object to retrieve the given property from
  • propertyName (string) – The path defined using dot-notation. Array indices can also be provided for traversing array values, e.g. arrayProp.0.propOnFirstItem
Returns:

True if the object contains a property at the given path, otherwise false.

Return type:

boolean

EXAMPLE

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
var obj = {
  "Account": {
    "Parent": {
      "Name": "ACME Global",
      "Type": "Customer"
    },
    "Name": "Acme USA"
  },
  "AccountId": "001000000034632"
};

skuid.utils.hasObjectProperty(obj, "Account.Name");
// => true
skuid.utils.hasObjectProperty(obj, "Account.Parent.OwnerId");
// => false
skuid.utils.makeXMLDoc(xmlString)

Parses a string of XML and generates a jQuery-wrapped XML Document. Useful for generating XML for use in dynamic creation of Skuid Models and Components.

Arguments:
  • xmlString (string) – a string of valid XML
Returns:

A jQuery object wrapping the parsed XML Document.

Return type:

jQuery object

EXAMPLE

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// Build a set of tabs that we'd like to add to a tab set
var tabNames = ["Animals","Vegetables","Minerals"];
// Generate a Tab Set XML document
var $xml = skuid.utils.makeXMLDoc;
var tabsetXml = $xml('<tabset/>').append(
   $xml('<tabs/>').append(skuid.$.map(tabNames,function(tabName){
      return $xml('<tab/>').attr('name',tabName);
   }))
);
// Generate a Tab Set component and add it to the bottom of the first skuidpage component
var tabsetComponent = skuid.component.factory({ definition: tabsetXml });
tabsetComponent.element.appendTo(
   skuid.component.getByType('skuidpage')[0].element
);
skuid.utils.merge(mode, template, options, model, row)

Evaluates a Skuid merge template, using Skuid’s Template syntax, in the desired mode.

Arguments:
  • mode (string) –

    Must be one of the following values:

    • ”global” - no specific Model or Row context is expected
    • ”model” - a specific Model context is expected, but not a Row
    • ”row” - a specific Model and Row context is expected
  • template (string) – A Skuid Template. For more information about Skuid-specific template syntax, see the Template Syntax and the Merge API docs.
  • options (object) –

    Optional. A simple object with any of the following properties:

    • nl2br (boolean): Optional, defaults to true. If set to false, prevents conversion of new line characters to HTML line break tags.
    • createFields (boolean): Optional, defaults to true. If true, Skuid will create skuid.ui.Fields if the merge method is “row” and field level merges, e.g. {{FirstName}} {{LastName}}, are encountered.
  • model (skuid.model.Model) – Optional. The Model to use when resolving the template in “model” mode.
  • row (object) – Optional. A simple row object to use when resolving the template in “row” mode. Can be obtained via a skuid.model.Model object’s getRowById() function or, simply, via the data property.
Returns:

jQuery-wrapped HTML. If you would like to return text, then use skuid.utils.mergeAsText() instead.

skuid.utils.mergeAsText(mode, template, options, model, row)

Evaluates a Skuid merge template, using Skuid’s Template syntax, in the desired mode.

Arguments:
  • mode (string) –

    Must be one of the following values:

    • ”global” - no specific Model or Row context is expected
    • ”model” - a specific Model context is expected, but not a Row
    • ”row” - a specific Model and Row context is expected
  • template (string) – A Skuid Template. For more information about Skuid-specific template syntax, see the Template Syntax and the Merge API docs.
  • options (object) –

    Optional. A simple object with any of the following properties:

    • createFields (boolean): Optional, defaults to true. If true, Skuid will create skuid.ui.Fields if the merge method is “row” and field level merges, e.g. {{FirstName}} {{LastName}}, are encountered. The HTML elements generated for these fields will be converted to text.
  • model (skuid.model.Model) – Optional. The Model to use when resolving the template in “model” mode.
  • row (object) – Optional. A simple row object to use when resolving the template in “row” mode. Can be obtained via a skuid.model.Model object’s getRowById() function or, simply, via the data property.
Returns:

A text string containing the result of the merge.

skuid.utils.mergeAsTextInContext(template, context[, mergeSettings])

Evaluates a Skuid merge template, using Skuid’s Template syntax, using whatever model and/or row context is provided.

The mode used for the merge is determined automatically by the presence of model and/or row properties in the optional context object - if model is provided and resolves to a valid Skuid Model, then the merge mode will be “model”, and if a row is provided, then the merge mode will be “row”, but if neither “model” or “row” is provided then the mode will be “global”.

Arguments:
  • template (string) – A Skuid Template. For more information about Skuid-specific template syntax, see the Template Syntax and the Merge API docs.
  • context (object) – Optional. A simple object with any of the following properties:
  • model (skuid.model.Model) – Optional. The Model to use when resolving the template in “model” mode.
  • row (object) – Optional. A simple row object to use when resolving the template in “row” mode. Can be obtained via a skuid.model.Model object’s getRowById() or getRows() functions.
  • mergeSettings (object) – Optional. A simple object with any of the following properties:
  • createFields (boolean) – Optional, defaults to true. If true, Skuid will create skuid.ui.Fields if the merge method is “row” and field level merges, e.g. {{FirstName}} {{LastName}}, are encountered. The HTML elements generated for these fields will be converted to text.
Returns:

A text string containing the result of the merge.

skuid.utils.setObjectProperty(object, propertyName, propertyValue)
Sets the value of an arbitrarily nested property on a JavaScript object using a dot-notation path.
Arguments:
  • object (object) – The object to set the given property on
  • propertyName (string) – The path defined using dot-notation.
  • propertyValue (object) –

    The new value to set for the object property at the given path

    EXAMPLE

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
var obj = {
  "Account": {
    "Parent": {
      "Name": "ACME Global",
      "Type": "Customer"
    },
    "Name": "Acme USA"
  },
  "AccountId": "001000000034632"
};

skuid.utils.getObjectProperty(obj, "Account.Parent.Type");
// => "Customer"
skuid.utils.setObjectProperty(obj, "Account.Parent.Type", "Partner");
skuid.utils.getObjectProperty(obj, "Account.Parent.Type");
// => "Partner"
skuid.utils.size(object)

Returns the number of properties defined on the provided object. Essentially a shortcut for Object.keys(object).length

Arguments:
  • object (object) – An input object to examine.
Returns:

Number of properties defined on the object

Return type:

number

var obj = { "uno": "one", "dos": "two" };
skuid.utils.size(obj);
//  => 2

Examples

For these examples, we’ll assume that we have a Skuid Page with 3 Models:

# “Account” - limited to one Account, with various Account fields pulled in # “Contacts” - all Contacts on the Account in our first Model # “Opportunities” - all Opportunities on the Account in our first Model

# “Account” - limited to one Account, with various Account fields pulled in
# “Contacts” - all Contacts on the Account in our first Model.
# “Opportunities” - all Opportunities on the Account in our first Model.

// Define the DOM element we want to write to
var output = $('#output');
// 1. Global merge examples
var template = '<b>{{$Model.Opportunities.labelPlural}} Tab</b>';
   output.append(
   skuid.utils.merge('global',template)
   );
// --> displays 'Opportunities Tab', or the localized equivalent
   template = '{{$Model.Account.fieldsMap.Name.label}}: {{#$Model.Account.data}}{{Name}}{{/$Model.Account.data}}';
   output.append(
   skuid.utils.merge('global',template)
   );
// --> displays 'Account Name: ACME Recruiting'
// 2. Model merge examples
// We'll build an HTML table.
template = '<table>';
// We'll populate the headers of each table column
// by pulling from the metadata of each 3 fields in our Model,
template += '<thead>';
template += '<th>{{Model.Fields.Name.label}}</th>';
template += '<th>{{Model.Fields.StageName.label}}</th>';
template += '<th>{{Model.Fields.CloseDate.label}}</th>';
template += '</thead>';
// We'll populate the body of our table
// by looping over the data rows in our Model,
// using Mustache section syntax,
// and creating <td> cells populated with each rows corresponding data.
template += '<tbody>'template += '{{#Model.Data}}';
template += '<tr>';
template += '<td>{{Name}}</td>';
template += '<td>{{StageName}}</td>';
template += '<td>{{CloseDate}}</td>';
template += '</tr>';
template += '{{/Model.Data}}';
// If we have NO data rows,
// we'll using Mustache's inverted section syntax to display a message
template += '{{^Model.Data}}';
template += '<tr><td colspan="3">There are no Opportunities to display on this Account.</td></tr>';
template += '{{/Model.Data}}';
template += '</tbody>';
template += '</table>';
output.append(
    skuid.utils.merge('model',template,{},skuid.model.getModel('Opportunities'))
);

The following “row” merge variables are only available in the row merge context:

  • first: true if this is the first Row in the Model’s data
  • last: true if this is the last Row in the Model’s data
  • index: returns the index of this row in the Model’s data