Note:

If you want to create a new page for developers, you should create it on the Moodle Developer Resource site.

lib/formslib.php Form Definition

From MoodleDocs

definition()

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() 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 definition 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.

Note that the definition function is called when the form class is instantiated. There is no option to (say) manipulate data in the class (that may affect the rendering of the form) between instantiating the form and calling any other methods.

require_once("$CFG->libdir/formslib.php");

class simplehtml_form extends moodleform {

    function definition() {
        global $CFG;
       
        $mform = $this->_form; // Don't forget the underscore! 

        $mform->addElement()... // Add elements to your form
            ...
    }                           // Close the function
}                               // Close the class

Passing parameters to the Form

The constructor for moodleform allows a number of parameters including one ($customdata) to permit an array of arbitrary data to be passed to your form.

For example, you can pass the data "$email" and "$username" to the Form's class for use inside (say) the definition.

...
 $mform_simple = new simplehtml_form( null, array('email'=>$email, 'username'=>$username ) );
...

(the first parameter is $action, null will cause the form action to be determined automatically)

Secondly, inside the form definition you can use those parameters to set the default values to some of the form's fields

...
 $mform->addElement('text', 'email', get_string('email'), 'maxlength="100" size="25" ');
 $mform->setType('email', PARAM_NOTAGS);
 $mform->addRule('email', get_string('missingemail'), 'required', null, 'server');
 // Set default value by using a passed parameter
 $mform->setDefault('email',$this->_customdata['email']);
...

Use Fieldsets to group Form Elements

You use code like this to open a fieldset with a legend.
(Note: Some themes turn off legends on admin setting pages by using CSS: #adminsettings legend {display:none;}.)

$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.

Moodle 2.5

Since Moodle 2.5 fieldsets without any required fields are collapsed by default. To display these fieldsets on page load, use:

 $mform->setExpanded('foo')

To close a fieldset on page load, use:

 $mform->setExpanded('foo', false)


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) :

$mform->closeHeaderBefore('buttonar');

addElement

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 :

button

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

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


autocomplete

Moodle 3.1

Available since Moodle 3.1

$searchareas = \core_search\manager::get_search_areas_list(true);                                                           
$areanames = array();                                                                                                       
foreach ($searchareas as $areaid => $searcharea) {                                                                          
    $areanames[$areaid] = $searcharea->get_visible_name();                                                                  
}                                                                                                                           
$options = array(                                                                                                           
    'multiple' => true,                                                  
    'noselectionstring' => get_string('allareas', 'search'),                                                                
);         
$mform->addElement('autocomplete', 'areaids', get_string('searcharea', 'search'), $areanames, $options);

The autocomplete element is an advanced form element that supports server-side searching - or simple filtering of a predefined list of options. Some benefits of using this form element are that it handles very large datasets extremely well - it has great accessibility built in - and it gives a good user experience. If you have so much data you need to build pagination into a page - you could probably come up with a better design using this. The simplest way to use it is compatible with the standard 'select' form element. You give it a list of options and some parameters to configure how it behaves. The valid parameters for this simple mode of operation are:

  • multiple (boolean - default false) - Allow more than one selected item. The data coming from the form will be an array in this case.
autocomplete with multiple option
autocomplete with multiple option.
  • noselectionstring (string - default '') - The text to display when nothing is selected.
  • showsuggestions (boolean - default true) - Do not show the list of suggestions when the user starts typing.
  • placeholder (string - default '') - The text to show in the search box when it is empty.
  • casesensitive (boolean - default false) - Is the search case sensitive ?
  • tags (boolean - default false) - This changes the behaviour so that the user can create new valid entries in the list by typing them and pressing enter.
  • ajax (string - default '') - This string is the name of an AMD module that can fetch and format results.
  • valuehtmlcallback - For use with the AJAX option, so that it can format the initial value of the form field (available since Moodle 3.5)

More explanation on the 'ajax' option. This should be the name of an AMD module that implements 2 functions:

/**                                                                                                                         
 * Source of data for Ajax element.
 *
 * @param {String} selector The selector of the auto complete element.
 * @param {String} query The query string.                        
 * @param {Function} callback A callback function receiving an array of results.
 * @param {Function} failure A callback function to be called in case of failure, receiving the error message.
 * @return {Void}                                                                                                           
*/                                                                                                                         
transport: function(selector, query, callback, failure) ...

/**                                                                                                                         
 * Process the results for auto complete elements.                                                                          
 *                                                                                                                          
 * @param {String} selector The selector of the auto complete element.                                                      
 * @param {Array} results An array or results.                                                                              
 * @return {Array} New array of results.                                                                                    
 */                                                                                                                         
processResults: function(selector, results)...

A good example is here: admin/tool/lp/amd/src/frameworks_datasource.js

The 'valuehtmlcallback' function is needed when an AJAX-supporting form field has an initial value that needs special rendering, similar to how the AJAX code would render it when the user changes it dynamically. For example, if the field contains user ids and its initial value is '1,2' then you want it to use the rendered HTML display for each value (probably a user's name and picture), not just display those numbers. Here is an example, from /search/classes/output/form/search.php:

'valuehtmlcallback' => function($value) {
    global $DB, $OUTPUT;
    $user = $DB->get_record('user', ['id' => (int)$value], '*', IGNORE_MISSING);
    if (!$user || !user_can_view_profile($user)) {
        return false;
    }
    $details = user_get_user_details($user);
    return $OUTPUT->render_from_template(
        'core_search/form-user-selector-suggestion', $details);
}

The Mustache template used here is the same as the one used by the AJAX code when the field is changed dynamically.

When using the ajax option in an mform with validation etc - it is recommended to sub-class the php class "MoodleQuickForm_autocomplete" so that you can provide a list of name and values to populate the form element if the form is re-displayed due to a validation error. An example is admin/tool/lp/classes/form/framework_autocomplete.php.

We have provided several useful subclasses of this form element already that are simple to use (course and tags).

 
    // Course example.
    //  Valid options are:                                                                                     
    //                       'multiple' - boolean multi select                                                                      
    //                       'exclude' - array or int, list of course ids to never show                                             
    //                       'requiredcapabilities' - array of capabilities. Uses ANY to combine them.                              
    //                       'limittoenrolled' - boolean Limits to enrolled courses.                                                
    //                       'includefrontpage' - boolean Enables the frontpage to be selected.  
    $options = array('multiple' => true, 'includefrontpage' => true);                                                           
    $mform->addElement('course', 'mappedcourses', get_string('courses'), $options); 

    // Tags
    //  Valid options are:                                                                                     
    //                       'showstandard' - boolean One of the core_tag_tag constants to say which tags to display
    //                       'component' - string The component name and itemtype define the tag area
    //                       'itemtype' - string The component name and itemtype define the tag area
    $mform->addElement('tags', 'interests', get_string('interestslist'), array('itemtype' => 'user', 'component' => 'core'));

checkbox

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

This is a simple checkbox. The third parameter for this element is the label to display on the left side of the form. You can also supply a string as a fourth parameter 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.

You can have a 5th parameter $attributes, as on other elements.

BEWARE: Unchecked checkboxes return nothing at all (as if they didn't exist). This can surprise the unwary. You may wish to use advcheckbox instead, which does return a value when not checked. 'Advcheckbox' eliminates this problem.

advcheckbox

$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 some important improvements:

  1. The (optional) 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 (optional) 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.
  3. It returns a 0 value when unchecked. Compare with the ordinary checkbox which does not return anything at all.

choosecoursefile

Moodle1.9

$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.

Note: This has been superceded by filepicker in Moodle 2.

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'

You can also pass an optional 5th parameter of attributes, as for other elements. The most useful way of using that is something like

array('maxlength' => 255, 'size' => 48)

to control the maxlength / size of the text box (note size will default to 48 if not specified)

Finally, as this element is a group containing two elements (button + value), you can add validation rules by using the addGroupRule() method in this (complex) way:

$mform->addGroupRule('elementname', array('value' => array(array(list, of, rule, params, but, fieldname))));

Where: "elementname" is the name of the choosecoursefile group element, "value" is the name of the text field within the group and the "list, of, addrule, params, but, fieldname" is exactly that, the list of fields in the normal addRule() function but ommiting the first one, the fieldname.

For example, the file/url resource type, uses one "choosecoursefile" element, and it controls the maximum length of the field (255) with this use of addGroupRule():

$mform->addGroupRule('reference', array('value' => array(array(get_string('maximumchars', '', 255), 'maxlength', 255, 'client'))));

date_selector

$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,
    '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.

date_time_selector

$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,
    'step'      => 5,
    '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. Setting 'optional' to true adds an 'enable' checkbox to the selector. You can supply a fifth param of attributes here as well.

duration

Moodle 2.0


        $mform->addElement('duration', 'timelimit', get_string('timelimit', 'quiz'));

This field type lets the user input an interval of time. It comprises a text field, where you can type a number, and a dropdown for selecting a unit (days, hours, minutes or seconds). When submitted the value is converted to a number of seconds.

You can add a fourth parameter to give options. At the moment the only option supported is here is an array of options. The defaults for the options is:

array('optional' => true)

You can also pass an optional 5th parameter of attributes, as for other elements. The most useful way of using that is something like

array('size' => 5)

to control the size of the text box.

editor

This replaces the old htmleditor field type. It allows the user to enter rich text content in a variety of formats.

$mform->addElement('editor', 'fieldname', get_string('labeltext', 'langfile'));
$mform->setType('fieldname', PARAM_RAW);

NOTE: It won't work properly without the setType() as shown.

If you would like to let the user use the filepicker to upload images etc. that are used in the content, then see Using_the_File_API_in_Moodle_forms.

You can supply a fifth param to htmleditor of an array of options that are mostly related to file handling:

array(
    'subdirs'=>0,
    'maxbytes'=>0,
    'maxfiles'=>0,
    'changeformat'=>0,
    'context'=>null,
    'noclean'=>0,
    'trusttext'=>0,
    'enable_filemanagement' => true);

The option 'enable_filemanagement' will display the file management button on true and remove it on false.

To save the data if you don't care about files:

$formdata = $mform->get_data();
$text     = $formdata->fieldname['text'];
$format   = $formdata->fieldname['format'];

Note: Because the text editor might be "Atto" (depending on user preferences) and Atto has an "autosave" feature - it requires that the combination of $PAGE->url and this elementid are unique. If not, the autosaved text for a different form may be restored into this form.

file

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()) {
      ...
    $mform->save_files($destination_directory);
      ...
}

If there is no requirement to save the file, you can read the file contents directly into a string as follows...

    $mform->get_file_content('attachment');

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()) {
      ...
    $mform->save_files($destination_directory);
    $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.

filepicker

Moodle 2.0


General replacement of file element.

$mform->addElement('filepicker', 'userfile', get_string('file'), null, array('maxbytes' => $maxbytes, 'accepted_types' => '*'));

See also Using the File API in Moodle forms

hidden

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

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

html

You can add arbitrary HTML to your Moodle form:

$mform->addElement('html', '<div class="qheader">');

See "Question: Can I put a moodleform inside a table td?" for a concrete example.

htmleditor & format

These elements are now deprecated. Please use the editor field type instead.

modgrade

$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.

modvisible

$mform->addElement('modvisible', 'visible', get_string('visible'));

This is a custom element for selecting a grade visibility in an activity mod update form.

password

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

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

passwordunmask

Moodle1.9

$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.

radio

Moodle 2.3

$radioarray=array();
$radioarray[] = $mform->createElement('radio', 'yesno', '', get_string('yes'), 1, $attributes);
$radioarray[] = $mform->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.

Since 2.3 it cannot be statically called anymore, so we need to call createElement from $mform reference.

setDefault

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

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

This would make the default 'no'.

select

$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.

It is also possible to create a select with certain options disabled, using this technique.

You can set an 'onchange' attribute when adding or creating the select element:

$form->addElement('select', 'iselTest', 'Test Select:', $arrayOfOptions, array('onchange' => 'javascript:myFunctionToDoSomething();'));


multi-select

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

To set the default selected item in a select element, you can use the 'setSelected' method. The 'setSelected' can either get a value or an array of values.

$options = array(
    'ff0000' => 'Red',
    '00ff00' => 'Green',
    '0000ff' => 'Blue'
);
$select = $mform->addElement('select', 'colors', get_string('colors'), $options);
// This will select the colour blue.
$select->setSelected('0000ff');

Or for multiple-selection:

$skillsarray = array(
    'val1' => 'Skill A',
    'val2' => 'Skill B',
    'val3' => 'Skill C'
);
$mform->addElement('select', 'md_skills', get_string('skills', 'metadata'), $skillsarray);
$mform->getElement('md_skills')->setMultiple(true);
// This will select the skills A and B.
$mform->getElement('md_skills')->setSelected(array('val1', 'val2'));

However you probably don't want to do this. Instead you probably want to use setDefault, or set it using the form's setData method.

selectyesno

$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.

selectwithlink

$options = array();
$mform->addElement('selectwithlink', 'scaleid', get_string('scale'), $options, null, 
    array('link' => $CFG->wwwroot.'/grade/edit/scale/edit.php?courseid='.$COURSE->id, 'label' => get_string('scalescustomcreate')));

select type element with options containing link

static

$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 if 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=array();
$buttonarray[] = $mform->createElement('submit', 'submitbutton', get_string('savechanges'));
$buttonarray[] = $mform->createElement('reset', 'resetbutton', get_string('revert'));
$buttonarray[] = $mform->createElement('cancel');
$mform->addGroup($buttonarray, 'buttonar', '', ' ', 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'). Note the $this not $mform

$this->add_action_buttons();

text

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

For a simple text input element. (For text labels, use the 'static' element.) Your fourth parameter here can be a string or array of attributes for the text element. The following are equivalent :

$attributes='size="20"';
$attributes=array('size'=>'20');

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

float

Moodle 3.7

$mform->addElement('float', 'defaultmark', get_string('defaultmark', 'question'), $attributes);

Use the float element if you want a text box to get a floating point number. This element automatically supports localised decimal separators. You don't need to use setType with the float element.

textarea

$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.

recaptcha

Moodle1.9

$mform->addElement('recaptcha', '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 http://recaptcha.net/api/getkey before using this element.

To check whether recaptcha is enabled at site level use:

if (!empty($CFG->recaptchapublickey) && !empty($CFG->recaptchaprivatekey)) {
    //recaptcha is enabled
}

tags

Moodle 2.0


$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.

grading

$mform->addElement('grading', 'advancedgrading', get_string('grade').':', array('gradinginstance' => $gradinginstance));

Custom element for advanced grading plugins.

When adding the 'grading' element to the form, developer must pass an object of class gradingform_instance as $attributes['gradinginstance']. Otherwise an exception will be thrown.

questioncategory

$mform->addElement('questioncategory', 'category', get_string('category', 'question'),
    array('contexts'=>$contexts, 'top'=>true, 'currentcat'=>$currentcat, 'nochildrenof'=>$currentcat));

Creates a drop down element to select a question category.

Options are: contexts - (required) context in which question appears currentcat - (optional) course category top - (optional) if true will put top categories on top nochildrenof - (optional) Format categories into an indented list reflecting the tree structure

filetypes

Moodle 3.4

Available since Moodle 3.4

$mform->addElement('filetypes', 'allowedfiletypes', get_string('allowedfiletypes', 'tool_myplugin'));

Creates an input element allowing the user to specify file types for the given purpose. The typical scenario is a setting that allows the teacher define a list of allowed file types submitted by students.

The element allows the user to either type the list of filetypes manually, or select the types from the list. Also supported is selecting the whole group of file types - such as "image". The element integrates with the Core filetypes system so all default types and groups are presented, as well as those defined locally by the admin.

As the list can be types in manually, the form processing code should always normalize it first via the provided utility methods:

$formdata = $mform->get_data();
$filetypesutil = new \core_form\filetypes_util();
$allowedfiletypes = $filetypesutil->normalize_file_types($formdata->allowedfiletypes);

This always returns an array of recognized valid values. The original list can be separated by whitespace, end of lines, commas, colons and semicolons. During the normalization, values are converted to lowercase, empty valies and duplicates are removed. Glob evaluation is not supported.

The normalization should also happen if the previously defined list had been saved to the database and re-read for actual usage. The normalization output value can be directly used as the accepted_types option for the filepicker.

$filetypesutil = new \core_form\filetypes_util();
$options['accepted_types'] = $filetypesutil->normalize_file_types($allowedfiletypes);

By default, user input is validated against the list of known file types and groups. This validation can be disabled via options.

Supported options

onlytypes
Allow selection from these file types only; for example ['onlytypes' => ['web_image']].
allowall
Allow to select 'All file types', defaults to true. Does not apply with onlytypes are set.
allowunknown
Skip implicit validation against the list of known file types.

Example:

$mform->addElement('filetypes', 'doctypes', get_string('doctypes', 'tool_myplugin'), ['onlytypes' => ['document'], 'allowunknown' => true]);

addGroup

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=array();
$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 a bad example (don't do this for real, use the 'optional' => true option of the date element): 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=array();
$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');
  • If you want to put a group inside another array so that you can repeat items, use createElement instead of addGroup:
$group = $mform->createElement('group', 'groupname', get_string('label'), $groupitems);
  • By default, groups modify the names of elements inside them by appending a number. This is often unhelpful, for example if you want to use disabledIf on the element. To prevent this behaviour, set the last parameter to false when creating a group.:
$group = $mform->createElement('group', 'groupname', get_string('label'), $groupitems, null, false);

addRule

$mform->addRule('elementname', get_string('error'), 'rule type', 'extraruledata', 'server'(default), false, false);

The first param(element) is an element name and second(message) is the error message that will be displayed to the user. The third parameter(type) is the type of rule. The fourth param(format) is used for extra data needed with some rules such as minlength and regex. The fifth parameter(validation) validates input data on server or client side, if validation is done on client side then it will be checked on the server side as well.

 * @param    string     $element       Form element name
 * @param    string     $message       Message to display for invalid data
 * @param    string     $type          Rule type, use getRegisteredRules() to get types
 * @param    string     $format        (optional)Required for extra rule data
 * @param    string     $validation    (optional)Where to perform validation: "server", "client"
 * @param    boolean    $reset         Client-side validation: reset the form element to its original value if there is an error?
 * @param    boolean    $force         Force the rule to be applied, even if the target form element does not exist

Common Rule Types

  • required
  • maxlength
  • minlength
  • rangelength
  • email
  • regex
  • lettersonly
  • alphanumeric
  • numeric
  • nopunctuation
  • nonzero
  • callback
  • compare

Server side and Client side

In case you use the Client side validation option, you can mainly check for an empty or not input field. unless you write some Client side code which will probably be JavaScript functions to verify the data inside the input fields before it is submitted to the server. It could save some time if those functions are short, simple and quick to compute. In case you need a more complex validation checks which relay on Moodle's internal PHP libraries (or other/external PHP libraries) you better use the Server side validation checks. Where you can query the DB, write complex PHP validation functions and much much more, that are not available (easily) when using JavaScript on the client's side.

addHelpButton

$mform->addHelpButton('api_key_field', 'api_key', 'block_extsearch');

The following parameters are expected:

/**
 * @param $elementname The name of the form element to add the help button for
 * @param $identifier The identifier for the help string and its title (see below)
 * @param $component The component name to look for the help string in
 */
  1. get_string($identifier, $component) // The title of the help page
  2. get_string("{$identifier}_help", $component) // The content of the help page

So you will need to have $identifier and {$identifier}_help defined in order for the help button to be created properly. For example the multiple choice question editing form has a button for shuffling the answers.

$mform->addHelpButton('shuffleanswers', 'shuffleanswers', 'qtype_multichoice');

and so the language file includes the strings

$string['shuffleanswers'] = 'Shuffle the choices?'; 
$string['shuffleanswers_help'] = 'If enabled,.....';

You can also add the language string like

$string['shuffleanswers_link'] = 'question/shuffleanswers';

to add a link to more help on Moodle docs. See String_API for more information about help icons.

setDefault

$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.

$mform->addElement('editor', 'desc', get_string('description'));     
$mform->setDefault('desc', array('text'=>$defaulttext));

Note that when setting the default for an editor element you must use an array to define the default "text" value as shown above.

disabledIf

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='1')

  • 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 second 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', 'noitemselected', 'eq', 'in' or, if it is anything else, 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 'in' then we check to see if a selected item is in the given list or not. (This was introduced in Moodle 2.7+)
    • If $condition is 'noitemselected' then we check to see whether nothing is selected in a dropdown list.

Examples:

// 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 when a dropdown has value 42.
$mform->disabledIf('mycontrol', 'someselect', 'eq', 42);
// Disable my control unless a dropdown has value 42.
$mform->disabledIf('mycontrol', 'someselect', 'neq', 42);

The possible choices here are in the dependency manager in lib/form/form.js.

A tricky case

You need to take care with disabledIf if you plan to use it with groups of checkboxes.

Let's say you have a group of 5 checkboxes and you want to enable a depending item such as a drop down menu only when the first and the last checkboxes are selected.

To fix ideas:

If the selection in the checkboxes group is:

mycheck_01 == 1
mycheck_02 == 0
mycheck_03 == 0
mycheck_04 == 0
mycheck_05 == 1

the depending item must be enabled while ANY OTHER COMBINATION must disable the drop down menu.

The following code will, apparently, fail:

$mform->disabledIf('dropdownmenu', 'mycheck_01', 'neq', '1');
$mform->disabledIf('dropdownmenu', 'mycheck_02', 'neq', '0');
$mform->disabledIf('dropdownmenu', 'mycheck_03', 'neq', '0');
$mform->disabledIf('dropdownmenu', 'mycheck_04', 'neq', '0');
$mform->disabledIf('dropdownmenu', 'mycheck_05', 'neq', '1');

In fact, once you get the drop down menu enabled, you are free to unselect mycheck_01 whilst still having the depending item enabled. This apparent bug occurs because a non-checked checkbox behaves like a non existing mform element. So the js code will not find the element "mycheck_01" and will not apply the corresponding rule.

A working solution for this kind of issue seems to be:

$mform->disabledIf('dropdownmenu', 'mycheck_01', 'notchecked');
$mform->disabledIf('dropdownmenu', 'mycheck_02', 'checked');
$mform->disabledIf('dropdownmenu', 'mycheck_03', 'checked');
$mform->disabledIf('dropdownmenu', 'mycheck_04', 'checked');
$mform->disabledIf('dropdownmenu', 'mycheck_05', 'notchecked');

To see a failing example as the one described, try the attachments provided in MDL-38975. See also in MDL-38975 for the working solution in action with modifications suggested by Eloy.

hideIf

Moodle 3.4

For any element or groups of element in a form you can conditionally hide the group or individual element depending on conditions. This uses the same syntax as disabledIf just with hideIf instead.

setType

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. For the full list, see the file lib/moodlelib.php.

  • 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 contain multi-lang content. 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 *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_FLOAT is also available for decimal numbers but is not recommended for user input since it does not work for languages that use , as a decimal separator.

These types are deprecated:

  • PARAM_CLEAN obsoleted, please use a more specific type of parameter. @deprecated since 2.0
  • PARAM_ACTION deprecated alias for PARAM_ALPHA use for various actions in forms and urls. Use PARAM_ALPHANUMEXT instead.

disable_form_change_checker

By default, any Moodle form will pop-up an "Are you sure?" alert if you make some changes and then try to leave the page without saving. Occasionally, that is undesirable, in which case you can call

$mform->disable_form_change_checker()

RTL support

Moodle 3.2


As of Moodle 3.2, some form elements have been refined to better support right-to-left languages. In RTL, most fields should not have their direction flipped, a URL, a path to a file, a number, ... are always displayed LTR. Input fields and text areas now will best guess whether they should be forced to be displayed in LTR based on the PARAM type associated with it. You can call:

$mform->setForceLtr('name', true/false);

on some form fields (like 'text') to manually set the value, and for directionality.

References