Difference between revisions of "Form API"

From MoodleDocs
m (Text replacement - "<code php>" to "<syntaxhighlight lang="php">")
 
(8 intermediate revisions by 6 users not shown)
Line 9: Line 9:
 
# 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.
+
# Addition for [https://docs.moodle.org/dev/lib/formslib.php_repeat_elements repeated elements].
 
# Addition for form elements in advance group
 
# Addition for form elements in advance 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.
 
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.
<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 35: Line 35:
 
     }
 
     }
 
}
 
}
</code>
+
</syntaxhighlight>
 
Then instantiate form (in this case simplehtml_form) on your page.
 
Then instantiate 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:
Line 64: Line 64:
 
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.
  
<code php>
+
<syntaxhighlight lang="php">
 
class block_yourblock extends block_base{
 
class block_yourblock extends block_base{
 
public function init(){
 
public function init(){
Line 96: Line 96:
 
}
 
}
 
}
 
}
</code>
+
</syntaxhighlight>
  
 
==Form elements==
 
==Form elements==
Line 111: Line 111:
 
# [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]
 +
 +
=== Advanced form elements===
  
===Custom 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 135:
 
# [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==
Line 139: Line 161:
 
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'''
  
<code php>
+
<syntaxhighlight lang="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()]]====
Line 156: Line 178:
 
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.
  
====[[lib/formslib.php_Form_Definition#setHelpButton|setHelpButton()]]====
+
====setHelpButton()====
Sets pop-up help button to a form element.
+
DEPRECATED - Sets pop-up help button to a form element.  Use addHelpButton() instead.
  
 
====[[lib/formslib.php_Form_Definition#addHelpButton|addHelpButton()]]====
 
====[[lib/formslib.php_Form_Definition#addHelpButton|addHelpButton()]]====

Latest revision as of 13:34, 14 July 2021

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