Class Index | File Index

Classes


Namespace LABKEY.Utils

Utils static class to provide miscellaneous utility functions.
Defined in: Utils.js.

Namespace Summary
Constructor Attributes Constructor Name and Description
 
Method Summary
Method Attributes Method Name and Description
<static>  
LABKEY.Utils.alert(title, msg)
Display an error dialog.
<static>  
LABKEY.Utils.apply(object, config)
Applies config properties to the specified object.
<static>  
LABKEY.Utils.applyTranslated(target, source, translationMap, applyOthers, applyFunctions)
Applies properties from the source object to the target object, translating the property names based on the translation map.
<static>  
LABKEY.Utils.capitalize(value)
Returns the string value with the first char capitalized.
<static>  
LABKEY.Utils.caseInsensitiveEquals(a, b)
Returns true if the arguments are case-insensitive equal.
<static>  
LABKEY.Utils.confirmAndPost(message, href)
Displays a confirmation dialog with the specified message and then, if confirmed, POSTs to the href, using the method above
<static>  
LABKEY.Utils.convertToExcel(spreadsheet)
Sends a JSON object to the server which turns it into an Excel file and returns it to the browser to be saved or opened.
<static>  
LABKEY.Utils.convertToTable()
Sends a JSON object to the server which turns it into an TSV or CSV file and returns it to the browser to be saved or opened.
<static>  
LABKEY.Utils.decode(data)
Decodes (parses) a JSON string to an object.
<static>  
LABKEY.Utils.deleteCookie(name, pageonly)
Deletes a cookie.
<static>  
LABKEY.Utils.displayAjaxErrorResponse(responseObj, exceptionObj, showExceptionClass, msgPrefix)
Shows an error dialog box to the user in response to an error from an AJAX request, including any error messages from the server.
<static>  
LABKEY.Utils.encode(data)
Encodes an Object to a string.
<static>  
LABKEY.Utils.encodeHtml(html)
Encodes the html passed in so that it will not be interpreted as HTML by the browser.
<static>  
LABKEY.Utils.endsWith(value, ending)
Returns true if value ends with ending
<static>  
LABKEY.Utils.generateUUID()
Returns a universally unique identifier, of the general form: "92329D39-6F5C-4520-ABFC-AAB64544E172" NOTE: Do not use this for DOM id's as it does not meet the requirements for DOM id specification.
<static>  
LABKEY.Utils.getCallbackWrapper(fn, scope, isErrorCallback)
This is used internally by other class methods to automatically parse returned JSON and call another success function passing that parsed JSON.
<static>  
LABKEY.Utils.getCookie(name, defaultvalue)
Retrieves a cookie.
<static>  
LABKEY.Utils.getDateAltFormats()
Returns date formats for use in an Ext.form.DateField.
<static>  
LABKEY.Utils.getDateTimeFormatWithMS()
Returns date format with timestamp including milliseconds.
<static>  
LABKEY.Utils.getFileIconUrl(fileName)
Returns a URL to the appropriate file icon image based on the specified file name.
<static>  
LABKEY.Utils.getOnFailure(config)
Standard documented name for error callback arguments is "failure" but various other names have been employed in past.
<static>  
LABKEY.Utils.getOnSuccess(config)
Standard documented name for success callback arguments is "success" but various names have been employed in past.
<static>  
LABKEY.Utils.getSessionID()
Retrieves the current LabKey Server session ID.
<static>  
LABKEY.Utils.id(prefix)
Will generate a unique id.
<static>  
LABKEY.Utils.isBoolean(value)
Tests whether the passed value can be used as boolean, using a loose definition.
<static>  
LABKEY.Utils.isEmptyObj(ob)
Returns true if the passed object is empty (ie.
<static>  
LABKEY.Utils.isString(value)
Returns true if the passed value is a string.
<static>  
LABKEY.Utils.merge(a, b, c)
Apply properties from b, c, .
<static>  
LABKEY.Utils.mergeIf(a, b, c)
Apply properties from b, c, .
<static>  
LABKEY.Utils.modal(title, msg, fn, args)
Display a modal dialog.
<static>  
LABKEY.Utils.onError(error)
Provides a generic error callback.
<static>  
LABKEY.Utils.onReady(config)
Adds new listener to be executed when all required scripts are fully loaded.
<static>  
LABKEY.Utils.onTrue(config)
Iteratively calls a tester function you provide, calling another callback function once the tester function returns true.
<static>  
LABKEY.Utils.padString(input, length, padChar)
Will pad the input string with zeros to the desired length.
<static>  
LABKEY.Utils.postToAction(href)
POSTs to the given href, including CSRF token.
<static>  
LABKEY.Utils.requiresCSS(filePath)
Includes a Cascading Style Sheet (CSS) file into the page.
<static>  
LABKEY.Utils.requiresScript(file, callback, scope, inOrder)
Loads JavaScript file(s) from the server.
<static>  
LABKEY.Utils.resizeToViewport()
This method has been migrated to specific instances for both Ext 3.4.1 and Ext 4.2.1.
<static>  
LABKEY.Utils.roundNumber(input, dec)
Rounds the passed number to the specified number of decimals
<static>  
LABKEY.Utils.setCookie(name, value, pageonly, days)
Sets a client-side cookie.
<static>  
LABKEY.Utils.setWebpartTitle(title, webPartId)
Sets the title of the webpart on the page.
<static>  
LABKEY.Utils.textLink(config)
Returns a string containing a well-formed html anchor that will apply theme specific styling.
Namespace Detail
LABKEY.Utils
Method Detail
<static> LABKEY.Utils.alert(title, msg)
Display an error dialog.
Parameters:
title
msg

<static> {*} LABKEY.Utils.apply(object, config)
Applies config properties to the specified object.
Parameters:
object
config
Returns:
{*}

<static> LABKEY.Utils.applyTranslated(target, source, translationMap, applyOthers, applyFunctions)
Applies properties from the source object to the target object, translating the property names based on the translation map. The translation map should have an entry per property that you wish to rename when it is applied on the target object. The key should be the name of the property on the source object and the value should be the desired name on the target object. The value may also be set to null or false to prohibit that property from being applied. By default, this function will also apply all other properties on the source object that are not listed in the translation map, but you can override this by supplying false for the applyOthers parameter.
Parameters:
target
The target object
source
The source object
translationMap
A map listing property name translations
applyOthers
Set to false to prohibit application of properties not explicitly mentioned in the translation map.
applyFunctions
Set to false to prohibit application of properties that are functions

<static> {String} LABKEY.Utils.capitalize(value)
Returns the string value with the first char capitalized.
Parameters:
{String} value
The string value to capitalize
Returns:
{String}

<static> {boolean} LABKEY.Utils.caseInsensitiveEquals(a, b)
Returns true if the arguments are case-insensitive equal. Note: the method converts arguments to strings for the purposes of comparing numbers, which means that it will return odd behaviors with objects (ie. LABKEY.Utils.caseInsensitiveEquals({t: 3}, '[object Object]') returns true)
Parameters:
{String/Number} a
The first item to test
{String/Number} b
The second item to test
Returns:
{boolean} True if arguments are case-insensitive equal, false if not

<static> LABKEY.Utils.confirmAndPost(message, href)
Displays a confirmation dialog with the specified message and then, if confirmed, POSTs to the href, using the method above
Parameters:
message
href

<static> LABKEY.Utils.convertToExcel(spreadsheet)
Sends a JSON object to the server which turns it into an Excel file and returns it to the browser to be saved or opened.
<script type="text/javascript">
 LABKEY.Utils.convertToExcel(
 {
     fileName: 'output.xls',
     sheets:
     [
         {
             name: 'FirstSheet',
             data:
             [
                 ['Row1Col1', 'Row1Col2'],
                 ['Row2Col1', 'Row2Col2']
             ]
         },
         {
             name: 'SecondSheet',
             data:
             [
                 ['Col1Header', 'Col2Header'],
                 [{value: 1000.5, formatString: '0,000.00'}, {value: '5 Mar 2009 05:14:17', formatString: 'yyyy MMM dd'}],
                 [{value: 2000.6, formatString: '0,000.00'}, {value: '6 Mar 2009 07:17:10', formatString: 'yyyy MMM dd'}]

             ]
         }
     ]
 });
 </script>
Parameters:
{Object} spreadsheet
the JavaScript representation of the data
{String} spreadsheet.fileName
name to suggest to the browser for saving the file. If the fileName is specified and ends with ".xlsx", it will be returned in Excel 2007 format.
{String} spreadsheet.sheets
array of sheets, which are objects with properties:
  • name: name of the Excel sheet
  • data: two dimensional array of values
The value array may be either primitives (booleans, numbers, Strings, and dates), or may be a map with the following structure:
  • value: the boolean, number, String, or date value of the cell
  • formatString: for dates and numbers, the Java format string used with SimpleDateFormat or DecimalFormat to control how the value is formatted
  • timeOnly: for dates, whether the date part should be ignored and only the time value is important
  • forceString: force the value to be treated as a string (i.e. prevent attempt to convert it to a date)

<static> LABKEY.Utils.convertToTable()
Sends a JSON object to the server which turns it into an TSV or CSV file and returns it to the browser to be saved or opened.
<script type="text/javascript">
 LABKEY.Utils.convertToTable(
 {
     fileName: 'output.csv',
     rows:
     [
         ['Row1Col1', 'Row1Col2'],
         ['Row2Col1', 'Row2Col2']
     ],
     delim: 'COMMA'
 });
 </script>
Parameters:
{Object} config.
The config object
{String} config.fileNamePrefix
name to suggest to the browser for saving the file. The appropriate extension (either ".txt" or ".csv", will be appended based on the delim character used (see below). Defaults to 'Export'
{String} config.delim
The separator between fields. Allowable values are 'COMMA' or 'TAB'.
{String} config.quoteChar
The character that will be used to quote each field. Allowable values are 'DOUBLE' (ie. double-quote character), 'SINLGE' (ie. single-quote character) or 'NONE' (ie. no character used). Defaults to none.
{String} config.newlineChar
The character that will be used to separate each line. Defaults to '\n'
{String} config.rows
array of rows, which are arrays with values for each cell.

<static> {Object} LABKEY.Utils.decode(data)
Decodes (parses) a JSON string to an object.
Parameters:
{String} data
The JSON string
Returns:
{Object} The resulting object

<static> LABKEY.Utils.deleteCookie(name, pageonly)
Deletes a cookie. Note that 'name' and 'pageonly' should be exactly the same as when the cookie was set.
Parameters:
{String} name
The name of the cookie to be deleted.
{Boolean} pageonly
Whether the cookie is scoped to the entire site, or just this page. Deleting a site-level cookie has no impact on page-level cookies, and deleting page-level cookies has no impact on site-level cookies, even if the cookies have the same name.

<static> LABKEY.Utils.displayAjaxErrorResponse(responseObj, exceptionObj, showExceptionClass, msgPrefix)
Shows an error dialog box to the user in response to an error from an AJAX request, including any error messages from the server.
Parameters:
{XMLHttpRequest} responseObj
The XMLHttpRequest object containing the response data.
{Error} exceptionObj Optional
A JavaScript Error object caught by the calling code.
{boolean} showExceptionClass Optional
Flag to display the java class of the exception.
{String} msgPrefix Optional
Prefix to the error message (defaults to: 'An error occurred trying to load:') The error dialog will display the Error's name and message, if available.

<static> {String} LABKEY.Utils.encode(data)
Encodes an Object to a string.
Parameters:
{Object} data
the variable to encode.
Returns:
{String} The JSON string.

<static> {String} LABKEY.Utils.encodeHtml(html)
Encodes the html passed in so that it will not be interpreted as HTML by the browser. For example, if your input string was "<p>Hello</p>" the output would be "&lt;p&gt;Hello&lt;/p&gt;". If you set an element's innerHTML property to this string, the HTML markup will be displayed as literal text rather than being interpreted as HTML.
Parameters:
{String} html
The HTML to encode
Returns:
{String} The encoded HTML

<static> LABKEY.Utils.endsWith(value, ending)
Returns true if value ends with ending
Parameters:
value
the value to examine
ending
the ending to look for

<static> LABKEY.Utils.generateUUID()
Returns a universally unique identifier, of the general form: "92329D39-6F5C-4520-ABFC-AAB64544E172" NOTE: Do not use this for DOM id's as it does not meet the requirements for DOM id specification. Based on original Math.uuid.js (v1.4) http://www.broofa.com mailto:robert@broofa.com Copyright (c) 2010 Robert Kieffer Dual licensed under the MIT and GPL licenses.

<static> LABKEY.Utils.getCallbackWrapper(fn, scope, isErrorCallback)
This is used internally by other class methods to automatically parse returned JSON and call another success function passing that parsed JSON.
Parameters:
fn
The callback function to wrap
scope
The scope for the callback function
{boolean} isErrorCallback Optional, Default: false
Set to true if the function is an error callback. If true, and you do not provide a separate callback, alert will popup showing the error message

<static> LABKEY.Utils.getCookie(name, defaultvalue)
Retrieves a cookie. Useful for retrieving non-essential state to provide a better user experience. Note that some browser settings may prevent cookies from being saved, and users can clear browser cookies at any time, so previously saved cookies should not be assumed to be available.
Parameters:
{String} name
The name of the cookie to be retrieved.
{String} defaultvalue
The value to be returned if no cookie with the specified name is found on the client.

<static> LABKEY.Utils.getDateAltFormats()
Returns date formats for use in an Ext.form.DateField. Useful when using a DateField in an Ext object, it contains a very large set of date formats, which helps make a DateField more robust. For example, a user would be allowed to enter dates like 6/1/2011, 06/01/2011, 6/1/11, etc.

<static> LABKEY.Utils.getDateTimeFormatWithMS()
Returns date format with timestamp including milliseconds. Useful for parsing the date in "yyyy-MM-dd HH:mm:ss.SSS" format as returned by DateUtil.getJsonDateTimeFormatString(). ex. Ext4.Date.parse("2019-02-15 17:15:10.123", 'Y-m-d H:i:s.u')

<static> {String} LABKEY.Utils.getFileIconUrl(fileName)
Returns a URL to the appropriate file icon image based on the specified file name. Note that file name can be a full path or just the file name and extension. If the file name does not include an extension, the URL for a generic image will be returned
Parameters:
{String} fileName
The file name.
Returns:
{String} The URL suitable for use in the src attribute of an img element.

<static> LABKEY.Utils.getOnFailure(config)
Standard documented name for error callback arguments is "failure" but various other names have been employed in past. This function provides reverse compatibility by picking the failure callback argument out of a config object be it named failure, failureCallback or errorCallback.
Parameters:
config

<static> LABKEY.Utils.getOnSuccess(config)
Standard documented name for success callback arguments is "success" but various names have been employed in past. This function provides reverse compatibility by picking the success callback argument out of a config object, be it named success or successCallback.
Parameters:
config

<static> {String} LABKEY.Utils.getSessionID()
Retrieves the current LabKey Server session ID. Note that this may only be made available when the session ID cookie is marked as httpOnly = false.
Returns:
{String} sessionid The current session id. Defaults to ''.
See:

<static> {*} LABKEY.Utils.id(prefix)
Will generate a unique id. If you provide a prefix, consider making it DOM safe so it can be used as an element id.
Parameters:
{string} prefix Optional, Default: lk-gen
- Optional prefix to start the identifier.
Returns:
{*}

<static> LABKEY.Utils.isBoolean(value)
Tests whether the passed value can be used as boolean, using a loose definition. Acceptable values for true are: 'true', 'yes', 1, 'on' or 't'. Acceptable values for false are: 'false', 'no', 0, 'off' or 'f'. Values are case-insensitive.
Parameters:
value
The value to test

<static> {Boolean} LABKEY.Utils.isEmptyObj(ob)
Returns true if the passed object is empty (ie. {}) and false if not.
Parameters:
{Object} ob
The object to test
Returns:
{Boolean} the result of the test

<static> {Boolean} LABKEY.Utils.isString(value)
Returns true if the passed value is a string.
Parameters:
{Object} value
The value to test
Returns:
{Boolean}

<static> LABKEY.Utils.merge(a, b, c)
Apply properties from b, c, ... to a. Properties of each subsequent object overwrites the previous. The first object is modified. Use merge({}, o) to create a deep copy of o.
Parameters:
a
b
c

<static> LABKEY.Utils.mergeIf(a, b, c)
Apply properties from b, c, ... to a. Properties are not overwritten. The first object is modified.
Parameters:
a
b
c

<static> LABKEY.Utils.modal(title, msg, fn, args)
Display a modal dialog.
<script type="text/javascript">

var myFN = function(arg1) {
    document.getElementById('modal-fn-body').innerHTML = "Hello " + LABKEY.Security.currentUser[arg1] + "!";
}
LABKEY.Utils.modal("Hello", null, myFN, ["displayName"]);
</script>
Parameters:
title
Title of the modal dialog.
msg
Message to be included in the dialog body. Can be null if the function generates its own content.
fn
{function} This will be called with the provided argument list {args} after the modal is shown. You can generate content in the modal via the following empty div: <div id="modal-fn-body"></div>
args
{array} Array of arguments to be applied to the function when it is called.

<static> LABKEY.Utils.onError(error)
Provides a generic error callback. This helper show a modal dialog, log the error to the console and will log the error to the audit log table. The user must have insert permissions on the selected container for this to work. By default, it will insert the error into the Shared project. A containerPath param can be passed to use a different container. The intent of this helper is to provide site admins with a mechanism to identify errors associated with client-side code. If noAuditLog=true is used, the helper will not log the error.
<script type="text/javascript">
 //basic usage
 LABKEY.Query.selectRows({
                schemaName: 'core',
                queryName: 'users',
                success: function(){},
                failure: LABKEY.Utils.onError
            });

 //custom container and turning off logging
 LABKEY.Query.selectRows({
                schemaName: 'core',
                queryName: 'users',
                success: function(){},
                failure: function(error){
                     error.containerPath = 'myContainer';
                     error.noAuditLog = true;
                     LABKEY.Utils.onError(error);
                }
            });
 </script>
Parameters:
{Object} error
The error object passed to the callback function
{String} error.containerPath Optional
Container where errors will be logged. Defaults to /shared
{Boolean} error.noAuditLog Optional
If false, the errors will not be logged in the audit table. Defaults to true

<static> LABKEY.Utils.onReady(config)
Adds new listener to be executed when all required scripts are fully loaded.
<script type="text/javascript">
 //simple usage
 LABKEY.onReady(function(){
                    //your code here.  will be executed once scripts have loaded
                });

 //
 LABKEY.Utils.onReady({
                    scope: this,
                    scripts: ['/myModule/myScript.js', 'AnotherScript.js],
                    callback: function(){
                        //your code here.  will be executed once scripts have loaded
                    });
                });
 </script>
Parameters:
{Mixed} config
Either a callback function, or an object with the following properties:
  • callback (required) A function that will be called when required scripts are loaded.
  • scope (optional) The scope to be used for the callback function. Defaults to the current scope.
  • scripts (optional) A string with a single script or an array of script names to load. This will be passed to LABKEY.requiresScript().

  • <static> LABKEY.Utils.onTrue(config)
    Iteratively calls a tester function you provide, calling another callback function once the tester function returns true. This function is useful for advanced JavaScript scenarios, such as cases where you are including common script files dynamically using the requiresScript() method, and need to wait until classes defined in those files are parsed and ready for use.
    <script>
        LABKEY.Utils.requiresScript("FileUploadField.js");
        LABKEY.Utils.requiresCSS("FileUploadField.css");
    </script>
    
    <script>
        function tester()
        {
            return undefined != Ext.form.FileUploadField;
        }
    
        function onTrue(msg)
        {
            //this alert is merely to demonstrate the successArguments config property
            alert(msg);
    
            //use the file upload field...
        }
    
        function onFailure(msg)
        {
            alert("ERROR: " + msg);
        }
    
        LABKEY.Utils.onTrue({
            testCallback: tester,
            success: onTrue,
            successArguments: ['FileUploadField is ready to use!'],
            failure: onFailure,
            maxTests: 100
        });
    </script>
    Parameters:
    {Object} config
    a configuration object with the following properties:
    {Function} config.testCallback
    A function that returns true or false. This will be called every ten milliseconds until it returns true or the maximum number of tests have been made.
    {Array} config.testArguments Optional
    A array of arguments to pass to the testCallback function
    {Function} config.success
    The function to call when the testCallback returns true.
    {Array} config.successArguments Optional
    A array of arguments to pass to the successCallback function
    {Object} config.failure Optional
    A function to call when the testCallback throws an exception, or when the maximum number of tests have been made.
    {Array} config.errorArguments Optional
    A array of arguments to pass to the errorCallback function
    {Object} config.scope Optional
    A scope to use when calling any of the callback methods (defaults to this)
    {int} config.maxTests Optional
    Maximum number of tests before the errorCallback is called (defaults to 1000).

    <static> {String} LABKEY.Utils.padString(input, length, padChar)
    Will pad the input string with zeros to the desired length.
    Parameters:
    {Number/String} input
    The input string / number
    {Integer} length
    The desired length
    {String} padChar
    The character to use for padding.
    Returns:
    {String} The padded string

    <static> LABKEY.Utils.postToAction(href)
    POSTs to the given href, including CSRF token. Taken from PageFlowUtil.postOnClickJavascript .
    Parameters:
    href
    containing action and parameters to be POSTed

    <static> LABKEY.Utils.requiresCSS(filePath)
    Includes a Cascading Style Sheet (CSS) file into the page. If the file was already included by some other code, this function will simply ignore the call. This may be used to include CSS files defined in your module's web/ directory.
    Parameters:
    {String} filePath
    The path to the script file to include. This path should be relative to the web application root. So for example, if you wanted to include a file in your module's web/mymodule/styles/ directory, the path would be "mymodule/styles/mystyles.css"

    <static> LABKEY.Utils.requiresScript(file, callback, scope, inOrder)
    Loads JavaScript file(s) from the server.
             <script type="text/javascript">
             LABKEY.requiresScript("myModule/myScript.js", true, function() {
                        // your script is loaded
                    });
             </script>
    Parameters:
    {(string|string[])} file
    - A file or Array of files to load.
    {Function} callback Optional
    - Callback for when all dependencies are loaded.
    {Object} scope Optional
    - Scope of callback.
    {boolean} inOrder Optional, Default: false
    - True to load the scripts in the order they are passed in. Default is false.

    <static> LABKEY.Utils.resizeToViewport()
    This method has been migrated to specific instances for both Ext 3.4.1 and Ext 4.2.1. For Ext 3.4.1 see LABKEY.ext.Utils.resizeToViewport For Ext 4.2.1 see LABKEY.ext4.Util.resizeToViewport

    <static> {Number} LABKEY.Utils.roundNumber(input, dec)
    Rounds the passed number to the specified number of decimals
    Parameters:
    {Number} input
    The number to round
    {Number} dec
    The number of decimal places to use
    Returns:
    {Number} The rounded number

    <static> LABKEY.Utils.setCookie(name, value, pageonly, days)
    Sets a client-side cookie. Useful for saving non-essential state to provide a better user experience. Note that some browser settings may prevent cookies from being saved, and users can clear browser cookies at any time, so cookies are not a substitute for database persistence.
    Parameters:
    {String} name
    The name of the cookie to be saved.
    {String} value
    The value of the cookie to be saved.
    {Boolean} pageonly
    Whether this cookie should be scoped to the entire site, or just this page. Page scoping considers the entire URL without parameters; all URL contents after the '?' are ignored.
    {int} days
    The number of days the cookie should be saved on the client.

    <static> LABKEY.Utils.setWebpartTitle(title, webPartId)
    Sets the title of the webpart on the page. This change is not sticky, so it will be reverted on refresh.
    Parameters:
    {string} title
    The title string
    {integer} webPartId
    The ID of the webpart

    <static> LABKEY.Utils.textLink(config)
    Returns a string containing a well-formed html anchor that will apply theme specific styling. The configuration takes any property value pair and places them on the anchor.
    Parameters:
    {Object} config
    a configuration object that models html anchor properties:
    {String} config.href
    (required if config.onClick not specified) the reference the anchor will use.
    {String} config.onClick
    (required if config.href not specified) script called when the onClick event is fired by the anchor.
    {String} config.text
    text that is rendered inside the anchor element.

    Documentation generated by JsDoc Toolkit 2.3.2 on Thu Mar 14 2019 22:39:27 GMT-0000 (UTC)