** Get Your Free Totara Demo Now! **

How to modify Moodle form elements before displaying the form

Forms in Moodle are both easy and hard to deal with. Easy, when you stick to standard form elements, without any solution specific modifications or design changes. And hard, when you have to break with standards or do some specific things with data.

We’re going to look into how to modify form elements before form is rendered on clients browser. Specifically, when you need to check or uncheck an element under some condition that not necessary is handled by Moodle code.

Moodle is giving you a definition_after_data method for manipulating displayed data or form elements, like checking or unchecking checkboxes, setting different default values etc.

Enough talking, let’s see sample code for block configuration definition:

[sourcecode language=”php”]
class block_yourblock_edit_form extends block_edit_form {
protected function specific_definition($mform) {

$mform->addElement(‘header’, ‘general’, ‘Header’);
$mform->addElement(‘advcheckbox’, "config_checkbox", $repository->name);
$mform->setType("config_checkbox", PARAM_BOOL);

$mform->addElement(‘text’, ‘config_text’, ‘Some text input’);

} // specific_definition

public function definition_after_data() {
parent::definition_after_data();

$mform =& $this->_form;
$config_text =& $mform->getElement(‘config_text’);
$config_checkbox =& $mform->getElement(‘config_checkbox’);

if (isset($config_checkbox->_attributes[‘checked’])) {
$config_text->attributes[‘value’] = "The checkbox is checked";
} // if

} // definition_after_data
} // class
[/sourcecode]

definition_after_data() method must call parent method before start manipulating form data. This method is available in all form classes (see formslib.php in lib directory) and it’s called after definition(), data submission and set_data().

We found it a great way to manipulate form when form is dependent on the form values or unusual conditions.

Another useful hint for manipulating group of elements using definition_after_data:

[sourcecode language=”php”]$group_of_elements =& $mform->getElement(‘some_group_of_elements’)->getElements();[/sourcecode]

You can also experiment with element visibility, adding css, etc.

June 3, 2014 In: Blog Written by: Grzegorz (Greg) Adamowicz

Leave a Reply