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
(11 intermediate revisions by 9 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


Line 57: Line 57:
   //displays the form
   //displays the form
   $mform->display();
   $mform->display();
}
</code>
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.
<code php>
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;
}
}
}
</code>
</code>
Line 62: Line 100:
==Form elements==
==Form elements==
===Basic form elements===
===Basic form elements===
# [https://docs.moodle.org/dev/lib/formslib.php_Form_Definition#autocomplete button]
# [https://docs.moodle.org/dev/lib/formslib.php_Form_Definition#button button]
# [https://docs.moodle.org/dev/lib/formslib.php_Form_Definition#button button]
# [https://docs.moodle.org/dev/lib/formslib.php_Form_Definition#checkbox checkbox]
# [https://docs.moodle.org/dev/lib/formslib.php_Form_Definition#checkbox checkbox]
Line 74: 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]


===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#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 94: 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:
<code>
    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);
</code>
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 108: Line 168:
To set the default value for an element.
To set the default value for an element.


====[[lib/formslib.php_Form_Definition#disabledIf|disableif()]]====
====[[lib/formslib.php_Form_Definition#disabledIf|disabledIf()]]====
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.


====[[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()]]====
Line 135: Line 199:
* [[Designing usable forms]]
* [[Designing usable forms]]
* [[Fragment]]
* [[Fragment]]
* [[MForm_Modal]]


[[Category:API]]
[[Category:API]]

Revision as of 10:23, 12 December 2020

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