< All Topics

Form script helper functions

Understanding Form Script in Axonator

A form script is a javascript associated with the form to make it more powerful. With form scripts in Axonator, you can make your forms interactive and smart. These scripts allow your forms to automatically fill in details, perform calculations, and ensure the data entered is accurate. This means you have full control on how your form works, your users spend less time on manual tasks, and have a smoother, more efficient experience.

To work with form scripts, you need to first understand the following concepts:

  1. Function: A function is a code snippet which can be called on a field’s value change or from another function in your script. You can define a function this way:
    1. function function_name(ws) { //Enter you logic here }
  2. Form script function triggers:
    1. On value change: this is the property in every field of your form. When you specify your form script function name in this property, that function is called when the value of the selected field is changed. The widget property must be filled with the function name (just the name, no brackets).
    2. function on_load(ws): Using on_load can help you perform any operations when the form is opened in the mobile app.
    3. function on_submit(ws): Using on_submit, you can perform any operations after the submit button is clicked, but before the form gets submitted.

 

Alert popup functions

 

// Display an alert message in the workspace.
// Possible type values: Error/Warning/Info
function showAlert(ws, title, message, type)
{
    type = type || "Error";
    var alertMessage = {
        "t": title,
        "m": message,
        "tp": type
    };
    ws.showAlert(JSON.stringify(alertMessage));
}
// Display an error alert message in the workspace
function showErrorAlert(ws, title, message)
{
    var alertMessage = {
        "t": title,
        "m": message,
        "tp": "Error"
    };
    ws.showAlert(JSON.stringify(alertMessage));
}
// Display an warning alert message in the workspace
function showWarningAlert(ws, title, message)
{
    var alertMessage = {
        "t": title,
        "m": message,
        "tp": "Warning"
    };
    ws.showAlert(JSON.stringify(alertMessage));
}
// Display an info alert message in the workspace
function showInfoAlert(ws, title, message)
{
    var alertMessage = {
        "t": title,
        "m": message,
        "tp": "Info"
    };
    ws.showAlert(JSON.stringify(alertMessage));
}

Date field functions

 

// Set the current date and time to a specific field
function setCurrentDateTime(ws, fieldId)
{
    var currentDateTime = new Date().toISOString().slice(0, 16).replace('T', ' ');
    ws.setWidgetValue(fieldId, currentDateTime);
}
// Set today's date to a specific field
function setTodaysDate(ws,dateFieldId)
{
    var date = new Date();
    var datestring = date.getFullYear() + '-' + JSON.stringify(date.getMonth() + 1) + '-' + date.getDate();
    ws.setWidgetValue(dateFieldId,datestring);
    ws.reloadUICell(dateFieldId);
}
function compareEnteredDateWithToday(ws, dateFieldId)
{
    var enteredDateStr = ws.getWidgetValue(dateFieldId);

    // Determine if the value includes time (datetime) or not (date)
    var isDateTime = enteredDateStr.length > 10;

    var currentDateTime = new Date();

    // Format the current date or datetime string
    var currentDateStr = isDateTime
        ? currentDateTime.toISOString().slice(0, 16).replace('T', ' ')
        : currentDateTime.toISOString().slice(0, 10);

    if (enteredDateStr > currentDateStr) {
        showAlert(ws, "Date Check", "Entered Date/Time is later than Today's Date/Time", "Error");
    } else {
        showAlert(ws, "Date Check", "Entered Date/Time is earlier or equal to Today's Date/Time", "Info");
    }
}
// Compare two date fields and display the result
function compareTwoDates(ws, firstDateField, secondDateField)
{
    if (firstDateField > secondDateField) {
        showAlert(ws, "Date Comparison", "First Date is later than Second Date", "Info");
    } else {
        showAlert(ws, "Date Comparison", "First Date is earlier or equal to Second Date", "Info");
    }
}
// Compare an entered date (in 'YYYY-MM-DD' format) with a hardcoded date in same format
function compareWithHardcodedDate(ws, enteredDateStr)
{
    if (hardcodedDateStr > enteredDateStr) {
        showAlert(ws, "Date Comparison", "Hardcoded Date is later than Entered Date", "Info");
    } else {
        showAlert(ws, "Date Comparison", "Hardcoded Date is earlier or equal to Entered Date", "Info");
    }
}

Reference Choice field functions

 

// Get record ID (foid) of the selected record in a reference choice list
function getReferenceRecordId(ws,referenceFieldId)
{
    var ref_field_data = JSON.parse(ws.getWidgetValue(referenceFieldId));
    return ref_field_data[0]?.foid || '';
}
// Get record title (fot) of the selected record in a reference choice list
function getReferenceRecordTitle(ws,referenceFieldId)
{
    var ref_field_data = JSON.parse(ws.getWidgetValue(referenceFieldId));
    return ref_field_data[0]?.fot || '';
}
// Get record subtitle (fost) of the selected record in a reference choice list
function getReferenceRecordSubtitle(ws,referenceFieldId)
{
    var ref_field_data = JSON.parse(ws.getWidgetValue(referenceFieldId));
    return ref_field_data[0]?.fost || '';
}
// Set a field's value with title information from another reference choice field in the same form
function setValueFromReferenceTitle(ws, sourceFieldId, targetFieldId)
{
    var fieldData = JSON.parse(ws.getWidgetValue(sourceFieldId));
    var title = fieldData[0]?.fot || '';
    ws.setWidgetValue(targetFieldId, title);
    ws.reloadUICell(targetFieldId);
}
// Set a field's value with subtitle information from another reference choice field in the same form
function setValueFromReferenceSubtitle(ws, sourceFieldId, targetFieldId)
{
    var fieldData = JSON.parse(ws.getWidgetValue(sourceFieldId));
    var subtitle = fieldData[0]?.fost || '';
    ws.setWidgetValue(targetFieldId, subtitle);
    ws.reloadUICell(targetFieldId);
}
// Set field value in the current form using data from selected reference record
function setValueFromReferenceRecord(ws, srcRefFieldId, refRecordFieldId, targetFieldId)
{
    var ref_field_data = JSON.parse(ws.getWidgetValue(srcRefFieldId));
    var ref_record_id = ref_field_data[0]?.foid || '';
    var sourceValue = ws.getFormObjectWidgetValue(ref_record_id, refRecordFieldId);
    ws.setWidgetValue(targetFieldId, sourceValue);
    ws.reloadUICell(targetFieldId);
}
// Set field value in the current form using data from another form
function setValueFromOtherRecord(ws, sourceFormobjectId, sourceFieldId, targetFieldId)
{
    var sourceValue = ws.getFormObjectWidgetValue(sourceFormobjectId, sourceFieldId);
    ws.setWidgetValue(targetFieldId, sourceValue);
    ws.reloadUICell(targetFieldId);
}

Field visibility functions

 

// Toggle the visibility of a field between true and false
function toggleFieldVisibility(ws, FieldId)
{
    var isVisible = ws.isWidgetVisible(FieldId);
    ws.setWidgetValue(FieldId, !isVisible);
    ws.reloadUICell(FieldId);
}
// Copy the visibility of a field based on another field's visibility
function copyFieldVisibility(ws, sourceFieldId, targetFieldId)
{
    var source_field_visibility = ws.isWidgetVisible(sourceFieldId);
    ws.setWidgetValue(targetFieldId, );
    ws.reloadUICell(FieldId);
}

Form operations functions

 

// Function that gets executed when the form is opened
function on_load(ws)
{
  // Enter your logic here

}
// Function that gets executed on submit, before the form is submitted
function on_submit(ws)
{
  // Enter your logic here

}
// Helper function to close the form with a custom warning message
function closeFormWithWarning(ws, alertTitle, alertDescription)
{
    var warningMessage = JSON.stringify({
        "t": alertTitle,
        "Close": alertDescription
    });
    ws.closeForm(warningMessage);
}

Computation functions

 

// Calculate occurrences of the specified value in the list of the choice fields in the form
// choiceFieldIds is the list of choice field identifiers in the form
// values is the list of values, out of which if any is found in the field, the occurrence is considered
// scoreFieldId is the optional parameter to provide the field identifier to set the number of occurrences (score) in that field
// The function returns the number of occurrences

function calculateOcurrences(ws, choiceFieldIds, values, scoreFieldId)
{
    var score = 0;
    var choiceFieldIds = choiceFieldIds ? choiceFieldIds : ["Choice_List_1","Choice_List_2"];
    var values = values ? values : ["Yes"];
    var scoreFieldId = scoreFieldId ? scoreFieldId : "";
    for (var i = 0; i< choiceFieldIds.length;i++) {
        if(ws.getWidgetValue(choiceFieldIds[i]) != ""){
            var val = JSON.parse(ws.getWidgetValue(choiceFieldIds[i])); 
            if (val && val.length > 0 && values.some(posVal => val[0].includes(posVal))) {
                score += 1;
            }
        }
    }
    if(scoreFieldId != ""){
        // Set the calculated score in the appropriate textbox
        ws.setWidgetValue(scoreFieldId, score.toString());
        ws.reloadUICell(scoreFieldId);
    }
  return score;
}
function calculatePercentageOcurrences(ws, TargetFieldId) {
  var widgetKeys = ["Choice_List_1", "Choice_List_2"];

  // Pass the widgetKeys to calculateOccurrences
  var yesOccourrence=calculateOcurrences(ws, widgetKeys, ["Yes"], "Total_YES");
  var noOccourrence=calculateOcurrences(ws, widgetKeys, ["No"], "Total_NO");
  var totalOccourrence = yesOccourrence + noOccourrence;

  if (totalOccourrences > 0) {
    var percentageYes = (yesOccourrence / totalOccourrences) * 100;
    // Set the percentage in the appropriate widget
    ws.setWidgetValue(TargetFieldId, percentageYes.toFixed(2));
    ws.reloadUICell(TargetFieldId);
  } else {
    // Handle the case where there are no Yes or No responses
    ws.setWidgetValue(TargetFieldId, "0.00");
    ws.reloadUICell(TargetFieldId);
  }
}

 Form Manipulation functions

 

// Update the prompt (label) of a field
function updateFieldPrompt(ws, fieldId, prompt)
{
    ws.setWidgetPrompt(fieldId, prompt);
    ws.reloadUICell(fieldId);
}
function updateChoiceField(ws, choiceFieldId, choices)
{
    setWidgetChoices(choiceFieldId, choices);
    ws.reloadUICell(choiceFieldId);
}

//example to set choices of a fixed choice list field
var choiceFieldId = "Choice_List_1";
var choices ="Choice1\nChoice2\nChoice3";
updateChoiceField(ws, choiceFieldId, choices);

Field value functions

 

// Get value of a field
function getValue(ws, fieldId)
{
    return ws.getWidgetValue(fieldId);
}
// Set value of a field
function setValue(ws, fieldId, value)
{
    ws.setWidgetValue(fieldId, value);
    ws.reloadUICell(fieldId);
}
// Set value of a fixed choice list field as the string provided as value
function setFixedChoiceValue(ws,choiceFieldId,value)
{
    ws.setWidgetValue(choiceFieldId,'[\"'+value+'\"]');
    ws.reloadUICell(choiceFieldId);
}
// Set value of a reference choice list field
function setReferenceChoiceValue(ws,referenceChoiceFieldId,foid,title,subtitle)
{
    ws.setWidgetValue(referenceChoiceFieldId,'[{"foid":"'+ foid +'","fot":"'+ title +'","fost":"'+ subtitle +'"}]');
    ws.reloadUICell(referenceChoiceFieldId);
}
// Compare two number/decimal fields. Possible type values: "number"/"decimal". Default: number
// Shows result on alert
function compareNumbers(ws, firstNumberFieldId, secondNumberFieldId, type)
{
    if(type == "decimal")
    {
        var firstVal = parseFloat(val(ws,firstNumberFieldId));
        var secondVal = parseFloat(val(ws,secondNumberFieldId));
    }
    else
    {
        var firstVal = parseInt(val(ws,firstNumberFieldId));
        var secondVal = parseInt(val(ws,secondNumberFieldId));
    }
    if(!isNaN(firstVal) && !isNaN(secondVal) && firstVal<secondVal) { showAlert(ws, "Numbers Comparison", "First number is less than the second number.", "Info"); } else if(!isNaN(firstVal) && !isNaN(secondVal) && firstVal>secondVal)
    {
        showAlert(ws, "Numbers Comparison", "First number is greater than the second number.", "Info");
    }
    else if(isNaN(firstVal))
    {
        showAlert(ws, "Numbers Comparison", "First number is not a valid number.", "Info");
    }
    else if(isNaN(secondVal))
    {
        showAlert(ws, "Numbers Comparison", "Second number is not a valid number.", "Info");
    }
    else
    {
        showAlert(ws, "Numbers Comparison", "Something went wrong.", "Info");
    }
    return "";
}
// Compare two number/decimal fields. Possible type values: number/decimal. Default: number
// Returns true/false
function isFirstNumberLess(ws, firstNumberFieldId, secondNumberFieldId, type)
{
    if(type == "decimal")
    {
        var firstVal = parseFloat(val(ws,firstNumberFieldId));
        var secondVal = parseFloat(val(ws,secondNumberFieldId));
    }
    else
    {
        var firstVal = parseInt(val(ws,firstNumberFieldId));
        var secondVal = parseInt(val(ws,secondNumberFieldId));
    }
    if(!isNaN(firstVal) && !isNaN(secondVal) && firstVal<secondVal) { return true; } else if(!isNaN(firstVal) && !isNaN(secondVal) && firstVal>secondVal)
    {
        return false;
    }
    else if(isNaN(firstVal))
    {
        return false;
    }
    else if(isNaN(secondVal))
    {
        return false;
    }
    else
    {
        showAlert(ws, "Numbers Comparison", "Something went wrong.", "Info");
    }
    return "";
}
// Calculates and sets the sum of a number/decimal field in all child records in the form. Possible type values: number/decimal. Default: number
function setChildFieldSum(ws, childFieldId, numberFieldIdInChild, targetFieldId, type)
{
    var children = ws.getWidgetValue(childFieldId);
    if(children!=''){
        children = JSON.parse(children);
        var total = 0;

        for(var i=0;i<children.length;i++){
            var child = children[i];
            if(type=="decimal")
            {
                var numberValue = parseFloat(ws.getFormObjectWidgetValue(child["foid"],numberFieldIdInChild));
            }
            else
            {
                var numberValue = parseInt(ws.getFormObjectWidgetValue(child["foid"],numberFieldIdInChild));
            }
            if (numberValue){
                total += numberValue;              
            }
    
        }
        ws.setWidgetValue(targetFieldId, total);
        ws.reloadUICell(targetFieldId);
    }
}

 Conversion functions

 

function convertToNumber(ws, valIdentifier) {
    return parseInt(ws.getWidgetValue(valIdentifier), 10);
}
function convertToDecimal(ws, valIdentifier) {
    return parseFloat(ws.getWidgetValue(valIdentifier));
}
function convertToDate(ws, valIdentifier) {
    return new Date(ws.getWidgetValue(valIdentifier));
}

Calculation functions

 

// Possible values for operation: add/minus/multiply/divide. Default: add
// Possible values for valueType: number/decimal. Default: number
function calculate(ws, firstFieldId, secondFieldId, operation, valueType) {

    var firstValue = valueType === 'decimal'
        ? convertToDecimal(ws, firstFieldId)
        : convertToNumber(ws, firstFieldId);

    var secondValue = valueType === 'decimal'
        ? convertToDecimal(ws, secondFieldId)
        : convertToNumber(ws, secondFieldId);

    var result;

    switch(operation) {
        case 'minus':
            result = firstValue - secondValue;
            break;
        case 'multiply':
            result = firstValue * secondValue;
            break;
        case 'divide':
            result = secondValue !== 0 ? firstValue / secondValue : 'Infinity';
            break;
        case 'add':
        default:
            result = firstValue + secondValue;
            break;
    }

    return result;
}
// Possible roundingMode values: up/down/off. With default as ‘off’
function roundToDecimal(ws, decimalFieldId, decimalPlaces, roundingMode) {
    var valueStr = ws.getWidgetValue(decimalFieldId);

    var value = parseFloat(valueStr);

    switch (roundingMode) {
        case 'up':
            roundedValue = Math.ceil(value * Math.pow(10, decimalPlaces)) / Math.pow(10, decimalPlaces);
            break;
        case 'down':
            roundedValue = Math.floor(value * Math.pow(10, decimalPlaces)) / Math.pow(10, decimalPlaces);
            break;
        case 'off':
        default:
            roundedValue = value.toFixed(decimalPlaces);
            break;
    }

    ws.setWidgetValue(decimalFieldId,roundedValue);

    ws.reloadUICell(decimalFieldId);
}

Miscellaneous functions

 

function existsInChoice(ws, choiceFieldId, value) {
    // Get the value from the choice field
    var choice = ws.getWidgetValue(choiceFieldId);

    // Check if the specified value is included in the choice string
    return choice.includes(value);
}
function makeApiCall(ws, apiUrl, requestParams, isLoading, onSuccess, onError) {
    // Indicate that the API call is in progress
    in_on_load = _load;

    // Make the API call
    ws.callAPI(
        apiUrl,                        // The API endpoint to call
        JSON.stringify(requestParams), // The parameters for the API request, converted to a JSON string
        JSON.stringify([]),            // Headers (empty in this case)
        onSuccess,                     // Function to call if the API request succeeds
        onError                        // Function to call if the API request fails
    );
}

//example for makeApiCall

// Example callback functions
function onUserInfoSuccess(response) {
    console.log('API call succeeded:', response);
}

function onUserInfoError(error) {
    console.error('API call failed:', error);
}

// API endpoint URL
var apiUrl = "anyExample.com/get-user-info";
var requestParams = {
    "user_id": "12345"
};
var isLoading = true;
makeApiCall(ws, apiUrl, requestParams, isLoading, "onUserInfoSuccess", "onUserInfoError");

Table of Contents