lib/formslib.php Form Definition

Revision as of 08:34, 27 February 2009 by Daniele Cordella (talk | contribs) (recaptcha)

Jump to: navigation, search


The definition of the elements to be included in the form, their 'types' (PARAM_*), helpbuttons included, etc is all included in a function you must define in your class 'definition();'

definition() is used to define the elements in the form and this definition will be used for validating data submitted as well as for printing the form. For select and checkbox type elements only data that could have been selected will be allowed. And only data that corresponds to a form element in the defintion will be accepted as submitted data.

The definition() should include all elements that are going to be used on form, some elements may be removed or tweaked later in definition_after_data(). Please do not create conditional elements in definition(), the definition() should not directly depend on the submitted data.

Use Fieldsets to group Form Elements

You use code like this to open a fieldset with a legend.

        $mform->addElement('header', 'nameforyourheaderelement', get_string('titleforlegened', 'modulename'));

You can't yet nest these visible fieldsets unfortunately. But in fact groups of elements are wrapped in invisible fieldsets.

You close a fieldset with moodle_form's closeHeaderBefore method. You tell closeHeaderBefore the element before you wish to end the fieldset. A fieldset is automatically closed if you open a new one. You need to use this code only if you want to close a fieldset and the subsequent form elements are not to be enclosed by a visible fieldset (they are still enclosed with an invisibe one with no legend) :



Use the addElement method to add an element to a form. The first few arguments are always the same. The first param is the type of the element to add. The second is the elementname to use which is normally the html name of the element in the form. The third is often the text for the label for the element.

Some examples are below :


            $mform->addElement('button', 'intro', get_string("buttonlabel"));

A button element. If you want a submit or cancel button see 'submit' element.


        $mform->addElement('checkbox', 'ratingtime', get_string('ratingtime', 'forum'));

This is a simple checkbox. The third param for this element is the label to display on the left side of the form. You can also supply a string as a fourth param to specify a label that will appear on the right of the element. Checkboxes and radio buttons can be grouped and have individual labels on their right.


        $mform->addElement('advcheckbox', 'ratingtime', get_string('ratingtime', 'forum'), 'Label displayed after checkbox', array('group' => 1), array(0, 1));

Similar to the checkbox above, but with a couple of important improvements:

  1. The 5th parameter is a normal $attributes array, normally used to set HTML attributes for the <input> element. However, a special value of 'group' can be given, which will add a class name to the element, and enable its grouping for a checkbox controller
  2. The 6th parameter is an array of values that will be associated with the checked/unchecked state of the checkbox. With a normal checkbox you cannot choose that value, and in fact an unchecked checkbox will not even be sent with the form data.


        $mform->addElement('choosecoursefile', 'mediafile', get_string('mediafile', 'lesson'), array('courseid'=>$COURSE->id));

Choose a file from the course files area. The fourth option is a list of options for the element.

array('courseid'=>null,//if it is null (default then use global $COURSE
 'height'=>500,// height of the popup window
 'width'=>750, // width of the popup window
'options'=>'none');//options string for the pop up window 
                   //eg. 'menubar=0,location=0,scrollbars,resizable'


        $mform->addElement('date_selector', 'assesstimefinish', get_string('to'));

This is a date selector. You can select a Day, Month and Year using a group of select boxes. The fourth param here is an array of options. The defaults for the options are :

array('startyear'=>1970, 'stopyear'=>2020,
                    'timezone'=>99, 'applydst'=>true, 'optional'=>false);

You can override these defaults by supplying an array as fourth param with one or more keys with a value to override the default. You can supply a fifth param of attributes here as well.


        $mform->addElement('date_time_selector', 'assesstimestart', get_string('from'));

This is a group of select boxes to select a date (Day Month and Year) and time (Hour and Minute). When submitted, submitted data is processed and a timestamp is passed to $form->get_data(); the fourth param here is an array of options. The defaults for the options are:

array('startyear'=>1970, 'stopyear'=>2020,
                    'timezone'=>99, 'applydst'=>true, 'step'=>5);

You can override these defaults by supplying an array as fourth param with one or more keys with a value to override the default. You can supply a fifth param of attributes here as well.


File upload input box with browse button. In the form definition type

            $mform->addElement('file', 'attachment', get_string('attachment', 'forum'));

after form submission and validation use

            if ($data = $mform->get_data()) {

If you need advanced settings such as required file, different max upload size or name of uploaded file

            $this->set_upload_manager(new upload_manager('attachment', true, false, $COURSE, false, 0, true, true, false));
            $mform->addElement('file', 'attachment', get_string('attachment', 'forum'));
            $mform->addRule('attachment', null, 'required');

            if ($data = $mform->get_data()) {
              $newfilename = $mform->get_new_filename();

When porting old code it is also possible to use the upload manager directly for processing of uploaded files.

Please note that if using set_upload_manager() it must be before addElement('file',..).

Moodle 2.0

File uploading was rewritten in 2.0. Please see inline docs for now. This page will be updated when the new API stabilises.


Moodle 2.0

General replacement of file element.


         $mform->addElement('hidden', 'reply', 'yes');

A hidden element. Set the element name (in this case reply) to the stated value (in this case yes).

htmleditor & format

        $mform->addElement('htmleditor', 'text', get_string('choicetext', 'choice'));
        $mform->setType('text', PARAM_RAW);
	$mform->addRule('text', null, 'required', null, 'client');

        $mform->addElement('format', 'format', get_string('format'));

You can supply a fourth param to htmleditor of an array of options :

array('canUseHtmlEditor'=>'detect','rows'=>10, 'cols'=>65, 
'width'=>0,'height'=>0, 'course'=>0);
//options same as print_textarea params
//use rows and cols options to control htmleditor size.


        $mform->addElement('modgrade', 'scale', get_string('grade'), false);

This is a custom element for selecting a grade for any activity module. The fourth argument is whether to include an option for no grade which has a value 0. This select box does include scales. The default is true, include no grade option.

A helpbutton is automatically added.


         $mform->addElement('password', 'password', get_string('label'), $attributes);

A password element. Fourth param is an array or string of attributes.



         $mform->addElement('passwordunmask', 'password', get_string('label'), $attributes);

A password element with option to show the password in plaintext. Fourth param is an array or string of attributes.


        $radioarray[] = &MoodleQuickForm::createElement('radio', 'yesno', '', get_string('yes'), 1, $attributes);
        $radioarray[] = &MoodleQuickForm::createElement('radio', 'yesno', '', get_string('no'), 0, $attributes);
        $mform->addGroup($radioarray, 'radioar', '', array(' '), false);

Second param names the radio button and should be the same for each button in the group in order to toggle correctly. Third param would be the label for the form element but is generally ignored as this element will always be in a group which has it's own label. Fourth param is a string, a label to be displayed on the right of the element. The fifth is the value for this radio button. $attributes can be a string or an array of attributes.

It is possible to add help to individual radio buttons but this requires a custom template to be defined for the group elements. See MDL-15571.


To set the default for a radio button group as above use the following :

        $mform->setDefault('yesno', 0);

This would make the default 'no'.


        $mform->addElement('select', 'type', get_string('forumtype', 'forum'), $FORUM_TYPES, $attributes);

The fourth param for this element is an array of options for the select box. The keys are the values for the option and the value of the array is the text for the option. The fifth param $attributes is optional, see text element for description of attributes param.


        $select = &$mform->addElement('select', 'colors', get_string('colors'), array('red', 'blue', 'green'), $attributes);


        $mform->addElement('selectyesno', 'maxbytes', get_string('maxattachmentsize', 'forum'));

If you want a yes / no select box this one automatically translates itself and has value 1 for yes and 0 for no.


         $mform->addElement('static', 'description', get_string('description', 'exercise'),
                  get_string('descriptionofexercise', 'exercise', $COURSE->students));

This is a static element. It should be used with care it is used to display a static piece of text with a label. The third param is the label and the fourth is the static text itself.

submit, reset and cancel

        //normally you use add_action_buttons instead of this code
        $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
        $buttonarray[] = &$mform->createElement('reset', 'resetbutton', get_string('revert'));
        $buttonarray[] = &$mform->createElement('cancel');
        $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);

A 'Submit' type element is a submit type form element which will submit the form. A 'Reset' will not submit the form but will reset any changes the user has made to form contents. A 'Cancel' element cancels form submission. You need to have a branch in your code before you check for get_data() to check if submission has been cancelled with is_cancelled(); See the example on the usage page.

You should name your submit and reset buttons 'submitbutton' and 'resetbutton' or something similar (not 'submit' and 'reset'). This avoids problems in JavaScript of collisions between form element names and names of JavaScript methods of the form object.

add_action_buttons($cancel = true, $submitlabel=null);

You will normally use this helper function which is a method of moodleform to add all the 'action' buttons to the end of your form. A boolean parameter allow you to specify whether to include a cancel button and specify the label for your submit button (pass the result of get_string). Default for the submit button label is get_string('savechanges').


        $mform->addElement('text', 'name', get_string('forumname', 'forum'), $attributes);

For a simple text element. Your fourth parameter here can be a string or array of attributes for the text element. The following are equivalent :


Generally you are encouraged to use CSS instead of using attributes for styling.

A format element can be used as a format select box. It will be non-selectable if you're using an html editor.

The third param for this element is $useHtmlEditor and it defaults to null in which case an html editor is used if the browser and user profile support it.


            $mform->addElement('textarea', 'introduction', get_string("introtext", "survey"), 'wrap="virtual" rows="20" cols="50"');

A textarea element. If you want an htmleditor use htmleditor element. Fourth element here is a string or array of attributes.


            $mform->addElement('recaptcha', 'field_name', $attributes);

Use this recaptcha element to reduce the spam risk in your forms. Third element here is a string or array of attributes. Take care to get an API key from before using this element.

To validate the recaptcha element add the following code to the function validation($data) { in your form: if (!empty($CFG->recaptchapublickey) && !empty($CFG->recaptchaprivatekey)) { // alias if recaptcha is enabled

   $recaptcha_element = $this->_form->getElement('recaptcha_element');
   if (!empty($this->_form->_submitValues['recaptcha_challenge_field'])) {
       $challenge_field = $this->_form->_submitValues['recaptcha_challenge_field'];
       $response_field = $this->_form->_submitValues['recaptcha_response_field'];
       if (true !== ($result = $recaptcha_element->verify($challenge_field, $response_field))) {
           $errors['recaptcha_element'] = $result;
   } else {
       $errors['recaptcha_element'] = get_string('missingrecaptchachallengefield');



Moodle 2.0+ only.

            $mform->addElement('tags', 'field_name', $lable, $options, $attributes);

Used for editing a list of tags, for example on a blog post.

There is only one option available, 'display', which should be set to one of the contstants MoodleQuickForm_tags::ONLYOFFICIAL, NOOFFICIAL or DEFAULTUI. This controls whether the official tags are listed for easy selection, or a text area where arbitrary tags may be typed, or both. The default is both.

The value should be set/returned as an array of tags.


A 'group' in formslib is just a group of elements that will have a label and will be included on one line.

For example typical code to include a submit and cancel button on the same line :

        $buttonarray[] =& $mform->createElement('submit', 'submitbutton', get_string('savechanges'));
        $buttonarray[] =& $mform->createElement('submit', 'cancel', get_string('cancel'));
        $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);

You use the same arguments for createElement as you do for addElement. Any label for the element in the third argument is normally ignored (but not in the case of the submit buttons above where the third argument is not for a label but is the text for the button).

Here's an example of putting a date_selector (which is itself a group of elements) and a checkbox on the same line, note that you can disable every element in the group using the group name 'availablefromgroup' but it doesn't disable the controlling element the 'availablefromenabled' checkbox:

	$availablefromgroup[] =& $mform->createElement('date_selector', 'availablefrom', '');
	$availablefromgroup[] =& $mform->createElement('checkbox', 'availablefromenabled', '', get_string('enable'));
        $mform->addGroup($availablefromgroup, 'availablefromgroup', get_string('availablefromdate', 'data'), ' ', false);
        $mform->disabledIf('availablefromgroup', 'availablefromenabled');


            $mform->setHelpButton('lessondefault', array('lessondefault', get_string('lessondefault', 'lesson'), 'lesson'));

First param is an elementname and the second param is an array of params that are passed to helpbutton in weblib.php. Params are :

 * @param string $page  The keyword that defines a help page
 * @param string $title The title of links, rollover tips, alt tags etc
 *           'Help with' (or the language equivalent) will be prefixed and '...' will be stripped.
 * @param string $module Which module is the page defined in
 * @param mixed $image Use a help image for the link?  (true/false/"both")
 * @param boolean $linktext If true, display the title next to the help icon.
 * @param string $text If defined then this text is used in the page, and
 *           the $page variable is ignored.
 * @param boolean $return If true then the output is returned as a string, if false it is printed to the current page.
 * @param string $imagetext The full text for the helpbutton icon. If empty use default help.gif

Make sure you don't set boolean $return to false.

You need to do use this method after addElement();


        $mform->addElement('select', 'grade', get_string('gradeforsubmission', 'exercise'), $grades);
        $mform->setHelpButton('grade', array('grade', get_string('gradeforsubmission', 'exercise'), 'exercise'));
        $mform->setDefault('grade', 100);

Set the default of the form value with setDefault($elementname, $value); where elementname is the elementname whose default you want to set and $value is the default to set. We set the defaults for the form in definition(). This default is what is used if no data is loaded into the form with set_data(); eg. on display of the form for an 'add' rather than 'update' function.


For any element or groups of element in a form you can conditionally disable the group or individual element depending on conditions.

You can use $mform->disabledIf($elementName, $dependentOn, $condition = 'notchecked', $value=null)

  • elementname can be a group. If you specify a group all elements in the group will be disabled (if dependentOn is in elementname group that is ignored and not disabled). These are the element names you've used as the first argument in addElement or addGroup.
  • dependentOn is the actual name of the element as it will appear in html. This can be different to the name used in addGroup particularly but also addElement where you're adding a complex element like a date_selector. Check the html of your page. You typically make the depedentOn a checkbox or select box.
  • $condition will be notchecked, checked, selected, eq or if it is anything else then we test for neq.
  • 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 selected then we check to see if a particular option is selected from a dropdown list.


// Disable my control unless a checkbox is checked.
$mform->disabledIf('mycontrol', 'somecheckbox');

// Disable my control if a checkbox is checked.
$mform->disabledIf('mycontrol', 'somecheckbox', 'checked');

// Disable my control unless a dropdown has value 42.
$mform->disabledIf('mycontrol', 'someselect', 'eq', 42);

Note: I am not sure this section is complete. I just found and added one missing case, but there may be others--Tim Hunt 06:04, 15 October 2007 (CDT)


PARAM_* types are used to specify how a submitted variable should be cleaned. These should be used for get parameters such as id, course etc. which are used to load a page and also with setType(); method. Every form element should have a type specified except select, radio box and checkbox elements, these elements do a good job of cleaning themselves (only specified options are allowed as user input).

Most Commonly Used PARAM_* Types

These are the most commonly used PARAM_* types and their proper uses. More types can be seen in moodlelib.php starting around line 100.

  • PARAM_CLEAN is deprecated and you should try to use a more specific type.
  • PARAM_TEXT should be used for cleaning data that is expected to be plain text. It will strip all html tags. But will still let tags for multilang support through.
  • PARAM_NOTAGS should be used for cleaning data that is expected to be plain text. It will strip *all* html type tags. It will still *not* let tags for multilang support through. This should be used for instance for email addresses where no multilang support is appropriate.
  • PARAM_RAW means no cleaning whatsoever, it is used mostly for data from the html editor. Data from the editor is later cleaned before display using format_text() function. PARAM_RAW can also be used for data that is validated by some other way or printed by p() or s().
  • PARAM_INT should be used for integers.
  • PARAM_ACTION is an alias of PARAM_ALPHA and is used for hidden fields specifying form actions.