Note:

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

Form API: Difference between revisions

From MoodleDocs
(Added in the usage for within blocks)
m (Protected "Form API": Developer Docs Migration ([Edit=Allow only administrators] (indefinite)))
 
(16 intermediate revisions by 11 users not shown)
Line 1: Line 1:
{{Template:Migrated|newDocId=/docs/apis/subsystems/form/}}
==Overview==
==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.
[https://en.wikipedia.org/wiki/Form_(HTML) Web forms] in Moodle are created using the Form API. The Form API supports all HTML elements (checkboxes, radio buttons, text boxes, etc), with improved accessibility and security.
==Highlights==
==Highlights==
# Tested and optimised for use on major screen-readers Dragon and JAWS.  
# Tested and optimised for use on major screen-readers like Dragon and JAWS.
# Tableless layout.
# Tableless layout.
# Process form data securely, with required_param, optional_param and session key.
# Processes form data securely, with required_param, optional_param and session key.
# Supports client-side validation
# Supports client-side validation.
# Facility to add Moodle help buttons to forms.  
# Facility to add Moodle help buttons to forms.  
# Support for file repository using [[File_API]]
# Support for file repository using [[File_API]] .
# Support for many custom moodle specific and non-specific form elements.
# Support for many custom Moodle specific and non-specific form elements.
# Addition for repeated elements.
# Facility for [https://docs.moodle.org/dev/lib/formslib.php_repeat_elements repeated elements].
# Addition for form elements in advance group
# Facility for form elements in advanced group
 
==Usage==
==Usage==
For creating a form in moodle, you have to create class extending moodleform class and override [https://docs.moodle.org/dev/lib/formslib.php_Form_Definition#definition.28.29 definition] for including form elements.
To create a form in Moodle, you have to create a class that extends the moodleform class and overrides the [https://docs.moodle.org/dev/lib/formslib.php_Form_Definition#definition.28.29 definition] member function for including form elements.
<code php>
<syntaxhighlight lang="php">
//moodleform is defined in formslib.php
//moodleform is defined in formslib.php
require_once("$CFG->libdir/formslib.php");
require_once("$CFG->libdir/formslib.php");
Line 25: Line 25:
         $mform = $this->_form; // Don't forget the underscore!  
         $mform = $this->_form; // Don't forget the underscore!  


         $mform->addElement('text', 'email', get_string('email')); // Add elements to your form
         $mform->addElement('text', 'email', get_string('email')); // Add elements to your form.
         $mform->setType('email', PARAM_NOTAGS);                  //Set type of element
         $mform->setType('email', PARAM_NOTAGS);                  // Set type of element.
         $mform->setDefault('email', 'Please enter email');        //Default value
         $mform->setDefault('email', 'Please enter email');        // Default value.
             ...
             ...
     }
     }
Line 35: Line 35:
     }
     }
}
}
</code>
</syntaxhighlight>
Then instantiate form (in this case simplehtml_form) on your page.
Then instantiate the form (in this case simplehtml_form) on your page.
<code php>
<syntaxhighlight lang="php">
//include simplehtml_form.php
//include simplehtml_form.php
require_once('PATH_TO/simplehtml_form.php');
require_once('PATH_TO/simplehtml_form.php');
Line 58: Line 58:
   $mform->display();
   $mform->display();
}
}
</code>
</syntaxhighlight>
 
If you wish to use the form within a block then you should consider using the render method, as demonstrated below:
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.
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.
 
<syntaxhighlight lang="php">
<code php>
class block_yourblock extends block_base{
class block_yourblock extends block_base{
public function init(){
public function init(){
Line 96: Line 94:
}
}
}
}
</code>
</syntaxhighlight>
 
==Form elements==
==Form elements==
===Basic form elements===
===Basic form elements===
Line 111: Line 108:
# [https://docs.moodle.org/dev/lib/formslib.php_Form_Definition#text text]
# [https://docs.moodle.org/dev/lib/formslib.php_Form_Definition#text text]
# [https://docs.moodle.org/dev/lib/formslib.php_Form_Definition#textarea textarea]
# [https://docs.moodle.org/dev/lib/formslib.php_Form_Definition#textarea textarea]
 
# [https://docs.moodle.org/dev/lib/formslib.php_Form_Definition#Use_Fieldsets_to_group_Form_Elements header]
===Custom form elements===
=== Advanced form elements===
# [https://docs.moodle.org/dev/lib/formslib.php_Form_Definition#autocomplete Autocomplete] - A select box that allows you to start typing to narrow the list of options, or search for results.
# [https://docs.moodle.org/dev/lib/formslib.php_Form_Definition#autocomplete Autocomplete] - A select box that allows you to start typing to narrow the list of options, or search for results.
# [https://docs.moodle.org/dev/lib/formslib.php_Form_Definition#advcheckbox advcheckbox] - Advance checkbox
# [https://docs.moodle.org/dev/lib/formslib.php_Form_Definition#advcheckbox advcheckbox] - Advance checkbox
# [https://docs.moodle.org/dev/lib/formslib.php_Form_Definition#float float]
# [https://docs.moodle.org/dev/lib/formslib.php_Form_Definition#passwordunmask passwordunmask] - A password element with option to show the password in plaintext.
# [https://docs.moodle.org/dev/lib/formslib.php_Form_Definition#passwordunmask passwordunmask] - A password element with option to show the password in plaintext.
# [https://docs.moodle.org/dev/lib/formslib.php_Form_Definition#recaptcha recaptcha]
# [https://docs.moodle.org/dev/lib/formslib.php_Form_Definition#recaptcha recaptcha]
Line 132: Line 130:
# [https://docs.moodle.org/dev/lib/formslib.php_Form_Definition#grading grading]
# [https://docs.moodle.org/dev/lib/formslib.php_Form_Definition#grading grading]
# [https://docs.moodle.org/dev/lib/formslib.php_Form_Definition#questioncategory questioncategory]
# [https://docs.moodle.org/dev/lib/formslib.php_Form_Definition#questioncategory questioncategory]
===Custom form elements===
If you need a custom form element you can dynamical register new elements and then use them like this:
<syntaxhighlight lang="php">
    MoodleQuickForm::registerElementType('course_competency_rule',
                                        "$CFG->dirroot/$CFG->admin/tool/lp/classes/course_competency_rule_form_element.php",
                                        'tool_lp_course_competency_rule_form_element');
    // Reuse the same options.
    $mform->addElement('course_competency_rule', 'competency_rule', get_string('uponcoursemodulecompletion', 'tool_lp'), $options);
</syntaxhighlight>
See:
https://github.com/moodle/moodle/blob/master/admin/tool/lp/lib.php#L157-L161


https://github.com/moodle/moodle/blob/master/admin/tool/lp/classes/course_competency_rule_form_element.php
==Commonly used functions==
==Commonly used functions==
====add_action_buttons($cancel = true, $submitlabel=null);====
====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'''
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'''
 
<syntaxhighlight lang="php">
<code php>
   $this->add_action_buttons();
   $this->add_action_buttons();
</code>
</syntaxhighlight>
 
====[[lib/formslib.php_Form_Definition#setDefault_2|setDefault()]]====
====[[lib/formslib.php_Form_Definition#setDefault_2|setDefault()]]====
To set the default value for an element.
To set the default value for an element.
 
====[[lib/formslib.php_Form_Definition#disabledIf|disabledIf()]]====
====[[lib/formslib.php_Form_Definition#disabledIf|disableif()]]====
For any element or groups of element in a form you can conditionally disable the group or individual element depending on conditions.
For any element or groups of element in a form you can conditionally disable the group or individual element depending on conditions.
 
====[[lib/formslib.php_Form_Definition#hideIf|hideif()]]====
For any element or groups of element in a form you can conditionally hide the group or individual element depending on conditions.
Same syntax as disabledIf. Can do a simple search and replace on disabledIf. Added in Moodle 3.4.
====[[lib/formslib.php_Form_Definition#addRule|addRule()]]====
====[[lib/formslib.php_Form_Definition#addRule|addRule()]]====
Add rule for server/client side validation. Like text field is required element and is of type email.
Add rule for server/client side validation. Like text field is required element and is of type email.
 
====setHelpButton()====
====[[lib/formslib.php_Form_Definition#setHelpButton|setHelpButton()]]====
DEPRECATED - Sets pop-up help button to a form element. Use addHelpButton() instead.
Sets pop-up help button to a form element.
 
====[[lib/formslib.php_Form_Definition#addHelpButton|addHelpButton()]]====
====[[lib/formslib.php_Form_Definition#addHelpButton|addHelpButton()]]====
Adds pop-up help button to a form element
Adds pop-up help button to a form element
====[[lib/formslib.php_Form_Definition#setType|setType()]]====
====[[lib/formslib.php_Form_Definition#setType|setType()]]====
PARAM_* types are used to specify how a submitted variable should be cleaned.
PARAM_* types are used to specify how a submitted variable should be cleaned.
====[[lib/formslib.php_Form_Definition#disable_form_change_checker|disable_form_change_checker()]]====
====[[lib/formslib.php_Form_Definition#disable_form_change_checker|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 <tt>$mform->disable_form_change_checker()</tt>.
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 <tt>$mform->disable_form_change_checker()</tt>.
==FAQ==
==FAQ==
[https://docs.moodle.org/dev/lib/formslib.php_Form_Definition#Use_Fieldsets_to_group_Form_Elements How to group elements]
[https://docs.moodle.org/dev/lib/formslib.php_Form_Definition#Use_Fieldsets_to_group_Form_Elements How to group elements]
==See also==
==See also==
* [[Core_APIs]]
* [[Core_APIs]]
* [[lib/formslib.php_Usage]]  
* [[lib/formslib.php_Usage]]  
Line 173: Line 177:
* [[Designing usable forms]]
* [[Designing usable forms]]
* [[Fragment]]
* [[Fragment]]
 
* [[MForm_Modal]]
[[Category:API]]
[[Category:API]]

Latest revision as of 06:40, 17 June 2022

Important:

This content of this page has been updated and migrated to the new Moodle Developer Resources. The information contained on the page should no longer be seen up-to-date.

Why not view this page on the new site and help us to migrate more content to the new site!

Overview

Web forms in Moodle are created using the Form API. The Form API supports all HTML elements (checkboxes, radio buttons, text boxes, etc), with improved accessibility and security.

Highlights

  1. Tested and optimised for use on major screen-readers like Dragon and JAWS.
  2. Tableless layout.
  3. Processes 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. Facility for repeated elements.
  9. Facility for form elements in advanced group

Usage

To create a form in Moodle, you have to create a class that extends the moodleform class and overrides the definition member function 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 the 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
  12. header

Advanced 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. float
  4. passwordunmask - A password element with option to show the password in plaintext.
  5. recaptcha
  6. selectyesno
  7. selectwithlink
  8. date_selector
  9. date_time_selector
  10. duration
  11. editor
  12. filepicker - upload single file
  13. filemanager - upload multiple files
  14. tags
  15. addGroup
  16. modgrade
  17. modvisible
  18. choosecoursefile
  19. grading
  20. questioncategory

Custom form elements

If you need a custom form element you can dynamical register new elements and then use them like this:


    MoodleQuickForm::registerElementType('course_competency_rule',
                                         "$CFG->dirroot/$CFG->admin/tool/lp/classes/course_competency_rule_form_element.php",
                                         'tool_lp_course_competency_rule_form_element');
    // Reuse the same options.
    $mform->addElement('course_competency_rule', 'competency_rule', get_string('uponcoursemodulecompletion', 'tool_lp'), $options);

See:

https://github.com/moodle/moodle/blob/master/admin/tool/lp/lib.php#L157-L161

https://github.com/moodle/moodle/blob/master/admin/tool/lp/classes/course_competency_rule_form_element.php

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.

disabledIf()

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

hideif()

For any element or groups of element in a form you can conditionally hide the group or individual element depending on conditions. Same syntax as disabledIf. Can do a simple search and replace on disabledIf. Added in Moodle 3.4.

addRule()

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

setHelpButton()

DEPRECATED - Sets pop-up help button to a form element. Use addHelpButton() instead.

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