JavaScript APIs

Scope

This document highlights the helper apis used in Smartflow form scripts with examples.

Helper apis (Form scripts)

Terminologies used

Control identifier

A control identifier is the unique identifier assigned by the system to each form control in a form template. It is commonly referred to as control id.

The control id is always in lowercase and starts with the prefix control_. For example, control_tanknumber, control_tolerancelevel etc.

The naming convention followed is control_<internalfieldname>, where the internalfieldname is the internal name assigned by the system to the form control in the builder.

A control identifier is case sensitive. When used, it should always be mentioned in all lowercase.

How to obtain the control id of a form control?

You can obtain the control id of a form control in the form builder. 

  1. Go to User settings and enable Developer options.

  2. Open the form template in the builder.

  3. Hover over the form control and click on Properties icon to open the properties window of the control.

  4. Click on the Information tab in the properties window.

  5. The text mentioned under Field id is the control identifier of the control.

Index

The index of a form control refers to the row number of the control in a multi-row structure. This property is relevant only if the form control being referred to resides inside a group control.

The index is a zero-based index. A zero-based index starts with the number 0. i.e. the index of the first item is 0 and the index of each subsequent item increases by one.

Callback function

A callback function is a code block that is executed after the current function completes. It is widely used concept in JavaScript for asynchronous programming.

The result of the current function is passed to the callback function, allowing the developer to perform further operation using the result.

For example, the function below binds a change event to a selectbox control. When user selects an item in the selectbox, the value of the selected item and the index of the control (if the control resides in a group) is passed to the callback function.

sfRegisterFieldCallback('control_productname','change',function(value,index) { // do something });

Category

Function Name

Description

Category

Function Name

Description

DOM access

sfGetValue

Returns the value of a form control.

sfGetText

Returns the text shown on a form control.

DOM manipulation

sfAddGroupitems

Adds a new row in a group control.

sfClearGroup

Removes all existing rows from a group control.

sfDisableForm

Makes the current form readonly.

sfField

Returns the reference to a form control.

sfHideGroupButtons

Hides action buttons from a group control.

sfLoadGroup

Loads a lazy loaded group control.

sfRegisterFieldCallback

Binds a function to an event on a form control.

sfRegisterGroupCallback

Binds a function to an event on a group control.

sfRemoveGroupItems

Removes a row at the mentioned index from a group control.

sfSaveForm

Saves the current form.

sfSetValue

Sets the provided value to a form control.

sfSetDefaultValue

Sets the provided value to a form control (only if the field is empty).

sfShowFormStatusPopup

Renders the standard form status selection popup.

Context variables

sfGetCurrentDomain

Returns the name of the domain that the user is currently logged in to.

sfGetCurrentUser

Returns the properties of the user who is currently logged in.

sfGetDocumentMode

Returns the mode in which the digital form is open.

sfGetFormStatus

Returns the form status of the current form.

sfGetLocale

Returns the current locale code in use.

sfGetPlatform

Returns the name of the platform in which the app is currently running.

sfSetFormStatus

Sets the status of the current form.

sfSetLocale

Sets the current locale in use.

Functions

sfContains

Checks whether the search value is present in the provided collection.

System actions

sfAddSystemTriggerAction

Requests the server for a system action like send an email or create a report.

sfCreateDocument

Requests the server to generate a report of a form.

sfSendEmail

Requests the server to send an email.

sfSetValidationBool(value)

Parameter: value

  • value(bool): either true or false 

Returns: NONE

Description: Sets the ignoreValidation variable to either true or false. If set to true the form ignores validation when saving the form.

sfGetCurrentFormId()

Parameter: None

Returns(string): The id of the opened form

sfGetCurrentViewId()

Parameters: None

Returns(string):The id of the view page that is currently opened.

sfSetFormVar(keyName, value, permanent)

Parameter:keyName, value, permanent

  • keyName(string): the key name where we want to set the value to.

  • value(any): the value variable that is passed in the keyName

  • permanent(bool and optional): If true is passed the value persists even when form is navigated from form detail page to view page.

Description: Sets the value of form variable with a key

sfGetFormVar(key, permanent)

Parameter:key, permanent

  • key(string): the name of the variable where value is stored

  • permanent(bool): If true, the value is retrieved from PermanentFormVar key in local storage else from navigationParam

Return(string): the value that is stored in the variable

sfViewSetFilterDefaultValue(fieldName, value)

Parameter: fieldName, value

  • fieldName(string): The field name of the control.

  • value(string): the default value to be set in the control

Description: sets the default value in the control in view filter

sfOpenForm(jsonParams, addToNavigationStack, maintainPosition)

Parameter: jsonParams, addToNavigationStack, maintainPosition

  • jsonParams(json): The json object with form information:FormId, TemplateName, ReferenceFormId, LinkObject. Either FormId or TemplateName must be passed in the object.

    • FormId(string): GUID of the form

    • TemplateName(string): Name of form template

    • ReferenceFormId(string): The form id whose data will be loaded.

    • LinkObject(string): The object where we want to maintain the cursor position

  • addToNavigationStack(bool): navigates back to the same form if value is set true 

  • maintainPosition(bool): maintains the same cursor position in the display when navigating back to the same form

Description: Opens the form whose information is sent in the json object.

 

var jsonParams = { 'FormId' : '950B2AC6-0D68-458A-9850-91422AEBEF31', 'TemplateName' : 'Automation Template', 'LinkObject' : sfField('control_button') }; sfOpenForm(jsonParams, true, true);

 

It opens the form whose form id is passed in the FormId parameter and the template name is Automation Template. When the back button is clicked it navigates back to the previous form and maintains its cursor position where it was previously before opening the form.

sfValidateForm(ignoreMandatoryFields, callBack)

Parameter:ignoreMandatoryFields, callBack

  • ignoreMandatoryFields(bool): validation is skipped for required fields when value is true else it is not skipped

  • callBack(function): Callback function which includes work to be done after validation is done.

Returns(object): An object with keys type and value

If validation is successful then object returned will be: 

{ "type": "empty", "value": "" }

If validation fails:

{ "type": "error", "value": "error-message" }

Description: Validates the form

 

sfValidateForm(false, function(result){ if(result.value == ""){ // Validation successful. Do something. } else { // Validation failed. Do something. } });

 

Tries to validate the form and if validation fails of mandatoryField fails for control_text(suppose) the object returned will be { "type": "error", "value": "Text is required." }

sfRedirect(param)

Parameter:param(not used in the function)

Description:  cancels the form and navigates to the previous page. If the form has autosave enabled and isn’t disabled:

  1. If save callback is overridden then it calls the save callback function.

  2. Else, it validates the form and saves it if validation is successful, otherwise, it gives validation error message

sfInsert(source, dataObject, callback)

Parameters: source, dataObject, callback

  • source(string): The entity to be inserted that is Form or Dataset

  • dataObject(object): The data object that is to be inserted

  • callback(function): The callback function that will be called after insert

Description: Inserts either form or dataset items

 

 

sfUpdate(source, dataObject, callback)

Parameters: source, dataObject, callback

  • source(string): The entity to be inserted that is Form or Dataset

  • dataObject(object): The data object that is to be inserted

  • callback(function): The callback function that will be called after insert

Description: Inserts either form or dataset items

Example:

To update forms:

 

To update datasets:

 

Example:

For Form:

var dataObject = 

[{

"FormId": “”,

"TemplateId": "E20CCC5B-BFB6-45F6-8773-9DB624ED7ADA",

"TemplateName": "Test Form",

"AssignedUserId": sfGetCurrentUserId(),

"ModifiedUserId": sfGetCurrentUserId(),

"FormStatusId": "B62A2792-80B8-411B-9623-9B5F43920BD4",

"Data": {

'Main': {

'Address': 'XYZ,North Carolina',

'Gender': {

'@DisplayValue': 'Male',

'@Value': 'man',

'DatasetItemId': '8CCEBBAC-A819-4BC9-81EA-B797BC65F654',

'Code': 'man',

'Value': 'Male'

},

'FullName': 'ABC Modified',

'DateOfBirth': '2020-10-10',

'Laptop': 'Dell',

}

}

}]

sfUpdate(“Form”,dataObject,function(){

...

});



For Dataset:

var dataObject = [{

"DatasetId": "f588e3d4-a9fb-4f3e-8047-fe8e0c334187",

"Data":

[{

    "Code": "1",

    "InspectionId": "Test Id Updated 123",

    "GeneralRemark": "Test remark",

    "Date": "Date"

}]

}];

 

sfUpdate(“Dataset”,dataObject,function(){

...

});

sfDelete(source, filters, callback)

Parameters: source, filters, callback

  • source(string): The entity to be inserted that is Form or Dataset

  • filters(object): The data object that is to be inserted

  • callback(function): The callback function that will be called after insert

Description: Deletes either form or dataset items

sfOpenAttachment(fileName)

Note: Not working in the browser at the moment as 0 is passed as formId. 

Parameters: fileName

  • fileName(string): the name of the form file that is to be opened

Description: Opens form attachment in the proper file viewer.

sfOpenResource(fileName, callback)

Parameters: fileName,callback

  • fileName(string): name of the resource or the filename of the resource. Only documents, video, images and icons can be opened

  • callback(function): the callback function 

Description: Opens the file that is in the Resource folder.

sfAddAttachment(fileName)

Parameters: fileName

  • fileName(string): the name of the file

Description: Adds the attachment to the current form.

sfInvokeRedirect()

Description: Navigates to the either main page or view page from the form detail. 

sfOpenDownload(fileName)

Parameters: fileName

  • fileName(string): the name of the file that is in the Download folder of the device.

Description: Opens the file with the name fileName that is in the download folder if it is found.

sfDownload(fileUrl, name)

Parameter: fileUrl, name

  • fileUrl(string): the url where the file is located. It contains the whole path other than the webServiceUrl for example: /TempDownload/ce2eebfc-5e9b-44ce-896e-4a52ba38723d_20170511_074124/Test_AND_OR_88admin_11052017_74019.pdf

  • name(string): name of the file that it will be saved as after download

Description: Downloads the file at the given url

sfShowLoading(translationCode, locale)

Note:Not working in r7

Parameter: translationCode, locale

  • translationCode(string): the translation code of of the message to be shown while loading spinner is shown

  • locale(string): the language that the translation is needed for i.e EN, NL, FR, IT, DE, ES, PL

Description: Shows the loading icon.

sfHideLoading() 

Description: Hides the loading icon.

sfGetTranslation(translationCode, locale, defaultValue)

Parameters: translationCode, locale , defaultValue

  • translationCode(string): the translation code 

  • locale(string): the language that the translation is needed for i.e EN, NL, FR, IT, DE, ES, PL

  • defaultValue(string): the default translation to be shown if translation code is not found.

Returns: The translation of the translation code passed in the parameter. The default value of locale will be the language the user has logged into. If translation code isn’t doesn’t match to the translations available default value is returned.

List of changes planned in 8.2

Function usage

Deprecation plan

Proposed alternative in 8.2

Function usage

Deprecation plan

Proposed alternative in 8.2

sfGetCurrentUser(“Roles”)

Will return a comma separated list of roles that the currently logged in user has (instead of a json string)

 

sfGetCurrentUser(“UserGroups”)

To be deprecated

sfGetCurrentUser(“UserGroup”)

sfCheckUserHasRole

Not to be supported further but may continue to work for near future.

sfContains(sfGetCurrentUser("Roles"),"<RoleToCheck>");

sfChangeLanguage

Not to be supported further but may continue to work for near future.

sfSetLocale(“<LanguageCode>”)

sfGetDocumentMode()

Will return “web” in browser (instead of “mobile”)

 

sfSendEmail

FORM_FILES_PDF and FORM_DOCUMENT_WITH_CHILDREN to be deprecated as attachmentTypes

FORM_DOCUMENT, FORM_FILES can be used instead of FORM_FILES_PDF

sfCreateDocument

To be deprecated

sfAddSystemTriggerAction

sfGetCurrentUserId

Not to be supported further but may continue to work for near future.

sfGetCurrentUser(“Id”)

sfSetCurrentUser

To be deprecated as the changes are not saved on the server.