Dynamic required fields when options are selected

From pmusers
Jump to: navigation, search

Use JavaScript to make fields required or not required depending on the options selected in a checkgroup.



DynaForm: Required from checkgroup options.json (right click and select Save link as)
Author: Amos Batto (amos@processmaker.com)
Version: 1.0 (2018-05-23)
Tested in: ProcessMaker 3.2.1 Community in Debian 8.4 with Firefox 51



Create a DynaForm with the following fields:

  • Checkgroup with the ID "selectEmployeeChange"
  • Text field with the ID "newTitle"
  • Text field with the ID "newSalary"
  • Dropdown with the ID "employmentType"

checkgroupOptionsForm.png

Note that the required property must be marked in the fields, because the enableValidation() and disableValidation() methods won't work on fields that do not have their required properties marked.

Then, add the following JavaScript to the DynaForm:

function setRequiredFields(aOptions) {
  if (aOptions.indexOf('title_change') != -1)
    $("#newTitle").enableValidation();
  else
    $("#newTitle").disableValidation();
  
  if (aOptions.indexOf('pay_change') != -1)
    $("#newSalary").enableValidation();
  else
    $("#newSalary").disableValidation();
  
  if (aOptions.indexOf('employment_type') != -1)
    $("#employmentType").enableValidation();
  else
    $("#employmentType").disableValidation();
}

//execute when selected options change in "Employee Changes" checkgroup:
$("#selectEmployeeChange").setOnchange( function(aNewOpts, aOldOpts) {
  setRequiredFields(aNewOpts);
});

setRequiredFields( $("#selectEmployeeChange").getValue() ); //execute when Dynaform loads

The setRequiredFields() function is called both when the DynaForm is first loaded and when the selected options are changed in the "selectEmployeeChange" checkgroup. setOnchange() returns an array of the selected options in the checkgroup, so the indexOf() function is used to search for an option in the array. If it returns -1, then the option's value wasn't found and it wasn't selected in the checkgroup.

Depending on which options are selected in the "selectEmployeeChange" checkgroup, the fields below it are set as required or not required:

requiredWhenOptionsSelected.png