Contents: [hide]
  1. JavaScript Functions
    1. Overview
    2. Accessing DynaForm Objects
      1. getField()
      2. getRow()
      3. getRowById()
      4. getControlsInTheRow()
      5. var_dump()
      6. getElementByName()
      7. getElementsByClassNameCrossBrowser()
    3. Accessing Field Values
      1. getValue()
      2. getValueById()
      3. changeValue()
      4. removeValue()
      5. unselectOptions()
    4. Hiding and Showing Objects
      1. visible()
      2. visibleById()
      3. hidden()
      4. hiddenById()
      5. showHideElement()
      6. hideRow()
      7. hideRowById()
      8. showRow()
      9. showRowById()
      10. hideRowById()
      11. showRowById()
      12. contractSubtitle()
      13. expandSubtitle()
      14. contractExpandSubtitle()
    5. Saving DynaForms
      1. submitForm()
      2. saveForm()
      3. saveAndRefreshForm()
      4. saveAndRedirectForm()
    6. Requiring Fields
      1. removeRequiredById()
      2. enableRequiredById()
      3. form.verifyRequiredFields()
      4. validateForm()
    7. Disabling and Enabling Fields
      1. disable()
      2. disableById()
      3. enable()
      4. enableById()
    8. Field Focus
      1. setFocus()
      2. setFocusById()
      3. dynaformSetFocus()
    9. Read-Only
      1. toReadOnly()
      2. toReadOnlyById()
    10. Highlight Functions
      1. G.highLight()
      2. highlightRow()
    11. Grid Functions
      1. getGridField()
      2. getGridValueById()
      3. Number_Rows_Grid()
      4. getObject()
      5. grid.getElementByName()
      6. grid.getElementValueByName()
      7. grid.getFunctionResult()
      8. grid.addGridRow()
      9. grid.deleteGridRow()
    12. Data Manipulation Functions
      1. isNumber()
      2. roundNumber()
      3. creaZero()
      4. toUnmaskNumber()
      5. validateURL()
      6. removeCurrencySign()
      7. removePercentageSign()
      8. htmlentities()
      9. fix()
      10. stripslashes()
      11. addslashes()
      12. string.trim()
      13. variant.toJSONString()
    13. Date Functions
      1. compareDates()
      2. diff_date()
      3. validDate()
      4. datePicker4()
    14. Cookie Functions
      1. createCookie()
      2. readCookie()
      3. eraseCookie()
    15. Messages to the User
      1. G.alert()
      2. msgBox()
      3. commonDialog()
      4. leimnud.module.app.confirm()
      5. leimnud.module.app.alert()
      6. leimnud.module.app.prompt()
      7. leimnud.module.panel()
    16. Browser Window Information
      1. getClientWindowSize()
      2. getBrowserClient()
      3. getAbsoluteLeft()
      4. getAbsoluteTop()
    17. Miscelaneous Functions
      1. Timer()
      2. setNestedProperty()
      3. popUp()
    18. Events
      1. fireEvent()
      2. leimnud.event.add()
    19. Variables to control DynaForms
      1. dynaformOnload
    20. DynaForm special fields
      1. Process UID
      2. DynaForm UID
      3. DynaformRequiredFields

JavaScript Functions

Overview

ProcessMaker provides a number of custom JavaScript functions for working with elements of a DynaForm. These functions can be used in addition to normal JavaScript functions. For more information about how to use custom code in forms, see JavaScript in DynaForms.

These functions are defined in the files <INSTALL-DIRECTORY>/gulliver/js/form/core/form.js and <INSTALL-DIRECTORY>/gulliver/js/common/core/common.js .

Accessing DynaForm Objects

getField()

getField() returns a DynaForm field object.

object getField(string fieldName)

Parameters:

  • string fieldName: The name of a DynaForm field. Remember that field names are case sensitive.

Return value:

  • object: Returns the row object which encloses the specified field.

Note: Entire checkgroups, radiogroups, and grids cannot be referenced with this function, but their component fields can be accessed. To reference an option in a checkgroup or radiogroup, use:

getField("field-name][option-name")

Where option-name is the value for an option, not its label.

To reference a field inside a grid, use:

getField("grid-name][row-number][field-name")

Where row-number is an integer, which starts counting rows from the number 1.

Example:

Set the "BidLimit" field to a value of 2000 and the "Bidder" field to a value of "Acme Inc." when the DynaForm loads:

getField("BidLimit").value = 2000;
getField("Bidder").value = "Acme Inc.";

getRow()

getRow() returns the HTML row object which contains the specified DynaForm field. Remember that DynaForms fields are laid out inside an HTML table, with each field and its label is contained in a separate row. Use the getRow() function to reference the row which encloses a field.

object getRow(string fieldName)

Parameters:

  • string fieldName: The name of a DynaForm field.

Return value:

  • object: Returns the row object which encloses the specified field.

Example:

If the "totalCost" field is greater than 2000, then change the background color of its row to red:

originalColor = getRow("totalCost").style.backgroundColor;
function checkTotal() {
   if (getValueById("totalCost") > 2000)
      getRow("totalCost").style.backgroundColor = "red";
   else
      getRow("totalCost").style.backgroundColor = originalColor;
}
leimnud.event.add(getField('totalCost'), 'change', checkTotal);

getRowById()

getRowById() is the same as getRow().

getControlsInTheRow()

getControlsInTheRow() returns an array of the names of the fields in a specified row in a DynaForm.

  array getControlsInTheRow(object oRow)

Parameters:

  • objectoRow: A row object. Use the getRow() function to obtain the row.

Return value:

  • array: Returns a array of field names found in the specified row.

Note: If using this function before version 2.0.46, the getControlsInTheRow() function does not work correctly with dropdown boxes, textareas, links, checkgroups, radiogroups and grid fields due to this bug.

To fix the the source code, so the function can work correctly, edit the the file "gulliver/js/form/core/form.js" and change the code from:

var getControlsInTheRow = function(oRow) {
  var aAux1 = [];
  if (oRow.cells) {
    var i;
    var j;
    var sFieldName;
    for (i = 0; i < oRow.cells.length; i++) {
      var aAux2 = oRow.cells[i].getElementsByTagName('input');
      if (aAux2) {
        for (j = 0; j < aAux2.length; j++) {
          sFieldName = aAux2[j].id.replace('form[', '');
          sFieldName = sFieldName.replace(']', '');
          if (sFieldName != '') {
            aAux1.push(sFieldName);
          }
        }
      }
    }
  }
  return aAux1;
};
To:
var getControlsInTheRow = function(oRow) {
  var aAux1 = [];
  if (oRow.cells) {
    var i;
    var j;
    var sFieldName;
    for (i = 0; i < oRow.cells.length; i++) {
      var aAux2 = oRow.cells[i].getElementsByTagName('input');
 
      aAux2 = concat_collection(aAux2, oRow.cells[i].getElementsByTagName('a'));
      aAux2 = concat_collection(aAux2, oRow.cells[i].getElementsByTagName('select'));
      aAux2 = concat_collection(aAux2, oRow.cells[i].getElementsByTagName('textarea'));
      if (aAux2) {
        for (j = 0; j < aAux2.length; j++) {
          sFieldName = aAux2[j].id.replace('form[', '');
          //sFieldName = sFieldName.replace(']', '');
          sFieldName = sFieldName.replace(/]$/, '');
          if (sFieldName != '') {
            aAux1.push(sFieldName);
          }
        }
      }
    }
  }
  return aAux1;
};

Example:

When a DynaForm is loaded with a populated grid, disable all the fields in the grid rows where the Yes/No grid field "useClient" is marked as "NO":

 var dynaformOnload = function() {
   var tot = Number_Rows_Grid("clientsGrid", "useClient");
   var aFieldsInRow;
   for (var i = 1; i <= tot; i++) {
      if (getGridField("clientsGrid", i, "useClient").value == "0") {
         aFieldsInRow = getControlsInTheRow(getRow("clientsGrid][" + i + "][useClient"));
         for (var ii = 0; ii < aFieldsInRow.length; ii++)
            disableById(aFieldsInRow[ii]);
      }
   }
}

var_dump()

var_dump() creates a string listing information about DynaForm fields and other types of objects, including all its methods and member variables and their values. It is very useful for debugging a problem or discovering how to interact with an object. It currently does not work with checkboxes, radiogroups or checkgroups.

  string var_dump(object field)

Parameters:

  • object field: The field or object to display information about. Use getField() or getGridField() to reference a DynaForm field object.

Return value:

  • string: The function returns a string with all the information about the field.

Example:
Display a message box with all the properties of the "userName" textbox field:

 alert(var_dump(getField('userName')));
 

getElementByName()

getElementByName() is like the standard getElementsByName() function, but it only returns the first object with a specified HTML name. This function is useful for getting the first option in a radiogroup or a checkgroup,

object getElementByName(string objectName)

Parameters:

  • string objectName: Specify the HTML name of the object. Remember to use the complete HTML name for an object, not the DynaForm field name. For example, a DynaForm field named "totalBid" would have an HTML name of "form[totalBid]". Most DynaForm fields have the same name as their id, but the options in a radiogroup or checkgroup have different ids, but the same name. Radiogroup options use the name "form[radiogroup-name]", while checkgroup options use the name "form[checkgroup-name][]".

Return value:

  • object: Returns the first object with a specified HTML name.

Example:
Mark the first option in a checkgroup named "caseOptions" when the "high" option is selected in the "casePriority" dropdown box:

 selectFirstOption() {
   if (getValueById("casePriority") == "high")
      getElementByName("form[caseOptions][]").checked = true;
}
leimnud.event.add(getField("casePriority"), 'change', selectFirstOption);

getElementsByClassNameCrossBrowser()

getElementsByClassNameCrossBrowser() returns an array of objects inside the specified node whose class matches a specified searchClass. This function is useful because many objects in DynaForms (such as grids) are located inside div's which have a particular class, but no id or name, so they can only be found by searching for their class.

array getElementsByClassNameCrossBrowser(string searchClass, object node, string tag)

Parameters:

  • string searchClass: The name of a class or a string which contains a regular expression to match class(es). Note that the regular expression search pattern is automatically constructed as RegExp("(^|\\s)"+searchClass+"(\\s|$)"), so do not include "^" or "$" in the string. See the Skins documentation for Common ProcessMaker Classes.
  • object node: The HTML node in which the search will take place. Set to null to search through the entire DynaForm.
  • string tag: Specify which type of HTML tag (such as "table", "td", "div", or "input") should be searched for the specified class. Set to null or "*" to search all types of HTML tags.

Return value:

  • array: Returns an array of HTML objects which match the the specified class.

Example:
Grids are enclosed inside of a div whose class is named "grid". The following code hides all the grids in a dynaform:

 var grids = getElementsByClassNameCrossBrowser("grid", null, "div");
var len = grids.length;
for (var i = 0; i < len; i++) {
   grids[i].style.display = "none";

To show all the grids in DynaForm, change the above line to:

  grids[i].style.display = "";
 

Accessing Field Values

getValue()

getValue() returns the value of the specified field as a string.

  string getValue(object field)

Parameters:

Return value:
Returns the value of the field as a string. If the field contains a number or date, it will need to be converted with parseInt(), parseFloat, Number(), or Date() before doing any calculations.

Note: This function will not work for checkboxes and options in checkgroups, which need to accessed through their checked property. For dropdown boxes, this function will return the value of the selected option (not its label). For listboxes, this function will only return the value of the first selected option. To find all selected options, loop through all its options examining their checked property.

Example:
The following code concatenates the contents of the "firstName" and "lastName" fields, then inserts them in the "fullName" field:

 function makeName() {
   var n = getValue(getField("firstName")) + ' ' + getValue(getField("lastName"));
   changeValue("fullName", n);
}
leimnud.event.add(getField('firstName'), 'change', makeName);
leimnud.event.add(getField('lastName'), 'change', makeName);

getValueById()

getValueById() returns the value of the specified field, just like the getValue() function, but it is more convenient because its parameter is the field name.

  string getValueById(string fieldName)

Parameters:

  • object fieldName: The name of a field.

Return value:
Returns the value of the field as a string. If the field contains a number or date, it will need to be converted with parseInt(), parseFloat, Number(), or Date() before doing any calculations.

Note: This function will not work for checkboxes and options in checkgroups, which need to accessed through their checked property. For dropdown boxes, this function will return the value of the selected option (not its label). For listboxes, this function will only return the value of the first selected option. To find all selected options, loop through all its options examining their checked property.

Example:
Whenever the values of the "price" or "discount" fields change, the values of the "discount" and "price" fields are converted into floating point numbers and then subtracted to be inserted into the "total" field:

 function calculateTotal() {
   getField("total").value = parseFloat(getValueById("price")) - parseFloat(getValueById("discount"));
}
leimnud.event.add(getField("price"), 'click', calculateTotal);
leimnud.event.add(getField("discount"), 'click', calculateTotal);

changeValue()

changeValue() sets the value of the specified field.

void changeValue(string fieldName, string newValue)

Parameters:

  • string fieldName: The name of a field whose value will be set.
  • string newValue: The new value to assign to the field. Note that all field values are stored as strings.

Return value:
None.

Note: Do not use this function with checkboxes and options in checkgroups, since they need to be set through their checked property. For dropdown boxes and listboxes, use the value of a option to select it (not its label). If using this function with listboxes, then it will deselect all other options. This function can not be used to select more than one option in a listbox. If more than one option needs to be selected, then set the checked property for each listbox option individually.

Example:
The following code transforms the value of the "ProductCode" field to uppercase when the focus leaves the field:

 function setUpper() {
   var upper = getValueById("ProductCode").toUpperCase();
   changeValue("ProductCode", upper);
}
leimnud.event.add(getField("ProductCode"), 'blur', setUpper);

removeValue()

removeValue() sets the value of the specified field to an empty string. Unlike the other functions to set the value, this function fires a "change" event after setting the value to an empty string, so any dependent fields will also update.

 void removeValue(string fieldName)

Parameters:

  • string fieldName: The name of a field whose value will be set to an empty string.

Return value:
None.

Example:
The following code clears the "Occupation" and "Income" fields if the "details" checkbox is not checked:

 function clearDetails() {
   if (getField("details").checked == false) {
      removeValue("Occupation");
      removeValue("Income");
   }
}
leimnud.event.add(getField("details"), 'change', clearDetails);

unselectOptions()

unselectOptions() deselects all the options in a dropdown box, listbox or radiogroup. In the case of dropdown boxes and radiogroups which always have one selected option, the first option in the list will automatically be reselected after calling this function.

void unselectOptions(string fieldName)

Parameters:

  • string fieldName: The field name of a dropdown box, listbox or radiogroup. Any other types of fields may generate errors.

Return value:

  • void: It does not return any value.

Example:

 function clearSelections() {
   unselectOptions('MyListbox');
}
leimnud.event.add(getField("MyTextbox"), 'change', clearSelections);

Hiding and Showing Objects

visible()

visible() makes a Dynaform field visible, by setting its HTML visible property to true.

void visible(object field)

Parameters:

  • object field: The object for the field to be be made visible. Use getField() or getGridField() to obtain the field object.

Return value:

  • void: It does not return any value.

Example:
Set the "telephoneNo" field to be visible if the "telephone" option is selected in the "contactType" dropdown box:

 function visField() {
   if (getValueById("contactType") == "telephone")
      visible(getField('telephoneNo'));
   else
      hidden(getField('telephoneNo'));
}
leimnud.event.add(getField("contactType"), 'change', visField);
visField(); //execute when DynaForm loads

Note: This function does not work with just the field names of checkgroups, radiogroups, and checkgroups. For example, this won't work:

 visible(getField('myRadioGroup'));
 

This function, however, can be used to show individual options in checkgroups and radiogroups and individual fields in grids. To show an option in a checkgroup or radiogroup:

visible(getField('myRadioGroup][myOption1'));

To show a field in a grid:

visible(getGridField('myGrid', 1, 'myField1'));

visibleById()

visibleById() works the same as the visible() function, but it is a more convenient version of this function which looks up an object by its field name and makes it visible.

 void visibleById(string fieldName)

Parameters:

  • string fieldName: The field name of the field to be made visible.

Return value:

  • void: It does not return any value.

Example:
Set the "telephoneNo" field to be visible if the "telephone" option is selected in the "contactType" dropdown box:

function visField() {
   if (getValueById("contactType") == "telephone")
      visibleById('telephoneNo');
   else
      hiddenById('telephoneNo');
}
leimnud.event.add(getField("contactType"), 'change', visField);
visField(); //execute when DynaForm loads

Note: This function does not work with just the field names of checkgroups, radiogroups, and checkgroups. For example, this won't work:

 visibleById('myRadioGroup');
 

This function, however, can be used to show individual options in checkgroups and radiogroups and individual fields in grids. To show an option in a checkgroup or radiogroup:

visibleById('myRadioGroup][myOption1');

To show a field in a grid:

visibleById('myGrid][1][myField1');

hidden()

hidden() turns a Dynaform field invisible (but not its surrounding row). The field still exists in memory, so it can be later redisplayed with the visible() or visibleById() functions.

 void hidden(object field)

Parameters:

Return value:

  • void: It does not return any value.

Example:
To hide a field named "selectAge" when a checkbox named "ageOption" is unmarked and show the field when it is marked:

 leimnud.event.add(getField("ageOption"), 'change', function()  
    if (getField("ageOption").checked)
       hidden(getField('selectAge'));
    else
       visible(getField('selectAge'));
 }
);

Note: This function does not work with just the field names of checkgroups, radiogroups, and checkgroups. For example, this won't work:

hidden(getField('myRadioGroup'));

This function, however, can be used to hide individual options in checkgroups and radiogroups and individual fields in grids. To hide an option in a checkgroup or radiogroup:

 hidden(getField('myRadioGroup][myOption1'));
 

To hide a field in a grid:

 hidden(getGridField('myGrid', 1, 'myField1'));

hiddenById()

hiddenById() works the same as the hidden() function, but it is a more convenient version of that function which looks up an object by its field name and makes it invisible.

void hiddenById(string fieldName)

Parameters:

  • string fieldName: The field name of the field to be made invisible.

Return value:

  • void: It does not return any value.

Example:

 function hiddenByIdField()
 {
    hiddenById('myfield');
    alert('The field is now hidden');
 }
 leimnud.event.add(getField("mybutton"), 'click', hiddenByIdField);
 

Where:

  • disField: The name of the function.
  • myfield: The field that will be invisible.
  • mybutton: The name of the button that will make invisible myfield.

Note: This function does not work with just the field names of checkgroups, radiogroups, and checkgroups. For example, this won't work:

 hiddenById('myRadioGroup');
 

This function, however, can be used to hide individual options in checkgroups and radiogroups and individual fields in grids. To hide an option in a checkgroup or radiogroup:

 hiddenById('myRadioGroup][myOption1');
 

To hide a field in a grid:

hiddenById('myGrid][1][myField1');

showHideElement()

showHideElement() toggles the visibility of a DynaForm field. If it is hidden, it will be shown. If it is visible, it will be hidden. This function is useful for using with toggle buttons to show or hide fields.

void showHideElement(string fieldName)

Parameters:

  • string fieldName: The field name of the field to hide/show.

Return value:

  • void: It does not return any value.

Example:

 getField("toggleButton").onclick = function() {showHideElement("Description")};
 

Note: This function does not work with just the field names of checkgroups, radiogroups, and checkgroups. For example, this won't work:

 showHideElement('myRadioGroup');
 

This function, however, can be used to show/hide individual options in checkgroups and radiogroups and individual fields in grids. To show/hide an option in a checkgroup or radiogroup:

showHideElement('myRadioGroup][myOption1');

To show/hide a field in a grid:

 showHideElement('myGrid][1][myField1');

hideRow()

This function is the same as hideRowById().

void hideRow(string fieldName)

hideRowById()

hideRowById() hides the complete row of a DynaForm field. The row includes not only the field, but also its label and its surrounding cells.

 void hideRowById(string fieldName)

Parameters:

  • string fieldName: The name of the field that will be hidden and its complete row.

Return value:

  • void: It does not return any value.

Example:
Hide the row of a field named "myField" when a button named "myButton" is clicked:

leimnud.event.add(getField("myButton"), 'click', function()
 {    hideRowById("myField"); }
);

showRow()

This function is the same as showRowById().

 void showRow(string fieldName)

showRowById()

showRowById() shows the complete row of a DynaForm field by specifying its field name.

void showRowById(string fieldName)

Parameters:

  • string fieldName: The name of the field, whose complete row will be shown.

Return value:

  • void: It does not return any value.

Example:
Show the row containing a field named "myField" when a button named "myButton" is clicked:

leimnud.event.add(getField("myButton"), 'click', function()
  { showRowById('myField'); }  
 );
 

hideRowById()

hideRowById() hides the rows of the DynaForm fields specified in an array of field names.

void showRowsById(array afieldNames)

Parameters:

  • array afieldNames: An array of the names of fields whose rows will be hidden. To hide checkgroups and radiogroups, specify one of the options within the group. Examples: "MyCheckGroup][OptionX" or "MyRadioGroup][OptionY"

Return value:
None.

Note: Grids can not hidden by this function due to this bug. For a workaround, see Hiding a grid.

Example:
Display the rows of the fields "price", "tax", "quantity", when the user marks the "PriceDetails" checkbox:

 function showOrHideFields() {
    if (getField("PriceDetails").checked)
       showRowById(["price", "tax", "quantity"]);
    else    //if not checked
       hideRowById(["price", "tax", "quantity"]);
 }
 leimnud.event.add(getField("PriceDetails"), 'change', showOrHideFields);//execute when changes
 showOrHideFields(); //execute when DynaForm loaded

showRowById()

showRowById() shows the rows of the DynaForm fields specified in an array of field names.

void showRowById(array afieldNames)

Parameters:

  • string afieldNames: An array of the names of fields whose rows will be shown.

Return value:

  • void: It does not return any value.

Example:
Display the rows of the fields "price", "tax", "quantity", when the user marks the "PriceDetails" checkbox:

 function showOrHideFields() {
    if (getField("PriceDetails").checked)
       showRowById(["price", "tax", "quantity"]);
    else    //if not checked
       hideRowById(["price", "tax", "quantity"]);
 }
 leimnud.event.add(getField("PriceDetails"), 'onchange', showOrHideFields); //execute when changes
 showOrHideFields(); //execute when DynaForm loaded
 

contractSubtitle()

contractSubtitle() contracts all the fields under a specified subtitle (until the next subtitle in the DynaForm), so they are hidden from view. Available from version 1.2-2467 on. Fields which have been hidden with this function will not be automatically validated, even if they have been defined as required="1" in the XML.

void contractSubtitle(string  fieldName)

Parameters:

  • string fieldName: The name of a subtitle field.

Return value:

None.

Note: This function cannot hide grids. To hide grids, see Hiding a Grid.

Example:

If a checkbox named "hideClientInfo" is marked, hide the fields under a subtitle named "clientInfoSection". If unmarked, then expand the subtitle:

leimnud.event.add(getField("hideClientInfo"), 'change', function()
   if (this.checked)
      contractSubtitle("clientInfoSection");
   else
      expandSubtitle("clientInfoSection");
}
);

expandSubtitle()

expandSubtitle() shows a subtitle field and all rows under it until the next subtitle in the DynaForm. This function is available from version 1.2-2467 on. If a field has been displayed with this function, then it will automatically be validated if it have been defined as required="1" in the XML.

void expandSubtitle(object subtitleField)

Parameters:

  • string subtitleField: The subtitle field object to expand.

Return value:

  • void: The function does not return any value.

Example:

 function expSub() {
    expandSubtitle('clientInfoSection');
 }
leimnud.event.add(getField("mybutton"), 'click', toggleSubtitle);

contractExpandSubtitle()

contractExpandSubtitle() shows or hides a subtitle field and all the rows beneath it until the next subtitle in the DynaForm. It works as a toggle switch, so if the subtitle is shown, then it will be hidden and if the subtitle is hidden, it will be shown. This function is useful for using with clickable images or buttons to contract/expand sections of a form.

void contractExpandSubtitle(object subtitleField)

Parameters:

  • string subtitleField: The subtitle field object, which can be obtained with the getField() function.

Return value:

  • void: The function does not return any value.

Example:

`
 function toggleSubtitle() {
    contractExpandSubtitle(getField('subRep1'));
 }
 leimnud.event.add(getField("mybutton"), 'click', toggleSubtitle);

Saving DynaForms

submitForm()

submitForm() submits the DynaForm, so the form will be closed and the values in the fields are saved to the database. This is the same action as when a user clicks on a submit button.

void submitForm()

Parameters:
None.

Return value:
None.

Example:
The following code automatically submits the DynaForm when a user selects the "no_details" option from the "selectDetails" dropdown box:

function checkDetails() {
   if (getValueById("selectDetails") == "no_details")
       submitForm();
}
leimnud.event.add(getField("selectDetails"), 'change', checkDetails);

saveForm()

Warning: File fields are not supported by the saveForm() function.

saveForm() saves the data in a DynaForm to the database (i.e., case variables are created for each field in the form). This function basically does the same thing as saveAndRefreshForm(), but it is faster since the form is not reloaded after sending the data to the ProcessMaker server with an AJAX call. Note that this function does not work in the Preview mode of the DynaForm Editor (since there is no case), but it does work when running a case. Available in version 2.0 and later.

void saveForm(object oObject)

Parameters:

  • object oObject: A field object, whose parent form will be saved. Set to null or "" (an empty string) to save all forms in the current DynaForm.

Return value:
None.

Examples:
Save the DynaForm's data when clicking on the custom "save" button:

function saveIt() {
    saveForm("");
 }
leimnud.event.add(getField("save"), 'click', saveIt);

Save the DynaForm's data when clicking on the custom "save" button, then redirect the browser window to the address "http://example.com/externalfeedbackForm.php":

function saveIt() {
    saveForm("");
    window.location.href = "http://example.com/externalfeedbackForm.php";
 }
leimnud.event.add(getField("save"), 'click', saveIt);

Automatically save the DynaForm data every 5 minutes, using the setInterval() and clearInterval() methods:

//starts when DynaForm loads:
 saveInterval = window.setInterval("saveForm('')", 60000);

Time is expressed in milliseconds, it means that 60000 milliseconds is equivalent to 1 minute

saveAndRefreshForm()

saveAndRefreshForm() saves and refreshes the data in a form at the same time. Note that this function does not work in the Preview mode of the DynaForm Editor (since there is no case data to be saved), but it does work when running a case. Available in version 1.2-2425 and later.

void saveAndRefreshForm(object objectName)

Parameters:

  • object objectName: A field object, whose parent form will be saved. Set to null or "" (an empty string) to save the first form found in the browser window, which in most cases will be the current DynaForm. However, using null might cause problems if running ProcessMaker inside an <iform> in a web page which has other forms.

Return value:

  • void: The function does not return any value.

Example:

function saveRefresh() {
    saveAndRefreshForm(this);
 }
 leimnud.event.add(getField("mybutton"), 'click', saveRefresh);

Note: It can take a while to save DynaForm data to a remote server. If redirecting the web page to a new location it may be a good idea to delay subsequent javascript commands to give saveAndRefreshForm() enough time to execute. For example, here a three second delay is added before redirecting the web browser to the cases list:

function saveRefresh() {
      saveAndRefreshForm(this);
      setTimeout("location.href = 'http://192.168.1.10/sysworkflow/en/green/cases/cases_List'", 3000);
 }
leimnud.event.add(getField("mybutton"), 'onclick ', saveRefresh);

saveAndRedirectForm()

saveAndRedirectForm() saves the data in a DynaForm to the database just like the saveForm() function, then redirects the web browser to a specified URL. Note that this function does not save any data in the Preview mode of the DynaForm Editor (since there is no case), but it does save data when running a case. Available in version 2.0 and later.

void saveAndRedirectForm(object oObject, string sLocation)

Parameters:

  • object oObject: A field object, whose parent form will be saved. Set to null or "" (an empty string) to save all forms in the current DynaForm.
  • string sLocation: A URL where the web browser will be redirected after saving the form. If set to "" (an empty string) or a direction which is not regarded as valid by the validateURL() function, then it will not redirect the web browser.

Return value:
None.

Example:
When clicking on the custom "save" button, save the current DynaForm and redirect back to the cases list:

function saveIt() {
    //construct URL for the cases list:
    var url = location.href.substring(0, location.href.lastIndexOf('/')) + "main";
    saveAndRedirectForm("", url);
 }
 leimnud.event.add(getField("save"), 'click', saveIt);

Requiring Fields

removeRequiredById()

removeRequiredById() disables the automatic validation of a specified field which is required by DynaForms. This function allows fields which were defined as required in the XML of a DynaForm to be omitted from validation (i.e., the user will be allowed to submit the form if this field is blank). Available in version 1.2-2467 and later.

void removeRequiredById(string fieldName)

Parameters:

  • string fieldName: The name of the field. If using a grid field, then use a field name like "grid-name][row-number][field-name". For example: "MyGrid][2][MyField"

Return value:

  • void: The function does not return any value.

Note 1: This function only works on fields which were marked as Required in their definition.

Note 2: This function does not remove the red asterisk * next to the field label, indicating that it is required. JavaScript can be used to remove the asterisk. See the example below.

Examples:
Remove the required property from the "validationCode" field when the "noValidate" checkbox is marked. When not marked, the required property is enabled. In addition, the red asterisk to the left of the field label is also removed or added:

getField("noValidate").onchange = function() {
   var labelNode = getRow('clientGroup').cells[0];
   var asterisk = '<font color="red">*  </font>';
   if (this.checked) {
      removeRequiredById('validationCode');
      //remove the red asterisk from the field's label:
      labelNode.innerHTML = labelNode.innerHTML.replace(asterisk, '');
   }
   else {
      enableRequiredById('validationCode');
      //if the field's label doesn't contain the red asterisk, then add it:
      if (labelNode.innerHTML.search(asterisk) == -1)
         labelNode.innerHTML = asterisk + labelNode.innerHTML;
   }
}

When a submit button named "submitNoValidate" is clicked, the form is submitted but none of the fields in the form are validated:

function removeAllRequired() {
    var aFields = document.forms[0].getElementsByTagName("input");
    for (var i = 0; i < aFields.length;  i++) {
        if ("value" in aFields[i] || "checked" in aFields[i]) {
           var fieldName = aFields[i].id.match(/^form\[(.*)\]$/);
           if (fieldName)
              removeRequiredById(fieldName[1]);
        }
    }
 }
 getField("submitNoValidate").onclick = function() {
    removeAllRequired();
    return true;
 }

Examples with Grid Fields:
The removeRequiredById() function can only be called on a single grid field in a specified row, not for the grid fields in all rows.

For example, to remove the required property from a grid field named "clientName" in the second row of a grid named "clientList":

removeRequiredById("clientList][2][clientName");

Removing the required property from all grid fields in every row is more difficult because the removeRequiredById() function has to be called for the field in every row in the grid. If the grid allows rows to be added or deleted, then it is recommended to remove the required property from the grid fields in an event handler for the form's submit action.

For example:

getField("clientList").form.onsubmit = function() {
   var totalRows = Number_Rows_Grid("clientList", "clientName");  
   for (var i = 1; i <= totalRows; i++) {        
      removeRequiredById("clientList][" + i + "][clientName");
   }
   return true;
}

If needing to determine whether to remove or not remove the required property at a point before the submit action, then set a variable which is read by the submit event handler.

For example, if a checkbox named "requireNameCheckbox" is marked, it sets the "removeRequiredName" variable which is used by the submit event handler:

removeRequiredName = false;
getField("requireNameCheckbox").onchange = function() {
   if (this.checked)
      removeRequiredName = true;
   else
      removeRequiredName = false;
}
getField("clientList").form.onsubmit = function() {
   if (removeRequiredName) {
      var totalRows = Number_Rows_Grid("clientList", "clientName");  
      for (var i = 1; i <= totalRows; i++) {        
         removeRequiredById("clientList][" + i + "][clientName");
      }
   }
   return true;
}

enableRequiredById()

enableRequiredById() enables the automatic validation of a specified field which is required (i.e., the user will not be allowed to submit the form if this field is blank). This function can be used to reactivate the validation of required fields which were previously disabled with removeRequiredById(). Available in version 1.2-2467 and later.

void enableRequiredById(string fieldName)

Parameters:

  • string fieldName: The name of the field to be required.

Return value:

  • void: The function does not return any value.

Note: This function only works on fields which were marked as Required in their definition. If needing to require fields which weren't marked as Required in their definition, then add custom code to submit which checks if the field is blank. See this example.

Example:

function enaRequired() {
    enableRequiredById('repSubject');
 }
 leimnud.event.add(getField("mybutton"), 'click', enaRequired);

Where:

  • repSubject: The name of the field that is required by the Dynaform.
  • mybutton: The button that will disable the automatic validation.
  • enaRequired: The name of the function.

form.verifyRequiredFields()

form.verifyRequiredFields() method highlights all the required fields in a form that are blank.

void form.verifyRequiredFields()

Parameters:
None.

Return value:
None.

Note: The form object in version 1.2, has a variable name like:

object_12565951048b858ca883c57091712352_40681270548d66e46554829029416532

The form object in version 2.0, has a variable name like:

form_WkpabW8yaWxhbU9rcUphaHFtbWFxR3FnWmNaaW4ybWphMm1pcDJxa3BXcG9wbXFtWnBob29XQ3FhSldrcVdYT3EyNXNxSktsWTVkZ29HaW9aMmFucldMTTZhS3BvbMKwbG9NOA______

Since the form variable name can change, it is best to concatenate the variable name with JavaScript and dynamically execute it with the eval() function. See the examples below.

Example in ProcessMaker version 1.2:

eval("object_" + getValueById("PRO_UID") + "_" + getValueById("DYN_UID")).verifyRequiredFields();

Example in ProcessMaker version 2.0:

eval("form_" + getField("MyField").form.id).verifyRequiredFields();

validateForm()

validateForm() checks whether any required fields in the current DynaForm are blank. If they are blank, a message appears informing the user to fill in the blank fields and they are highlighted in pink.

boolean validateForm(string sRequiredFields)

Parameters:

  • string sRequiredFields: An array of objects with information about the writable fields in the form which has been serialized as a JSON string. The contents of the DynaformRequiredFields hidden field can be used for this parameter.

Return value:

  • boolean: Returns true if there are no blank required fields. Returns false if there are any required fields which are blank.

Example:
Validate the fields when clicking on the "saveIt" button. If there are not blank required fields, then submit the form:

getField("saveIt").onclick = function() {
  var ret = validateForm(document.getElementById("DynaformRequiredFields").value);
  if (ret)
     submitForm();
}

Disabling and Enabling Fields

disable()

disable() greys out a DynaForm field, so its value can not be changed by the user (or clicked in the case of a button). After being disabled, the field is grayed out and the user cannot interact with it.

void disable(object field)

Parameters:

  • object field: The field object which will be disabled.

Return value:

  • void: It does not return any value.

Note: The data in a disabled field is not saved as a case variable when a DynaForm is submitted. To make sure that its data gets saved, either enable the field when the DynaForm is submitted or set the readOnly property of the field to true instead of disabling the field.

Example:

function disField()
 {
    disable(getField('myfield'));
    alert('The field is now disabled');
 }
 leimnud.event.add(getField("mybutton"), 'click', disField);

Where:

  • disField: The name of the function.
  • myfield: The field that will grey out.
  • mybutton: The name of the button that will disable myfield when clicked.

disableById()

disableById() works the same as the disable() function, but it is a more convenient version of that function which looks up an object by its field name.

void disableById(string fieldName)

Parameters:

  • string fieldName: The name of the field to be disable.

Return value:

  • void: It does not return any value.

Example:

function disByIdField()
 {
      disableById('myfield');
      alert('The field is now disabled');
 }
leimnud.event.add(getField("mybutton"), 'click', disByIdField);

Where:

  • disByIdField: The name of the function.
  • myfield: The field that will be disable.
  • mybutton: The name of the button that will disable myfield.

enable()

enable() activates a field, so its value can be changed by the user (or clicked in the case of a button). It sets its HTML disabled property to false.

void enable(object field)

Parameters:

  • object field: The field object to enable, which can be obtained with the getField() function.

Return value:

  • void: It does not return any value. .

Example:

function enaField()
 {
         enable(getField('myfield'));
         alert('The field is now enabled');
 }
leimnud.event.add(getField("mybutton"), 'click', enaField);

Where:

  • enaField: The name of the function.
  • myfield: The field that will grey out.
  • mybutton: The name of the button that will enable myfield when clicked.

enableById()

enableById() is a more convenient version of the enable() function, since its parameter is a field name, rather than a field object.

void enableById(string fieldName)

Parameters:

  • string fieldName: The name of the field to enable.

Return value:

  • void: It does not return any value.

Example:

function enaByIdField() {
      enableById('myfield');
      alert('The field is now enabled');
 }
 leimnud.event.add(getField("mybutton"), 'click', enaByIdField);

Where:

  • disByIdField: The name of the function.
  • myfield: The field that will be enable.
  • mybutton: The name of the button that will enable myfield.

Field Focus

setFocus()

setFocus() moves the focus in a specific field in a DynaForm so the user can interact with it directly without having move the mouse and clicking on the object. If the object is an input object such as a textbox, the cursor will be placed in the object so the user can begin changing its value. If the object is a button, it will receive the focus and the user can click it by pressing the ENTER key.

void setFocus(object field)

Parameters:

  • object field: The object for the field where the focus will be moved. Use the getField() function to get the field object.

Return value:

  • void: It does not return any value.

Example:

function setFocusField() {
    setFocus(getField('myfield'))
    alert('The attention is now focus on the field');
 }
 leimnud.event.add(getField("mybutton"), 'click', setFocusField);

Where:

  • setFocusField: The name of the function.
  • myfield: The field that you want be focus on.
  • mybutton: The name of the button that will focus the attention on myfield.

setFocusById()

setFocusById() works the same as the setFocus() function, but it is a more convenient version of that function which looks up a field by its field name and moves the focus to that field.

void setFocusById(string fieldName)

Parameters:

  • string fieldName: The field name of the field which will receive the focus.

Return value:

  • void: It does not return any value.

Example:

function setFocusByIdField() {
    setFocusById('myfield');
    alert('The field is now focus on');
 }
 leimnud.event.add(getField("mybutton"), 'click', setFocusByIdField);

Where:

  • setFocusByIdField: The name of the function.
  • myfield: The field that you want be focus on.
  • mybutton: The name of the button that will focus the attention on myfield.

dynaformSetFocus()

dynaformSetFocus() sets the focus in the first field in a DynaForm. This function is useful when resetting a DynaForm back to its original state.

void dynaformSetFocus()

Parameters:
None.

Return value:

  • void: It does not return any value.

Example:

function clearForm() {
    getField("Field1").value = '';
    getField("Field2").value = '';
    dynaformSetFocus();
 }
leimnud.event.add(getField("ClearButton"), 'click', clearForm);

Read-Only

toReadOnly()

toReadOnly() sets the specified field to read-only. Unlike activating the read only property of a field which doesn't change the appearance of the field, this function changes the background of the field to the color grey (#CCCCCC).

void toReadOnly(object field)

Parameters:

  • object field: The field object which will be set to read-only. Use the getField() function to get the field object.

Return value:
None.

Note: There is no function to set fields back so they are writable after calling this function, so the .readOnly and .style.background properties will have to be manually set to undo the changes caused by this function.

Example:
The following code clears the field "telephoneNo" and sets it to read-only when any option except "telephone" is selected from the "howContact" dropdown box:

function setTelephone() {
    if (getField("howContact").value != "telephone") {
       getField("telephoneNo").value = "";
       toReadOnly(getField("telephoneNo"));
    }
    else {
       getField("telephoneNo").readOnly = false;
       getField("telephoneNo").style.background = "";
    }
 }
leimnud.event.add(getField("howContact"), 'click', setTelephone);

toReadOnlyById()

toReadOnlyById() sets the specified field to read-only, just like the toReadOnly() function, but it is more convenient because its parameter is the field name.

void toReadOnlyById(string fieldName)

Parameters:

  • object fieldName: The name of the field which will be set to read-only.

Return value:
None.

Notes:

  • There is no function to set fields back so they are writable after calling this function, so the .readOnly and .style.background properties will have to be manually set to undo the changes caused by this function.

Examples:
The following code checks whether the "specifyName" hidden field was set to "yes" in a prior trigger when the DynaForm loads. If so, then it sets the "firstName" and "lastName" fields to read-only:

if (getField("specifyName").value == "yes") {
   toReadOnlyById("firstName");
   toReadOnlyById("LastName");
}

Highlight Functions

G.highLight()

G.highLight() sets the background color of a field to pink (#ffcaca). The field blinks once in red (#ff9d9d) after calling the function to call the user's attention to the field.

void G.highLight(object field)

Parameters:

Return Value:
None.

Note: To remove the highlighting from a field after calling G.highLight(), set the field's style.backgroundColor to an empty string. To make the highlighting disappear after a fixed amount of time, use the setTimeout() function to set the style.backgroundColor back to an empty string after a certain amount of time. (See examples below).

Examples:
If a user enters a value in the "bidTotal" field which is over the "maxBid", then highlight the "BidTotal" field and set focus to the "bidTotal" so the user can change it. If the "bidTotal" is less than the "maxBid", then the

leimnud.event.add(getField("bidTotal"), 'change', function()
 
    if (parseFloat(getValueById("bidTotal")) > parseFloat(getValueById("maxBid"))) {
       G.highLight(getField("bidTotal"));
       setFocusById("bidTotal");
    }
    else
       getField("bidTotal").style.backgroundColor = "";
 }
);

The following code highlights all the empty fields in a DynaForm for three seconds when a DynaForm first loads.

aFields = document.forms[0].getElementsByTagName("input");
for (var i = 0; i < aFields.length; i++) {
  if ("value" in aFields[i] && aFields[i].value == "") {
     G.highLight(aFields[i]);
  }
}
function removeHighlighting() {
   for (var ii = 0; ii < aFields.length; ii++)
      aFields[ii].style.backgroundColor = "";
}
setTimeout(removeHighlighting, 3000);

highlightRow()

highlightRow() sets the background color of a row (or any object) to a specified color.

void highlightRow(object obj, string color)

Parameters:

  • object obj: An object whose background color should be changed. A row in a DynaForm can obtained with the getRow() function. The cell holding a DynaForm field can be obtained with: getField("field-name").parentNode
  • string color: A color which can either be one of the 147 standard color names (such as "red") or the hexidecimal RGB (red-green-blue) numbers for the color (such as "#F2C2A1").

Return Value:
None.

Note for Normal Fields: For normal fields (not grid fields), this function only sets the background color of the cell holding the label, but not the background color of the cell holding the field itself. To set the background color around the field, use: highlightRow(getField("field-name").parentNode, "color");

Note for Grids: This function sets the background color of the whole row in grids, but that background color is quickly overwritten for every other row in the grid, which is set to a light blue color.

Examples:
If a currency field named "bidAmount" is set to a value over $1000, the background color of its row is changed to green:

leimnud.event.add(getField("bidAmount"), 'change', function()
   if (removeCurrencySign(getValueById("bidAmount")) > 1000) {
      highlightRow(getRow("bidAmount"), "green");
      highlightRow(getField("bidAmount").parentNode, "green");
   }
   else {  
      highlightRow(getRow("bidAmount"), "");                    //remove highlighting
      highlightRow(getField("bidAmount").parentNode, "f9f9f9"); //return cell to original color
   }
}
);

Set the background color of any row in a grid to yellow, whose "amount" field is over $100:

leimnud.event.add(getField("AccountsGrid"), 'change', function()
   var len = Number_Rows_Grid("ÄccountsGrid", "amount");
   for (var i = 1; i <= len; i++) {
      var row = getRow("AccountGrid][" + i + "][amount");
      if (getGridValueById("AccountGrid", i, "amount") > 100)
         highlightRow(row, "yellow");  
      else
         highlightRow(row, ""); //remove highlighting
   }
}
);

Grid Functions

getGridField()

getGridField() returns a field inside of a row in a grid. This function is useful when referencing the properties of a field in a grid (such as its .value property).

object getGridField(string gridName, int rowNo, string fieldName)

Parameters:

  • string gridName: The field name for the grid.
  • int rowNo: The number of the row in the grid, which starts counting from the number 1.
  • string fieldName: The name of a field inside the grid.

Return value:

  • object: Returns the specified field inside a grid.

Examples:
Set the values of the "firstName" and "lastName" fields in the first row of the "contactsGrid" when the DynaForm loads:

getGridField("contactsGrid", 1, "firstName").value = "Jane";
 getGridField("contactsGrid", 1, "lastName").value = "Doe";

When a DynaForm's submit button is clicked, the following code loops through a grid and creates a list of all the first and last names in the grid and saves them to a hidden field named "contactsList", so they can be displayed in a textarea in a subsequent DynaForm.

function saveName() {
    var list = '';
    var tot = Number_Rows_Grid("contactsGrid", "firstName");
    for (var i = 1; i <= tot; i++) {
       if (list != '')  //if not empty, add hard return before adding contact name to list
          list += '\n';
       list += getGridField("contactsGrid", i, "firstName").value + ' ' +
               getGridField("contactsGrid", i, "lastName").value;
    }
    getField('contactsList').value = list;
    return true; //return true so the submit action will continue
 }
 leimnud.event.add(getField("MySubmitButton"), 'click', saveNames);

getGridValueById()

getGridValueById() returns the value of a specified grid field.

string getGridValueById(string gridName, int rowNo, string fieldName)

Parameters:

  • string gridName: The field name for the grid.
  • int rowNo: The number of the row in the grid, which starts counting from the number 1.
  • string fieldName: The name of a field inside the grid.

Return value:

  • string: Returns the value of the specified grid field as a string. If the content of the field is a number or date, it will need to be converted.

Example:
The following code displays an alert showing the total price including tax whenever the "price" in the first row of a grid is changed:

function showTotal() {
    var price = parseFloat(getGridValueById("ProductsGrid", 1, "price"));
    var tax = price * parseFloat(getGridValueById("ProductsGrid", 1, "taxRate"));
    var total = price + tax;
    G.alert("The total price is $" + total", "Total");
 }
 getGridField("
ProductGrid", 1, "price").onchange = showTotal;

Number_Rows_Grid()

Number_Rows_Grid() returns the number of rows in a grid.

int Number_Rows_Grid(string gridName, string fieldName)

Parameters:

  • string gridName: The field name for the grid.
  • string fieldName: The name of any field inside the grid.

Return value:

  • string: Returns the number of rows in a grid. If the grid field doesn't exist or there are zero rows, this function returns 0.

Example:
Loop through all the rows in a grid named "contactsGrid" and clear their "firstName", "lastName" and "address" fields:

function clearIt() {
    var tot = Number_Rows_Grid("contactsGrid", "firstName");
    for (var i = 1; i <= tot; i++) {
       getGridField("contactsGrid", i, "firstName").value = "";
       getGridField("contactsGrid", i, "lastName").value = "";
       getGridField("contactsGrid", i, "address").value = "";
    }
 }
 leimnud.event.add(getField("ClearGridButton"), 'click', clearIt);

getObject()

getObject() returns an object representing a grid in a DynaForm. This object contains the grid methods, such as grid.addGridRow() and grid.deleteGridRow(). Available from version 1.2-2372 on.

object getObject(string gridName)

Parameters:

  • string gridName: The field name of the grid.

Return value:

  • object: The grid object.

Examples:
To better understand the structure of a grid object, examine its contents with var_dump():

alert(var_dump(getObject("MyGrid")));

grid.getElementByName()

grid.getElementByName() returns the specified grid field object for a specified row.

object grid.getElementValueByName(int iRow, string sName)

Parameters:

  • int iRow: The number of the row in the grid. Remember that the counting of rows starts from 1.
  • string sName: The name of the grid field.

Return value:

  • object: The object of the specified grid field.

Example:
When the user leaves the "contactsGrid", set the background color of all "lastName" fields which are blank to yellow in the "contactsGrid":

getField("contactsGrid").onblur = function() {
   var tot = Number_Grid_Rows("contactsGrid", "lastName");
   var grd = getObject("contactsGrid");
   for (var i = 0; i <= tot; i++) {
      if (grd.getElementByName(i, "lastName").value == "")
         grd.getElementByName(i, "lastName").style.backgroundColor = "yellow";
      else
         grd.getElementByName(i, "lastName").style.backgroundColor = "";
   }
}

grid.getElementValueByName()

grid.getElementValueByName() returns the value of a specified grid field for a specified row.

string grid.getElementValueByName(int iRow, string sName)

Parameters:

  • int iRow: The number of the row in the grid. Remember that the counting of rows starts from 1.
  • string sName: The name of the grid field.

Return value:

  • string: The value of the specified grid field.

Example:
When a new row is added to the "accountsGrid", automatically copy the "accountName" from the previous row:

grid_accountsGrid.onaddrow = function(iRow) {
   var grd = getObject("accountsGrid");
   grd.getElementByName(iRow, "accountName").value = grd.getElementValueByName(iRow - 1, "accountName");
}

grid.getFunctionResult()

grid.getFunctionResult() returns the result of an aggregate function (sum or avg) for a grid column.

string grid.getFunctionResult(string sName)

Parameters:

  • string sName: The name of the grid field which has an aggregate function.

Return value:

  • string: The result of the aggregate function (sum or avg). Remember to convert it to a number before using it in mathematical operations.

Example:
When the "price" field in the "productsGrid" or the "taxRate" field (outside the grid) changes, calculate the "total" based upon the sum of the "price" column, multipled by the "taxRate":

function calculateTotal() {
   var priceTotal = parseFloat(getObject("productsGrid").getFunctionResult("price"));
   getField("total") = priceTotal + priceTotal * removePercentageSign("taxRate");
}
//When new row added to grid, add onchange event handler for the new "price" field:
grid_productsGrid.onaddrow = function(iRow) {
   getGridField("productsGrid", iRow, "price").onchange = calculateTotal;
}
 
getField("taxRate").onchange = calculateTotal;

grid.addGridRow()

The grid.addGridRow() method adds a new row to the bottom of a grid object. The grid object can be obtained with the getObject() function.

void grid.addGridRow()

Parameters:
None.

Return value:
None.

Warning: The addGridRow() method does not work in the DynaForm editor in versions 2.0.36 - 2.0.39 due to this bug, but it does work when executing cases.

Example:
When the user clicks on the "addAccount" button, add a new row to a grid named "AccountsGrid" and then insert the value of the "accountName" and "accountNo" fields into the "name" and "no" grid fields in the new row:

getField("addAccount").onclick = function() {
  newRowNo = Number_Rows_Grid("accountsGrid", "name") + 1;
  getObject("accountsGrid").addGridRow();
  getGridField("accountsGrid", newRowNo, "name").value = getField("accountName").value;
  getGridField("accountsGrid", newRowNo, "no").value   = getField("accountNo").value;
}

grid.deleteGridRow()

The grid.deleteGridRow() method deletes a specified row from a grid object. The grid object can be obtained with the getObject() function.

boolean grid.deleteGridRow(variant sRow, boolean bWithoutConfirm)

Parameters:

  • variant sRow: The number of the row in the grid. Remember that the counting of rows starts from 1. Can pass the row number as either a string or a number. If the number is enclosed in square brackets such as "[3]" (as is found in grid field ids), then the square brackets will be stripped.
  • boolean bWithoutConfirm: An optional parameter available in version 2.0.30 and later. If not included or set to false then a message will appear asking the user to confirm the deletion of the row. Set to true to delete the row without confirmation from the user.

Return value:

  • boolean: Returns false if unable to delete a row, because it doesn't exist or because it is the only row in the grid.

Warning: This function does not work correctly in the DynaForm Designer, but it does work when running a case.

Example:
Delete all the rows in a grid named "contactsGrid", when a user click on the "clearGrid" button:

leimnud.event.add(getField("clearGrid"), 'click', function()
{
   var grd = getObject("contactsGrid");
   var i = Number_Rows_Grid("contactsGrid", "firstName");
   for (; i > 1; i--) {
       grd.deleteGridRow(i, true);
   }
   //The first row can't be deleted, clear the fields in the first row:
   for (i = 0; i < grd.aFields.length; i++) {
      getGridField("contactsGrid", 1, grd.aFields[i].sFieldName).value = "";
   }
 
 });

Data Manipulation Functions

isNumber()

isNumber() evaluates if the sent value is numeric. The only parameter for this function is the value.

boolean isNumber(variant value)

Parameters:

  • variant value: This is the value that the function will evaluate.

Return value:

  • boolean: The function returns a boolean value (true = 1 or false = 0).

Example:

var x = "a";
 var y = 5;
 if (isNumber(x))
      alert('x is number');
 else
      alert('x is not number');
 if (isNumber(y))
      alert('y is number');
 else
     alert('y is not number');

Where:

  • x: A variable defined as a string.
  • y: A variable defined as a integer.

roundNumber()

roundNumber() rounds a number to a specified number of decimal places. If the number decimal places is not specified or is 0, then 2 decimal places are taken by default.

float roundNumber(variant value, int number)

Parameters:

  • variant value: This is the value that the function will round. It can be a float, int, or string (which converts to a number).
  • int number: This is the number of decimals wished.

Return value:

  • float: The function returns the rounded number.

Note: When a floating point number is assigned to a DynaForm field it is automatically converted into a string, but JavaScript's toString() method drops any zeros, so 84.30 becomes "84.3". To ensure that zeros are displayed, use the roundNumber() function to round the number to a specified number of decimal places, then convert the number to a string with that specified number of decimal places with the toFixed() method. For example:

getField("MyField").value = roundNumber(2.789, 2).toFixed(2); //assigns "2.79"
 getField("MyField").value = roundNumber(2.7, 4).toFixed(4);   //assigns "2.7000"

To just round to the nearest whole number, use the Math.round() function. For example:

getField("MyField").value = Math.round(2.789);  //assigns 3

Example:
When the "price" or "quantity" field changes, multiple the two fields and round it to two decimal places before inserting it into the "total" field:

function setTotal() {
   var total = parseFloat(getValueById("price")) * parseInt(getValueById("quantity"));
   getField("total").value = roundNumber(total, 2).toFixed(2);
}
getField("price").onchange = setTotal;
getField("quantity").onchange = setTotal;
setTotal();

creaZero()

creaZero() creates a string of zeros, whose length is determined by its parameter.

string creaZero(int number)

Parameters:

  • int number: This is the number of zeros that will be added.

Return value:

  • string: The function returns a string with the number of zeros specified.

Example:

var x = "";
 var y = 4;
 alert('This is my string x = "' + x + '"');
 x = creaZero(y);
 alert('This is my new string x = "' + x + '"');

Where:

  • x: A string variable.
  • y: The number of zeros wished.

toUnmaskNumber()

toUnmaskNumber() strips any "," (commas), " " (spaces), "%" (percent signs) and "$" dollar signs from a string and converts it into a floating point number.

float toUnmaskNumber(variant sNumber)

Parameters:

  • variant sNumber: A string or number to be converted into a floating point number.

Return value:

  • float: The function returns a floating point number.

Example:
In this example, the string "9.025,123" is converted into the number 9.025123:

 var x = toUnmaskNumber("9.025,123");            
 alert('This is my x = ' + x);

validateURL()

validateURL() checks whether a string appears to be a valid URL (web address) which starts with "http://" or "https://" and appears to have a domain name or IP address. It only checks whether the URL matches a certain pattern of characters, so the URL may or may not exist in reality.

boolean validateURL(string url)

Parameters:

  • string url: The URL (Universal Resource Locator) to test.

Return value:

  • boolean: Returns true if appears to be a valid URL or false if it doesn't match the specified pattern.

Example:
When a user finishes entering the URL for a company website, an alert informs the user if the address appears to be invalid.

function checkAddress() {
    var url = getValueById("companyUrl");
    if (url != "" && !validateURL(url))
       G.alert("Address " + url + is not a valid web address.", "Error");
 }
 getField("
mybutton").onblur = checkAddress;

removeCurrencySign()

removeCurrencySign() strips all characters which are "$" (dollar signs), " " (spaces) and "," (commas) and returns a string without those characters. This function can be used before converting the value from a currency field to a number.

string removeCurrencySign(variant sNumber)

Parameters:

  • variant sNumber: A string or number.

Return value:

  • boolean: Returns a string without dollar signs, spaces or commas.

Example:
Show an alert message if the "price" times the "quantity" is over the maximum budget.

function checkTotal() {
    var price = Number(removeCurrencySign(getValueById("price")));  
    var quantity = Number(removeCurrencySign(getValueById("quantity")));
    var total = price * quantity;
    if (total > getValueById("maxBudget"))
        G.alert("Total $" + total + " is overbudget. Please reduce to less than $" +
           getValueById("maxBudget") + ".", "Budget Error!");
 }
 getField("quantity").onchange = checkTotal;
 getField("price").onchange = checkTotal;

removePercentageSign()

removePercentageSign() strips all characters which are "%" (percent signs), " " (spaces) and "," (commas) and returns a string without those characters. This function can be used before converting the value from a percentage field to a number.

string removeCurrencySign(variant sNumber)

Parameters:

  • variant sNumber: A string or number.

Return value:

  • string: Returns a string without dollar signs, spaces or commas.

Example:
Change the border color of the "price" field if the price plus tax is over budget:

function checkTotal() {
    var price = Number(removeCurrencySign(getValueById("price")));  
    var tax = Number(removePercentageSign(getValueById("tax")));
    var totalPrice = price + price * tax;
    if (total > getValueById("maxBudget"))
        getField("price").style.colorBorder = "red";
    else
        getField("price").style.colorBorder = "green";
 }
 getField("price").onchange = checkTotal;
 getField("tax").onchange = checkTotal;

htmlentities()

htmlentities() converts a string into its HTML entities, so characters are converted into an HTML code which can not be confused by the character encoding. For example, ">" becomes "&gt;" and "á" becomes "&aacute;". This function is useful for saving text which will later be displayed in email or output document templates where the character encoding may cause problems. Note that this function will only convert 8 bit characters found in Roman alphabet languages. It can not be used to convert languages like Russian, Greek, Chinese, etc.

string htmlentities(string str, string quote_style)

Parameters:

  • string str: A string to convert to HTML entities.
  • string quote_style: Set to "ENT_QUOTES" to convert quotation marks into HTML entities or "ENT_NOQUOTES" to not convert quotation marks.

Return value:

  • string: Returns the converted string.

Example:
A DynaForm has a textarea named "MessageToEmployee" which is the message to be inserted into a form letter to an employee. JavaScript code copies the text of this message into a hidden field named "MessageToEmployeeHtml" whose contents will be later inserted into an email template:

getField("MessageToEmployee").onchange = function() {
    getField("MessageToEmployeeHtml").value = htmlentities(getValueById("MessageToEmployee"));
 }

fix()

fix() sets a string (which is how fields store numbers) to have a specified number of decimal digits. This function just drops any extra digits and does not round. If rounding is needed, see Converting numbers to strings.

string fix(string val, int dec)

Parameters:

  • string val: A number in the format of a string. This function must be passed a string.
  • int dec: The number of decimal digits.

Return value:

  • string: Returns a string of the number with the specified number of decimal digits.

Note: This function should only be used with strings. If using numbers, it is recommended to use the number.toFixed() method.

Example:
When a user finishes entering the URL for a company website, an alert informs the user if the address appears to be invalid.

function checkAddress()
 {  var url = getValueById("companyUrl");
    if (url != "" && !validateURL(url))
       G.alert("Address " + url + is not a valid web address.", "Error");
 }
 getField("
mybutton").onblur = checkAddress;

stripslashes()

stripslashes() returns a string which has removed the backslashes "\" before quotation marks. Backslashes are used in SQL to escape quotation marks so they can be used inside a string and not terminate it.

void stripslashes(string str)

Parameters:

  • string str: A string of characters.

Return value:

  • string: A string with the backslashes removed.

Example: Strip the backslashes from the string "Don\'t say \"hello\" to him", so it becomes "Don't say "hello" to him":

getField("MyMessage").value = stripslashes(""Don\'t say \"hello\" to him");

addslashes()

addslashes() returns a string which has added backslashes "\" before quotation marks (' or "). Backslashes are used in SQL to escape quotation marks (" or ') so they can be used inside a string and not terminate it.

string addslashes(string str)

Parameters:

  • string str: A string of characters.

Return value:

  • string: A string with the backslashes added before quotation marks.

Example: Add backslashes to the string "Don't say "hello" to him", so it becomes "Don\'t say \"hello\" to him":

getField("MyMessage").value = addslashes("Don't say \"hello\" to him");

string.trim()

string.trim() method returns a string which has eliminated all leading and trailing spaces from a string.

string string.trim()

Parameters:
None.

Return value:

  • string: A string with all leading and trailing spaces stripped.

Examples:
Convert " this is a test! " to "this is a test!";:

var trimmedStr = "  this is a test!  ".trim();

When the "firstName" and "lastName" fields are changed, trim and concatenate them before inserting into the read-only "fullName" field:

function createFullName() {
  getField("fullName").value = getField("firstName").value.trim() + " " + getField("lastName").value.trim();
}
getField("firstName").onchange = createFullName;
getField("lastName").onchange = createFullName;

Trim the "accountName" field when the DynaForm is submitted:

getField("accountName").form.onsubmit = function() {
  getField("accountName").value = getField("accountName").value.trim();
  return true; //return true to continue with the submit action
}

variant.toJSONString()

variant.toJSONString() method returns the value of an object converted into a JSON string. This method is available for DynaForm fields, strings, numbers, arrays, and objects.

string variant.toJSONString()

Parameters:
None.

Return value:

  • string: A JSON string.

Examples:

var sArray = [123, "hello", ["x", "y"], true].toJSONString();
var sField = getField("MyField").toJSONString();

Date Functions

compareDates()

compareDates() compares two dates if one of them is greater or lesser the function returns a false value it means that the dates are not equal. On the other hand, if the function returns a true value it means that the dates are equal.

boolean compareDates(string dateA, string dateB, boolean byDays)

Parameters:

  • string dateA: The first input date to be compared. The input date must be a string in the format 'YYYY-MM-DD'. (Any time information will be ignored.)
  • string dateB: The second input date to be compared. The input date must be a string in the format 'YYYY-MM-DD'. (Any time information will be ignored.)
  • boolean byDays: To compare the date by days, then set to true. To only compare the year and month, but not the day, then set to false.

Return value:

  • boolean: The function returns true if the dates are equal and false if they are unequal.

Note: This function only works with dates in the default 'YYYY-MM-DD' format. If using dates with different formats, reorder the date string with JavaScript. (See example for diff_date() below.) To compare dates with different masks and do more advanced comparisons, see Accessing Dates with JavaScript.

Examples:
Comparing whether the "DueDate" and "DeliveryDate" are the same day:

if (compareDates(getValueById("DueDate"), getValueById("DeliveryDate"), true)
    alert("Delivered on exact day!");

Comparing whether the "DueDate" and "DeliveryDate" are in the same month:

if (compareDates(getValueById("DueDate"), getValueById("DeliveryDate"), false)
    alert("Delivered on in same month");

diff_date()

diff_date() calculates the difference in days between two dates which use the default "YYYY-MM-DD" format.

int diff_date(string date1, string date2)

Parameters:

  • string date1: A date string in the default "YYYY-MM-DD" format.
  • string date2: A date string in the default "YYYY-MM-DD" format.

Return value:

  • int: Returns the number of whole days of difference between two dates. If date1 is before date2, then the number will be negative.

Examples: When a user finishes entering the URL for a company website, an alert informs the user if the address appears to be invalid.

 function calcDiff() {  
    getField("dateDifference").value = diff_date(getValueById("dateFrom"), getValueById("dateTo"));
 }
 getField("dateFrom").onchange = calcDiff;
 getField("dateTo").onchange = calcDiff;
 calcDiff(); //execute when DynaForm loads

In this case the dates use the format "MM/DD/YYYY", so they will have to reordered as "YYYY-MM-DD" before being passed to diff_date():

function calcDiff() {  
    var a = getField("dateFrom").value.split("/");
    var dateFrom = a[2] + " " + a[0] + " " + a[1]);
    a = getField("dateTo").value.split("/");
    var dateTo = a[2] + " " + a[0] + " " + a[1]);
    getField("dateDifference").value = diff_date(dateFrom, dateTo);
 }
 getField("dateFrom").onchange = calcDiff;
 getField("dateTo").onchange = calcDiff;
 calcDiff(); //execute when DynaForm loads

validDate()

validDate() tests whether a date field (or any other type of field) has a valid date. After version 2.0.32, it can check fields which have any format for the date, as long as it includes a four digit year, a two digit month and a two digit day.

boolean validDate(string dateFieldName, boolean required)

Parameters:

  • string dateFieldName: The name of a date field.
  • boolean required: Set to true, if the date field is not allowed to be blank. If allowed to be blank, then set to false.

Return value:

  • boolean: Returns true if the date field contains a valid date value; otherwise returns false.

Warning: This function did not work before before version 2.0.32 due to this bug.

Example:
Check whether the input in a textbox named "dueDate" is a valid date when the user leaves the field. If not, highlight the field in pink:

getField("dueDate").onblur = function() {
  if (validDate("dueDate"))
     G.highLight(getField("dueDate"));
  else
     getField("dueDate").style.backgroundColor = "";
}

datePicker4()

datePicker4() sets the mask, date range and time option for a date field in version 2.0 and later.

void datePicker4(variant obj, string id, string mask, string startDate, string endDate, boolean showTime)

Parameters:

  • variant obj: An unused parameter that can be set to "" (an empty string).
  • string id: The id for the date field. Remember that DynaForm fields use the id: "form[field-name]"
  • string mask: The mask for the date field.
  • string startDate: The starting date for the date range in the date picker dialog in the format "YYYY-MM-DD".
  • string endDate: The starting date for the date range in the date picker dialog in the format "YYYY-MM-DD".
  • boolean showTime: To show the time (hours and minutes), set to true; otherwise set to false. This parameter is currently unused, although it may be implemented in future versions of Processmaker, so it is unused. To have the current time automatically inserted in the date, add the hours and minutes codes to the mask.

Return Value:

  • void: This function does not return any value.

Examples:
Set the "deliveryDate" date field to use the mask "%d-%m-%Y", so it will have the format "DD-MM-YYYY" and set its date range from January 1, 2010 to December 31 2013:

datePicker4("", 'form[deliveryDate]', '%d-%m-%Y', '2010-01-01', '2013-12-31', false);

In this example, the starting date of the date range for the "dueDate" date field is set by the value of the "orderDate" field. The ending date is set to 10 days after the "orderDate". The date field is set to use an English style date which has the mask "%m/%d/%Y":

function twoDigits(num) {
    return (num < 10 ? "0" : "") + num;
 }
 getField("orderDate").onchange = function() {
    var startDate = new Date(getValueById("orderDate"));
    var startDateSt = startDate.getFullYear() + '-' + twoDigits(startDate.getMonth()) +
       '-' + twoDigits(startDate.getDate());
    var endDate = new Date(startDate.getTime() + 10 * 86400000); //add ten days in milliseconds
    var endDateStr = endDate.getFullYear() + '-' + twoDigits(endDate.getMonth()) +
       '-' + twoDigits(endDate.getDate());
    datePicker4("", 'form[dueDate]', '%m/%d/%Y', startDateStr, endDateStr, false);
 };

Cookie Functions

createCookie()

createCookie() creates a cookie which is a name-value pair which is stored on the local browser for set amount of time. Cookies are commonly used to store temporary information which shouldn't be lost every time a web page unloads or is refreshed.

void createCookie(string name, variant value, int days)

Parameters:

  • string name: The name of the cookie.
  • string value: The value of the cookie.
  • int days: The number of days to store the cookie.

Return Value:
None.

Example:
Store the client name for a week when a DynaForm is submitted, so the same client name can be auto inserted in subsequent DynaForms for the next week in that web browser.

getField("clientName").form.onsubmit = function() {
    if (getValueById("clientName") != "")
       createCookie("clientName", getValueById("clientName"), 7);
    return true; //return true to continue with submit action
 }

readCookie()

readCookie() returns the value of a previously stored cookie.

string readCookie(string name)

Parameters:

  • string name: The name of the cookie.

Return Value:

  • string: Returns the value of the cookie. If the cookie doesn't exist or it has expired, then it returns null.

Example:
When a DynaForm loads, check if the "clientName" cookie (which was set in the previous example) exists. If so, insert its value into the "contactName" field.

var storedName = readCookie("clientName");
 if (storedName)
    getField("contactName").value = storedName";

eraseCookie()

eraseCookie() deletes a previously stored cookie.

void eraseCookie(string name)

Parameters:

  • string name: The name of the cookie to delete.

Return Value:
None.

Example:
If the user clicks on a reset button named "resetButton", then "clientName" cookie is deleted:

getField("resetButton").onclick = function() {
    eraseCookie("clientName");
    return true; //return true to continue with reset action
 }

Messages to the User

Standard JavaScript functions such as alert(), confirm(), and prompt() can be used, but ProcessMaker also provides custom functions to display messages to the user.

Unlike the standard JavaScript functions, ProcessMaker's custom message functions do not wait until the user closes the message box. Any code immediately after the message function will immediately execute and not wait for the response of the user to the message. If needing to wait for the response of the user, then use the setInterval() and clearInterval() functions to execute code after the user responds. See the examples below for msgBox() and leimnud.module.app.confirm().

G.alert()

G.alert() displays a message to the user. It is very similar to the standard alert() function, but the title of the message can be specified and the message box matches the ProcessMaker style.

void G.alert(string msg, string title)

Parameters:

  • string msg: The text to display to the user. HTML formatting tags can be used. To insert a newline, use <br>.
  • string title: The title of the message box. HTML formatting tags can be used.

Return Value:
None.

Note: The width of the message box will not change, but the height of the message box will adjust to accommodate larger texts so we recommend to use short texts.

Example:
When a DynaForm is submitted, check whether the "estimate", "transport" and "taxes" fields sum up to more than $100 and less than $1000. If not stop the submit and display a message to the user to change the quantities in the fields.

getField("estimate").form.onsubmit = function() {
   var estimate  = parseFloat(removeCurrencySign(getValueById("estimate")));
   var transport = parseFloat(removeCurrencySign(getValueById("transport")));
   var taxes     = parseFloat(removeCurrencySign(getValueById("taxes")));  
   var total = estimate + transport + taxes;
   if (total < 100) {
      G.alert("Estimate total should not be under $100.", "Total too Low!");
      return false;
   }
   else if (total > 1000) {
      G.alert("Estimate total should not be over $1000.", "Total too High!");
      return false;
   }
   return true;
}

msgBox()

msgBox() displays a message to the user. The style of the message box changes depending upon its type parameter, so it can be used to simply inform the user (similar to the standard alert() function) or to receive confirmation from the user (similar to the standard confirm() function).

void msgBox(string msg, string type, object callbackAccept, object callbackCancel)

Parameters:

  • string msg: The text to display to the user. HTML formatting tags can be used. To insert a newline, use <br>.
  • string type: The type of message box, which can be "info", "alert", or "confirm". The icon displayed in the message box will adjust according to the type. "info" and "alert" message boxes, display only an "Accept" button, while "confirm" message boxes display "Accept" and "Cancel" buttons. If the type parameter is not defined, then it will default to "info". If the type is not set to one of the three acceptable values, then the message box will not display.
  • object callbackAccept: A function to be executed when the user clicks on the "Accept" button. If no callback function is neeeded, set to null or do not include the parameter in the function call.
  • object callbackCancel: A function to be executed when the user clicks on the "Cancel" button (which only exists for "confirm" message boxes). If no callback function is neeeded, set to null or do not include the parameter in the function call.

Return Value:
None.

<

Note 1: If the user closes the message box by clicks on [x] in the upper right hand corner, then no callback function will be executed.

Note 2:The height and width of the message box will not adjust accommodate larger texts. If the msg is longer than two lines, vertical scroll bars will appear to allow larger texts to be read.

Example 1:
When a user marks the "notifyClient" checkbox, an "info" message box appears informing that user that a letter needs to be sent out by the user in the next week. The current time is automatically inserted into the "notifyTime" textbox when the user clicks on the "Accept" button.

function setTime() {
   var d = new Date();
   getField("notifyTime").value = d.getHours() + ":" + d.getMinutes();
}  
getField("notifyClient").onchange = function() {
   if (getField("notifyClient").checked == true)
      msgBox("Please send a letter to the client within the next week.", "info", setTime);
}

Example 2:
When a user marks the "notifyClient" checkbox, a "confirm" message box appears asking whether the client should be notified via email. If the "Accept" button is clicked, then an an anonymous callback function is executed to set the "sendEmail" hidden field to "yes". If the "Cancel" button is clicked, then the "sendEmail" hidden field is set to "no":

getField("notifyClient").onchange = function() {
   if (getField("notifyClient").checked == true) {
      msgBox("Automatically send an email to the client?", "confirm",
         function(){getField("sendEmail")="yes";},  //Accept callback function
         function(){getField("sendEmail")="no";}    //Cancel callback function
      );
   }
}

Example 3:
When a user clicks on the "saveData" button, a "confirm" message box appears asking whether the form data should be saved. If the user click on "Accept", the variable resp will be set to "yes". If the user clicks on "Cancel", it will be set to "no". A polling function is activated with the setInterval() function, which checks every 100 milliseconds whether the user has responded by looking at the resp variable. If the user has responded then the polling function will be removed with clearInterval(). If the response of the user was "yes", then call the saveForm() function to save the data in the form to the database. (Note: it would be much easier to just call saveForm() with the "Accept" callback function, but this example is provided to demonstrate how to set a polling function with setInterval() and clearInterval().)

getField("saveData").onclick = function() {
 var resp;
 var inter;
  msgBox("Do you want this?", "confirm",
      function(){resp = "yes";}, //Accept callback function
      function(){resp = "no";}   //Cancel callback function
  );
  //set a polling function to check if the user has responded:
  var inter = setInterval(function() {
        if (resp) {    //if the user has responded
           clearInterval(inter); //remove the polling function
           if (resp == "yes")
              saveForm();
        }
     }, 100);  
};

commonDialog()

commonDialog() is a generic function to create custom message boxes to interact with the user.

commonDialog(string type, string title, string text, object buttons, values, object callbackFn)

leimnud.module.app.confirm()

leimnud.module.app.confirm() is used to display a confirmation message to the user. It displays a panel with a question which the user can respond to by clicking on the Accept button or the Cancel button.

new leimnud.module.app.confirm().make( { label: "message", action: functionOnAccept, cancel: functionOnCancel //Optional //...: Any other properties for panels });

Properties:

  • label: A text message with a question for the user. HTML tags can be used to add formatting to the text. Use <br> to add line breaks.
  • action: A named or anonymous function to be executed when the user clicks on the Accept button.
  • cancel: Optional. A named or anonymous function to be executed when the user clicks on the Cancel button.
  • ...: Optional. Any other properties which can be defined for panels.

Note: If needing to check which button was clicked by the user, then set up a polling function with setInterval(). See example 2 below.

Example 1:
When the user clicks on the "SaveButton", check whether the user has selected a client in the "selectClient" dropdown box. If not, then display a confirmation message informing the user that the client is blank and asking whether the form should be saved. If the user clicks on Accept, then an anonymous function is executed which submits the form. If the user clicks on Cancel, then another anonymous function is executed which highlights the blank "selectClient" dropdown box to direct the user's attention to that field.

getField("SaveButton").onclick = function() {
   //if hasn't selected a client, then ask for confirmation to save:
   if (getValueById("selectClient") == "") {
      new leimnud.module.app.confirm().make(
      {
         label:  "No client has been selected.<br><b>Save form?</b>",
         action: function() { submitForm(); },
         cancel: function() { G.highLight(getField("selectClient")); }
      });
   }
   else {
      submitForm();
   }
}

Example 2:
A confirmation message is displayed to ask users if they accept the contract. A polling function is created to check whether the user clicked on Accept or Cancel. Both buttons call anonymous functions to set a value in the response variable. Once the response variable is set, then the polling function is terminated with clearInterval(). If the response is "yes" (accept), then the contract fields are displayed in the DynaForm. If "no" (cancel), then the contract fields are hidden.

var response = null;
//set a polling function to check if the user has responded:
function pollResponse() {
   if (response) {    //if the user has responded
      clearInterval(poll); //remove the polling function
      if (response == "yes") { //user clicked on "Accept"
         showRow("ContractProvisions");
         showRow("ContractType");
      }
      else {                   //user clicked on "Cancel"
         hideRow("ContractProvisions");
         hideRow("ContractType");
      }
   }
}
var poll = setInterval(pollResponse, 100);  
new leimnud.module.app.confirm().make(
{
   label:  "Do you accept this <b>contract</b>?",
   action: function() {response = "yes";},
   cancel: function() {response = "no";}
});

leimnud.module.app.alert()

leimnud.module.app.alert() is used to display a message to the user. It displays a panel with a message with an Accept button below. Set an anonymous or named function to be called when the user clicks on the Accept button.

new leimnud.module.app.alert().make( { label: "message", action: functionOnAccept //Optional //...: Any other properties for panels });

Properties:

  • label: A text message with a question for the user. HTML tags can be used to add formatting to the text. Use <br> to add line breaks.
  • action: Optional. A named or anonymous function to be executed when the user clicks on the Accept button.
  • ...: Optional. Any other properties which can be defined for panels.

Example:
Display the text of a contract to the user after the user clicks on button named "displayContract". When the user clicks on Accept, then hide the "ContractDetails" textbox.

getField("displayContract").onclick = function() {
   new leimnud.module.app.alert().make(
   {
      label:  getValueById('hiddenContractText'),
      action: function() { hiddenById("ContractDetails"); }
   });
}

leimnud.module.app.prompt()

leimnud.module.app.prompt() asks a user to input a value. It displays a panel with a message and a textbox, with Accept and Cancel buttons below.

new leimnud.module.app.alert().make( { label: "message", action: functionOnAccept(enteredValue) //Optional cancel: functionOnCancel //Optional //...: Any other properties for panels });

Properties:

  • label: A text message with a question for the user. HTML tags can be used to add formatting to the text. Use <br> to add line breaks.
  • action: Optional. A named or anonymous function to be executed when the user clicks on the Accept button. Its first parameter will be the value entered into the prompt's textbox by the user.
  • cancel: Optional. A named or anonymous function to be executed when the user clicks on the Cancel button.
  • ...: Optional. Any other properties which can be defined for panels.

Example:
When the DynaForm is displayed, display a prompt for the user to enter the name of a client:

PromptDialog.png

The entered value will be inserted in the "clientName" field, which has a dependent field which is a listbox which searches in the database for the value of the "clientName" with this SQL query:

SELECT ID, CONCAT(FIRSTNAME, ' ', LASTNAME) FROM CLIENTS WHERE FIRSTNAME LIKE '%@#clientName%' OR LASTNAME LIKE '%@#clientName%'

After the entered value is inserted in the "clientName" field, a "change" event is fired for the field to invoke the dependent field search to take place.

new leimnud.module.app.prompt().make(
{
   label:  "Enter a client's name to search:",
   action: function(val) {
      getField("clientName").value = val;
      //cause the dependent field search to happen:
      fireEvent(getField("clientName"), 'change');
   }
});

leimnud.module.panel()

leimnud.module.panel() is used to construct a "panel" which is a generic interface space in the LEIMNUD JavaScript framework. Panels can be used to construct customized dialog boxes with the user.

object leimnud.module.panel()

A LEIMNUD panel can have a number of member properties and methods. Some of the more common ones are listed below. To see the default values for a panel, examine its definition in <INSTALL-DIRECTORY>/gulliver/js/maborak/core/module.panel.js

Member Properties:

  • object options: The options (characteristics) for the panel.
    • array statusBarButtons: An array of button objects to be displayed at the button of the panel.
      • object {value: "button-label"}: An object defining the button.
      • ...
    • object position: An object defining the position of the panel on the screen. It can contain:
      • object {center: boolean}
    • object size: An object defining the width and height of the panel, which contains:
      • object {w: int, h: int}
    • object control: An object defining the controls on the panel, which can contain:
      • object {close: boolean, resize: boolean}
    • object fx: An object defining the functions of the panel, which can contain:
      • object {modal: boolean}:
  • object setStyle: Defines the style properties for the panel.
    • object content: Defines the style content. The following properties can be any appropriate CSS property. Here is a sample:
      • int padding: Pixels of padding between elements and the edges of the panel.
      • int paddingTop: Pixels to pad the top edge of the panel.
      • int paddingBottom: Pixels to pad the bottom edge of the panel.
      • int paddingRight: Pixels to pad the right edge of the panel.
      • int paddingLeft: Pixels to pad the left edge of the panel.
      • string textAlign: Pixels of padding between elements and the edges of the panel.
      • string background: The URL to an image to place in the background.
      • string backgroundRepeat: Set to "no-repeat" or "repeat" to determine whether the background image should be repeated to fill the available space.
      • string backgroundPosition: "Pixels or percentage where the background image should be places. The first number is the left position and the second number is the width of the image.
      • string backgroundColor: A named color or a hexadecimal RGB color. For no color, set to "transparent".
      • int borderWidth: Width of the border in pixels.
  • object elements: Objects in the panel.
  • object event: Define the event handlers for the object's events.

Panel Methods:

  • make(): Displays the panel to the user.
  • remove(): Closes the panel.
  • addContent(string sContent): HTML content to add to the panel.
  • fixContent(): Sets the positions of the elements in the panel, so they will not move afterwords.

Examples:

panel = new leimnud.module.panel();
panel.options={
  statusBarButtons:[
    {value:'yes'},
    {value:'no'},
    {value:'maybe'},
    {value:'cancel'}
  ],
  position:{center:true},
  size:{
    w: 350,
    h: 100
  },
  control:{
    close    :true,
    resize    :false
  },
  fx:{
    modal:true
  }
};
//alert(parent.info.path_images)
panel.setStyle={
  content:{
    padding:10,
    paddingBottom:2,
    textAlign:"left",
    paddingLeft:50,
    background:"url(/images/question.png)",
    backgroundRepeat:"no-repeat",
    backgroundPosition:"10 50%",
    backgroundColor:"transparent",
    borderWidth:0
  }
};
 
panel.make();
panel.addContent("Delete Case?");
panel.fixContent();
panel.elements.statusBarButtons[0].onmouseup=function()
  {
    alert('yes')
    panel.remove();
    return false;
  }.extend(this);
panel.elements.statusBarButtons[1].onmouseup=function()
  {
    alert('da');
    panel.remove();
    return false;
  }.extend(this);
 
panel.elements.statusBarButtons[2].onmouseup=function()
  {
    alert('maybe');
    panel.remove();
    return false;
  }.extend(this);
 
panel.elements.statusBarButtons[3].onmouseup=function()
  {
    alert('cancel');
    panel.remove();
    return false;
  }.extend(this);
 
panel.events = {
  remove: function() {
  }.extend(this)
};

Browser Window Information

getClientWindowSize()

getClientWindowSize() returns the width and height in pixels of the web browser window.

object getClientWindowSize()

Parameters:
None.

Return Value:
An object with the following elements:

  • int width: The width in pixels of the browser window.
  • int height: The height in pixels of the browser window.

Example:
Find the center of the DynaForm:

var dimensions = getClientWindowSize();
var centerH = parseInt(dimensions.height/2)
var centerW = parseInt(dimensions.width/2)

getBrowserClient()

getBrowserClient() returns an object with information about the current browser client

object getBrowserClient()

Parameters:
None.

Return Value:
An object with the following elements:

  • string name: The name of the web browser as reported in navigator.userAgent
  • string browser: A predictable browser name that can be used in script tests. It is one of the following values: "opera", "msie", "firefox", "safari"
  • string version: The version number of the browser.

Note: If using objects/functions which are browser specific, it is not recommended to use getBrowserClient() to decide what code to execute, because browser names can change, future versions of browsers may implement the object/function, and browsers even miss-report their names to ensure greater compatibility.

Example:

var browsType = getBrowserClient().browser;
 if (browsType != "firefox" && browsType != "msie")
     G.alert("Your web browser is not officially supported.", "Incompatible browser");

getAbsoluteLeft()

getAbsoluteLeft() returns the position in pixels of a specified object from left edge of the current frame in the web browser.

int getAbsoluteLeft(object oObject)

Parameters:

Return Value:

  • int: Returns the left position in pixels from the edge of the frame.

Examples:
To get the position of the table holding a grid, use getField() (not getObject() or getGridField()):

var leftPos = getAbsoluteLeft(getField("MyTable"));

To get the position of a particular grid field, use getGridField():

var leftPos = getAbsoluteLeft(getGridField("MyTable", 1, "MyField"));

To get the position of a checkgroup or radiogroup, specify one of the options in the group:

var leftPos = getAbsoluteLeft(getField("MyGroup][MyOption"));

getAbsoluteTop()

getAbsoluteTop() returns the top position in pixels of a specified object from the top edge of the current frame.

int getAbsoluteTop(object oObject)

Parameters:

Return Value:

  • int: Returns the top position in pixels of the object from the top edge of the current frame.

Examples:
To get the position of the table holding a grid, use getField() (not getObject() or getGridField()):

var leftPos = getAbsoluteTop(getField("MyTable"));

To get the position of a particular grid field, use getGridField():

var leftPos = getAbsoluteTop(getGridField("MyTable", 1, "MyField"));

To get the position of a checkgroup or radiogroup, specify one of the options in the group:

var leftPos = getAbsoluteTop(getField("MyGroup][MyOption"));

Miscelaneous Functions

Timer()

Timer() is executes a function after a specified number of seconds. It is similar to the standard setTimeout() function, but its timing is in seconds and it does not return an ID which can be used to cancel the function.

void Timer(object functionName, int time)

Parameters:

  • object functionName: The function to execute after a specified amount of time. This can be a named function or an anonymous function defined on the spot.
  • int time: The number of seconds after which the function will be executed. Note the time is not milliseconds like setTimeout().

Return Value:
None.

Example:
Fill in values in a DynaForm, if the fields haven't been filled within 30 seconds after the DynaForm is loaded:

function autoFillBlanks() {
    if (getValueById("orderQuantity").value == "")
        getField("orderQuantity").value = "5";
 
    if (getValueById("product").value == "")
        getField("product").value = "Big Wipe Erasers";
 }
 Timer(autoFillBlanks, 30);

setNestedProperty()

setNestedProperty() sets a nested DOM (Document Object Model) property.

boolean setNestedProperty(object obj, array propertyName, variant propertyValue)

popUp()

popUp() opens a new browser window with the specified URL and the specified window properties.

void popUp(string URL, int width, int height, int left, int top, boolean resizable)

Parameters:

  • string URL: The address to load in the new window. Like Link fields, if using a relative address, then the address will be appended to "http://<IP-ADDRESS>/sys<WORKSPACE>/<LANG>/<SKIN>/dynaforms/", so use "../url" to back out of the "dynaforms" subdirectory. Examples:
Open the login screen: "../login/login"
Open the cases list in v.2.0: "../cases/main"
Open just the cases list without header in v.2.0: "../cases/casesListExtJs"
Open the cases list in v.1.X: "../cases/cases_List"
  • int width: The width of the new windows in pixels.
  • int height: The height of the new windows in pixels.
  • int left: The position in pixels of the left edge of the window.
  • int top: The position in pixels of the top edge of the window.
  • boolean resizable: Set to true if the window can be resized by the user. Otherwise, set to false.

Return Value:
None.

Example:
Open the cases list in a new window in version 2.0, when the user clicks on a button named "casesButton":

getField("casesButton").onclick = function() {
   popUp("../cases/main", 800, 600, 50, 30, true);
}

Events

fireEvent()

fireEvent() is a cross-browser function which fires an event for a specified element. It is basically a wrapper for the fireEvent() method in Internet Explorer and the dispatchEvent() method in FireFox and other DOM Level 2 compliant browsers.

boolean fireEvent(object element, string event)

Parameters:

  • object element: An object on which the event will be fired. Use the getField() function to obtain an object reference for a DynaForm field. To reference the whole DynaForm use: getField("field-name").form
  • string event: The name of the event which will be fired. There are many possible events, but the most common are: "click", "change", "focus", "blur", "keypress", "keydown", "keyup", "mousedown", "mouseup", "mouseover", "mouseout", "load" and "unload".

Return value:

  • boolean: Returns true if the event was successfully fired. If unsuccessfully fired (or if the event's default action was cancelled in FireFox), it returns false.

Examples:
When a user marks a checkbox named "setDueDate", then fire a "click" event on the date picker button for a date field named "dueDate", so the date picker dialog will appear:

function showDatePicker() {
    if (getField("setDueDate").checked == true)
        fireEvent(getElementById("form[dueDate][btn]"), "click");  
 }
 getField("setDueDate").onchange = showDatePicker;

In this example, the "selectRegion" dropdown box is a dependent field and the "selectCountry" is its independent field. When setting the value of "selectCountry", also fire a "change" event, so that its dependent field will requery the database and repopulated its list of options.

Code running on Internet Explorer Browsers:

getField("includeMoreInfo").attachEvent('onchange', function() {
  getField("selectCountry").value = "USA";
  fireEvent(getField("selectCountry"), 'change');  
});

Code running on all of browser but Internet Explorer:

getField("includeMoreInfo").addEventListener('change', function() {
  getField("selectCountry").value = "USA";
  fireEvent(getField("selectCountry"), 'change');  
});

leimnud.event.add()

Leimnud is a Javascript framework developed by Wilmer, a member of the ProcessMaker development team. Leimnud can be used to add event handlers to JavaScript events:

void leimnud.event.add(object field, string event, object function);

Parameters:

  • object field: The field name is the name of the field in wich the user can do any action that causes it to fire an event .
  • object function: The function that will be executed when the event happens. This can either be an anonymous function defined on the spot or a named function defined elsewhere.
  • string event: The name of the event which will be handled by the function. There are many possible events, but the most common are: "click", "change", "focus", "blur", "keypress", "keydown", "keyup", "mousedown", "mouseup", "mouseover", "mouseout", "load" and "unload".

Return value:

  • void: It does not return any value.

Example:
As a named function:

function alertUser() {
    alert("Please select a client.");
    focusById("selectClient");
 }
 leimnud.event.add(getField("mybutton"), "click", alertUser);

As an anonymous function:

leimnud.event.add(getField("mybutton"), "click", function() {
    alert("Please select a client.");
    focusById("selectClient");
 });

Variables to control DynaForms

dynaformOnload

dynaformOnload is a custom variable used by ProcessMaker to execute a function after a DynaForm finishes loading. To use this variable, define a function and then assign a reference to that function to dynaformOnload.

For example, a DynaForm to request a company purchase will check whether the purchase price is greater than the maximum purchase limit. If it is over the limit, then the purchase price will automatically be reduced to the maximum purchase limit:

function checkDefaultValues()
 {
    var price = parseFloat(getField("PurchasePrice").value);
    var limit = parseFloat(getField("PurchaseLimit").value);  
    if (price > limit)
    {
       getField("PurchasePrice").value = limit;
       document.getDocumentById("WarningLabel").innerHTML =
          '<font color="red">Reduced Purchase Price to maximum limit</font>';  
    }
 }
 var dynaformOnload = checkDefaultValues;

DynaForm special fields

Process UID

The unique ID (UID) of the Process can be useful if needing to redirect to another location using JavaScript or save it in a hidden field. To obtain the Process UID, use the following JavaScript code:

var processUid = getField("field-name").form.name.split('_')[0];

Change "field-name" to the name of a field in the DynaForm.

Before version 2.5.0, the Process UID is also stored in a hidden field named "form[PRO_UID]".

Example before version 2.5.0:

var processUid = getValueById("PRO_UID");

DynaForm UID

The unique ID (UID) of the DynaForm can be useful if needing to redirect to another location using JavaScript or save it in a hidden field. To obtain the DynaForm's UID, use the following JavaScript code:

var dynaformUid = getField("field-name").form.name.split('_')[1];

Change "field-name" to the name of a field in the DynaForm.

Before version 2.5.0, the DynaForm's UID is also stored in a hidden field named "form[DYN_UID]".

Example before version 2.5.0:

var dynaformUid = getValueById("DYN_UID");

DynaformRequiredFields

The "DynaformRequiredFields" hidden field holds information about the writable fields in a DynaForm, which are not part of a grid. The information is stored as an array of objects with the properties for each field, which has been serialized as a JSON string. This string can be decoded with the eval()eval() function (or JSON.parse() in recent web browsers). In version 2.5.X and later, the format of this string has been URI encoded, so it first must be decoded with the decodeURIComponent() function. This array of objects is available for reference, but changing it will not change which fields are checked to make sure that they are not blank when clicking on a DynaForm's submit button. This field can also be used with the validateForm() function.

Example before version 2.5.0:
To see information about the required fields in a master DynaForm:

alert(var_dump(eval(document.getElementById("DynaformRequiredFields").value)));

Example in version 2.5.0 and later:

var requiredFields = eval(decodeURIComponent(document.getElementById("DynaformRequiredFields").value));