Form API

Jump to: navigation, search

Overview

Web Forms in moodle are created using forms API. Form API supports all html elements (checkbox, radio, textbox etc), with improved accessibility and security.

Highlights

  1. Tested and optimised for use on major screen-readers Dragon and JAWS.
  2. Tableless layout.
  3. Process form data securely, with required_param, optional_param and session key.
  4. Supports client-side validation
  5. Facility to add Moodle help buttons to forms.
  6. Support for file repository using File_API
  7. Support for many custom moodle specific and non-specific form elements.
  8. Addition for repeated elements.
  9. Addition for form elements in advance group

Usage

For creating a form in moodle, you have to create class extending moodleform class and override definition for including form elements.

//moodleform is defined in formslib.php
require_once("$CFG->libdir/formslib.php");
 
class simplehtml_form extends moodleform {
    //Add elements to form
    public function definition() {
        global $CFG;
 
        $mform = $this->_form; // Don't forget the underscore! 
 
        $mform->addElement('text', 'email', get_string('email')); // Add elements to your form
        $mform->setType('email', PARAM_NOTAGS);                   //Set type of element
        $mform->setDefault('email', 'Please enter email');        //Default value
            ...
    }
    //Custom validation should be added here
    function validation($data, $files) {
        return array();
    }
}

Then instantiate form (in this case simplehtml_form) on your page.

//include simplehtml_form.php
require_once('PATH_TO/simplehtml_form.php');
 
//Instantiate simplehtml_form 
$mform = new simplehtml_form();
 
//Form processing and displaying is done here
if ($mform->is_cancelled()) {
    //Handle form cancel operation, if cancel button is present on form
} else if ($fromform = $mform->get_data()) {
  //In this case you process validated data. $mform->get_data() returns data posted in form.
} else {
  // this branch is executed if the form is submitted but the data doesn't validate and the form should be redisplayed
  // or on the first display of the form.
 
  //Set default data (if any)
  $mform->set_data($toform);
  //displays the form
  $mform->display();
}

If you wish to use the form within a block then you should consider using the render method, as demonstrated below:

Note that the render method does the same as the display method, except returning the HTML rather than outputting it to the browser, as with above make sure you've included the file which contains the class for your Moodle form.

class block_yourblock extends block_base{
	public function init(){
		$this->title = 'Your Block';
	}
	public function get_content(){
 
		$this->content = new stdClass();
		$this->content->text = '';
 
		$mform = new simplehtml_form();
 
		//Form processing and displaying is done here
		if ($mform->is_cancelled()) {
			//Handle form cancel operation, if cancel button is present on form
		} else if ($fromform = $mform->get_data()) {
			//In this case you process validated data. $mform->get_data() returns data posted in form.
		} else {
			// this branch is executed if the form is submitted but the data doesn't validate and the form should be redisplayed
			// or on the first display of the form.
 
			//Set default data (if any)
			$mform->set_data($toform);
 
			//displays the form
			$this->content->text = $mform->render();
		}
 
		return $this->content;
 
	}
}

Form elements

Basic form elements

  1. button
  2. checkbox
  3. radio
  4. select
  5. multi-select
  6. password
  7. hidden
  8. html - div element
  9. static - Display a static text.
  10. text
  11. textarea

Custom form elements

  1. Autocomplete - A select box that allows you to start typing to narrow the list of options, or search for results.
  2. advcheckbox - Advance checkbox
  3. passwordunmask - A password element with option to show the password in plaintext.
  4. recaptcha
  5. selectyesno
  6. selectwithlink
  7. date_selector
  8. date_time_selector
  9. duration
  10. editor
  11. filepicker - upload single file
  12. filemanager - upload multiple files
  13. tags
  14. addGroup
  15. modgrade
  16. modvisible
  17. choosecoursefile
  18. grading
  19. questioncategory

Commonly used functions

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();

setDefault()

To set the default value for an element.

disableif()

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

addRule()

Add rule for server/client side validation. Like text field is required element and is of type email.

setHelpButton()

Sets pop-up help button to a form element.

addHelpButton()

Adds pop-up help button to a form element

setType()

PARAM_* types are used to specify how a submitted variable should be cleaned.

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

FAQ

How to group elements

See also