Disabling Form Elements in Moodle/Totara

|
| By Webner

Here we will discuss how to disable form elements based on conditions in moodle/totara.

We are creating a form in moodle/totara by extending “moodleform” class and overriding the definition() method to including the form elements.

For example:

form elements
If you want to disable any checkbox element by checking PHP variable value, then you can do this during the element creation time:

$isDisabled = true;
if($isDisabled){ // you can pass “disabled” property as an attributes array
 	$attrArray = array('disabled' => 'disabled');
$mform->addElement('checkbox', 'checkbox2', get_string('checkbox1') ,'',$attrArray);
}

When you want to disable any element depending on the conditions for instance after checking the value of another element in form, you can call disabledIf() function in the following way:

$mform->disabledIf(<elementname>, $dependentOn, $condition = 'checked', $value='1');
  • <elementname> In this, we specify the element name of that element which we want to disable. It can take multiple elements as a group. Moreover, if you want to specify a group, all elements in the group will be disabled.
  • dependentOn is the name of the element on which we are checking conditions. Based on this element value, we will disable the <eventname> element.
  • $condition will be ‘notchecked’, ‘checked’, ‘noitemselected’, ‘eq’ and ‘in’.
    • If $condition is ‘eq’ or ‘neq’ then we check the value of the dependentOn field and check for equality (==) or nonequality (!=) in js.
    • If $condition is ‘checked’ or ‘notchecked’ then we check to see if a checkbox is checked or not.
    • If $condition is ‘in’ then we check to see if a selected item is in the given list or not.
    • If $condition is ‘noitemselected’ then we check to fond out whether nothing is selected in a dropdown list.

Examples:
Now we will create two checkboxes named as “checkbox1” and “checkbox2” and one dropdown element named as “gender”.

  $mform->addElement('checkbox', 'checkbox1', get_string('checkbox1'));
  $mform->addElement('checkbox', 'checkbox2', get_string('checkbox1'));
 $gender = array(
        	0 => ‘Male’,
                	1 => ‘Female’
    	);
$mform->addElement('select', 'gender', get_string('gender', 'sequence'), $gender);

1. Now, we want to disable ‘checkbox2’ when ‘checkbox1’ is checked. For this we will invoke disableif() as below:

 	$mform->disabledIf('checkbox2', 'checkbox1', 'checked');

2. Disable ‘checkbox2’ when a dropdown ‘gender’ has value ‘Male’.

$mform->disabledIf('checkbox2', ‘gender’, 'eq', ‘Male’);

3. Disable ‘checkbox2’ unless a dropdown ‘gender’ has value ‘Male’.

$mform->disabledIf('checkbox2', ‘gender’, 'neq', ‘Male’);

Leave a Reply

Your email address will not be published. Required fields are marked *