Dynamic required fields

From pmusers
Jump to: navigation, search

Use JavaScript to make the "selectProducts" checkgroup required (i.e., at least one option is selected) when the "requiredProduct" checkbox field is marked. When it isn't marked, then the checkgroup is not required.


DynaForm: Dynamic required field.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 the following DynaForm with a checkbox whose ID is "requireProducts" and a checkgroup whose ID is "selectProducts":

dynamicRequiredForm.png

Note that the required property must be marked in the checkgroup, 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 setRequired(newVal, oldVal) {
  if (newVal == "1" || newVal == '"1"') {
    $("#selectProducts").enableValidation();
  } else {
    $("#selectProducts").disableValidation();
  }
}

$("#requireProducts").setOnchange(setRequired); //execute when value of checkbox changes
setRequired( $("#requireProducts").getValue(), ''); //execute when form loads

The setRequired() function is called both when the DynaForm is first loaded and when the value of the "requireProducts" checkbox changes. When the getValue() method is called, it will return "1" (if marked) or "0" (if not marked). However, the setOnchange() method will show the value of the checkbox as '"1"' (if marked) or '"0"' (if not marked). For this reason, it is necessary to check for both possibilities in the following line:

if (newVal == "1" || newVal == '"1"') {

When the "requireProducts" checkbox is marked, then the "selectProducts" checkgroup is required:

FieldRequiredWhenCheckboxMarked.png

And when it is not marked, the "selectProducts" checkgroup is not required:

FieldNotRequiredWhenCheckboxNotMarked.png