<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
	<id>https://docs.moodle.org/dev/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Marcojones</id>
	<title>MoodleDocs - User contributions [en]</title>
	<link rel="self" type="application/atom+xml" href="https://docs.moodle.org/dev/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Marcojones"/>
	<link rel="alternate" type="text/html" href="https://docs.moodle.org/dev/Special:Contributions/Marcojones"/>
	<updated>2026-06-06T02:40:05Z</updated>
	<subtitle>User contributions</subtitle>
	<generator>MediaWiki 1.43.5</generator>
	<entry>
		<id>https://docs.moodle.org/dev/index.php?title=Creating_a_web_service_client&amp;diff=55451</id>
		<title>Creating a web service client</title>
		<link rel="alternate" type="text/html" href="https://docs.moodle.org/dev/index.php?title=Creating_a_web_service_client&amp;diff=55451"/>
		<updated>2019-01-14T16:13:14Z</updated>

		<summary type="html">&lt;p&gt;Marcojones: /* Simple REST request example */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Moodle_2.0}}&lt;br /&gt;
[[Image:Moodle web service function documentation.jpg|thumb]]You need to know how to [https://docs.moodle.org/en/How_to_create_and_enable_a_web_service setup a web service] first.&lt;br /&gt;
To see the API Documentation, connect as Admin and go to &#039;&#039;&#039;Administration &amp;gt; Plugins &amp;gt; Web services &amp;gt; API Documentation&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
== Simple REST request example ==&lt;br /&gt;
&lt;br /&gt;
To quickly test the web service works you can visit the end point from the browser or via curl. For example to call a function via REST protocol:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
$ curl &amp;quot;https://your.site.com/moodle/webservice/rest/server.php?wstoken=...&amp;amp;wsfunction=...&amp;amp;moodlewsrestformat=json&amp;quot;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Customise the parameters &amp;lt;tt&amp;gt;wstoken&amp;lt;/tt&amp;gt; and &amp;lt;tt&amp;gt;wsfunction&amp;lt;/tt&amp;gt; to match the server side setup. Append additional parameters for the function call as needed with &amp;quot;&amp;amp;parameter_name=param&amp;quot;, or if your parameter is an array then use &amp;quot;&amp;amp;array_name[index][parameter_name]=param&amp;quot;. With the core_user_create_users function&#039;s (required) parameters for example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
$ curl &amp;quot;...&amp;amp;moodlewsrestformat=json&amp;amp;wsfunction=core_user_create_users&amp;amp;moodlewsrestformat=json&amp;amp;users[0][username]=testuser&amp;amp;users[0][firstname]=Anne&amp;amp;users[0][lastname]=Example...&amp;quot;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The &amp;lt;tt&amp;gt;moodlewsrestformat&amp;lt;/tt&amp;gt; parameter affects the response format and can be either &amp;lt;tt&amp;gt;xml&amp;lt;/tt&amp;gt; (default) or &amp;lt;tt&amp;gt;json&amp;lt;/tt&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
== Officially supported protocols ==&lt;br /&gt;
&lt;br /&gt;
; REST : The Moodle REST server accepts GET/POST parameters and return XML/JSON values. This server is not RESTfull.&lt;br /&gt;
; SOAP : The Moodle SOAP server is based on the Zend SOAP server (itself based on the PHP SOAP server). Zend publishes [http://framework.zend.com/manual/en/zend.soap.client.html a Zend SOAP client]. The current server implementation doesn&#039;t fully work with Java/.Net because we didn&#039;t generated a fully describe WSDL yet. If you are working on a Java/.Net client, follow or participate to the tracker issues MDL-28988 / MDL-28989&lt;br /&gt;
; XML-RPC : The Moodle XML-RPC server is based on Zend XML-RPC server. Zend also publishes [http://framework.zend.com/manual/en/zend.xmlrpc.client.html a Zend XML-RPC client].&lt;br /&gt;
; AMF : the Moodle AMF server is based on the Zend AMF server. The test client can be found in &#039;&#039;Settings blocks &amp;gt; Site Administration &amp;gt; Development &amp;gt; Web service test client &amp;gt; AMF Test client&#039;&#039;.&lt;br /&gt;
&lt;br /&gt;
== Demo client examples ==&lt;br /&gt;
&lt;br /&gt;
Demo client sample codes can be downloaded on [https://github.com/moodlehq/sample-ws-clients Github].&lt;br /&gt;
&lt;br /&gt;
For HTML5 app creators, you can also find:&lt;br /&gt;
* a nice [https://github.com/jleyva/umm phonegap / Jquery mobile template]&lt;br /&gt;
* a proof of concept of [http://moodle.org/mod/forum/discuss.php?d=189882 javascript cross-domain with Sencha Touch 1.1]&lt;br /&gt;
&lt;br /&gt;
Node.js apps can use the [https://github.com/mudrd8mz/node-moodle-client moodle-client] module.&lt;br /&gt;
&lt;br /&gt;
A [http://moodle.org/mod/forum/discuss.php?d=199453 Java Library for REST] can be found on [http://sourceforge.net/projects/moodlerestjava/ Sourceforge].&lt;br /&gt;
&lt;br /&gt;
A [https://github.com/llagerlof/MoodleRest PHP Library for REST] can be found on GitHub.&lt;br /&gt;
&lt;br /&gt;
A [https://github.com/zaddok/moodle Go Library for REST] can be found on GitHub.&lt;br /&gt;
&lt;br /&gt;
== How to get a user token ==&lt;br /&gt;
{{Moodle_2.2}}&lt;br /&gt;
Your client can call the script located in /login/token.php with a simple HTTP request. We highly recommend to do it securely with HTTPS.&lt;br /&gt;
The required parameters are:&lt;br /&gt;
* username&lt;br /&gt;
* password&lt;br /&gt;
* service shortname - The service shortname is usually hardcoded in the pre-build service (db/service.php files). Moodle administrator will be able to edit shortnames for service created on the fly: MDL-29807. If you want to use the Mobile service, its shortname is &amp;lt;tt&amp;gt;moodle_mobile_app&amp;lt;/tt&amp;gt;. Also useful to know, the database shortname field can be found in the table named external_services.&lt;br /&gt;
&lt;br /&gt;
Request:&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
https://www.yourmoodle.com/login/token.php?username=USERNAME&amp;amp;password=PASSWORD&amp;amp;service=SERVICESHORTNAME&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Response:&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
{token:4ed876sd87g6d8f7g89fsg6987dfh78d}&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Difference between Moodle versions ===&lt;br /&gt;
&lt;br /&gt;
* Moodle 2.2 and later: the script can generate user tokens for any service shortname (of course users must be allowed on the service, see [[:en:How to create and enable a web service|How to create and enable a web service]]).&lt;br /&gt;
* Moodle 2.1: the script can only generate tokens for the official built-in mobile service. However the script can returns tokens for other services, they just need to have been previously generated.&lt;br /&gt;
&lt;br /&gt;
=== About service shortname ===&lt;br /&gt;
&lt;br /&gt;
At the moment a service can have a shortname if you:&lt;br /&gt;
* create the service as a built-in service (in db/services.php files) &lt;br /&gt;
* add the shortname manually in the DB. Note: we&#039;ll add the admin UI for shortname later (MDL-30229)&lt;br /&gt;
&lt;br /&gt;
== Text formats ==&lt;br /&gt;
=== Moodle 2.0 to 2.2 ===&lt;br /&gt;
{{Moodle_2.0}}&lt;br /&gt;
HTML is the format sent/received by web service functions. All returned file urls are converted to &#039;http://xxxx/webservice/pluginfile.php/yyyyyyyy&#039;&lt;br /&gt;
&lt;br /&gt;
=== Moodle 2.3 and later ===&lt;br /&gt;
{{Moodle_2.3}}&lt;br /&gt;
Since Moodle 2.3 you can add few GET/POST parameters to your request (for devs who have a good knowledge of File API and format_text()):&lt;br /&gt;
* &#039;&#039;moodlewssettingraw&#039;&#039; =&amp;gt; false by default. If true, the function will not apply format_text() to description/summary/textarea. The function will return the raw content from the DB.&lt;br /&gt;
* &#039;&#039;moodlewssettingfileurl&#039;&#039; =&amp;gt; true by default, returned file urls are converted to &#039;http://xxxx/webservice/pluginfile.php/yyyyyyyy&#039;. If false the raw file url content from the DB is returned (e.g. @@PLUGINFILE@@)&lt;br /&gt;
* &#039;&#039;moodlewssettingfilter&#039;&#039; =&amp;gt; false by default. If true, the function will filter during format_text()&lt;br /&gt;
&lt;br /&gt;
== See also ==&lt;br /&gt;
* [[Web services|Web services developer documentation]]&lt;br /&gt;
* [[:en:Web_services|Web services user documentation]]&lt;br /&gt;
* [[Creating a web service and a web service function | Implement a web service and a web service function]]&lt;br /&gt;
* [[Web_services_Roadmap|Web service Roadmap]]&lt;br /&gt;
&lt;br /&gt;
[[Category:Web Services]]&lt;/div&gt;</summary>
		<author><name>Marcojones</name></author>
	</entry>
	<entry>
		<id>https://docs.moodle.org/dev/index.php?title=lib/formslib.php_Form_Definition&amp;diff=55355</id>
		<title>lib/formslib.php Form Definition</title>
		<link rel="alternate" type="text/html" href="https://docs.moodle.org/dev/index.php?title=lib/formslib.php_Form_Definition&amp;diff=55355"/>
		<updated>2019-01-04T14:31:45Z</updated>

		<summary type="html">&lt;p&gt;Marcojones: /* Passing parameters to the Form */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Formslib}}&lt;br /&gt;
== &#039;&#039;definition()&#039;&#039; ==&lt;br /&gt;
&lt;br /&gt;
The definition of the elements to be included in the form, their &#039;types&#039; (PARAM_*), helpbuttons included, etc. is all included in a function you must define in your class.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;definition()&#039;&#039; is used to define the elements in the form and &#039;&#039;&#039;this definition will be used for validating data submitted as well as for printing the form.&#039;&#039;&#039; 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.&lt;br /&gt;
&lt;br /&gt;
The &#039;&#039;definition()&#039;&#039; should include all elements that are going to be used on form, some elements may be removed or tweaked later in &#039;&#039;definition_after_data()&#039;&#039;. Please do not create conditional elements in &#039;&#039;definition()&#039;&#039;, the definition() should not directly depend on the submitted data.&lt;br /&gt;
&lt;br /&gt;
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. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
require_once(&amp;quot;$CFG-&amp;gt;libdir/formslib.php&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
class simplehtml_form extends moodleform {&lt;br /&gt;
&lt;br /&gt;
    function definition() {&lt;br /&gt;
        global $CFG;&lt;br /&gt;
       &lt;br /&gt;
        $mform = $this-&amp;gt;_form; // Don&#039;t forget the underscore! &lt;br /&gt;
&lt;br /&gt;
        $mform-&amp;gt;addElement()... // Add elements to your form&lt;br /&gt;
            ...&lt;br /&gt;
    }                           // Close the function&lt;br /&gt;
}                               // Close the class&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
===Passing parameters to the Form===&lt;br /&gt;
&lt;br /&gt;
The constructor for &#039;&#039;moodleform&#039;&#039; allows a number of parameters including one (&#039;&#039;$customdata&#039;&#039;) to permit an array of arbitrary data to be passed to your form. &lt;br /&gt;
&lt;br /&gt;
For example, you can pass the data &amp;quot;$email&amp;quot; and &amp;quot;$username&amp;quot; to the Form&#039;s class for use inside (say) the definition.&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
...&lt;br /&gt;
 $mform_simple = new simplehtml_form( null, array(&#039;email&#039;=&amp;gt;$email, &#039;username&#039;=&amp;gt;$username ) );&lt;br /&gt;
...&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
(the first parameter is $action, &#039;&#039;null&#039;&#039; will cause the form action to be determined automatically)&lt;br /&gt;
&lt;br /&gt;
Secondly, inside the form definition you can use those parameters to set the default values to some of the form&#039;s fields&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
...&lt;br /&gt;
 $mform-&amp;gt;addElement(&#039;text&#039;, &#039;email&#039;, get_string(&#039;email&#039;), &#039;maxlength=&amp;quot;100&amp;quot; size=&amp;quot;25&amp;quot; &#039;);&lt;br /&gt;
 $mform-&amp;gt;setType(&#039;email&#039;, PARAM_NOTAGS);&lt;br /&gt;
 $mform-&amp;gt;addRule(&#039;email&#039;, get_string(&#039;missingemail&#039;), &#039;required&#039;, null, &#039;server&#039;);&lt;br /&gt;
 // Set default value by using a passed parameter&lt;br /&gt;
 $mform-&amp;gt;setDefault(&#039;email&#039;,$this-&amp;gt;_customdata[&#039;email&#039;]);&lt;br /&gt;
...&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Use Fieldsets to group Form Elements==&lt;br /&gt;
&lt;br /&gt;
You use code like this to open a fieldset with a &#039;&#039;legend&#039;&#039;. &amp;lt;br /&amp;gt;&lt;br /&gt;
(&#039;&#039;&#039;Note&#039;&#039;&#039;: Some themes turn off legends on admin setting pages by using CSS: &amp;lt;nowiki&amp;gt;#adminsettings legend {display:none;}&amp;lt;/nowiki&amp;gt;.)&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$mform-&amp;gt;addElement(&#039;header&#039;, &#039;nameforyourheaderelement&#039;, get_string(&#039;titleforlegened&#039;, &#039;modulename&#039;));&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can&#039;t yet nest these visible fieldsets unfortunately. But in fact groups of elements are wrapped in invisible fieldsets.&lt;br /&gt;
&lt;br /&gt;
{{Moodle 2.5}}&lt;br /&gt;
Since Moodle 2.5 fieldsets without any required fields are collapsed by default. To display these fieldsets on page load, use:&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
 $mform-&amp;gt;setExpanded(&#039;foo&#039;)&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You close a fieldset with moodle_form&#039;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) :&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$mform-&amp;gt;closeHeaderBefore(&#039;buttonar&#039;);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==addElement==&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Some examples are below :&lt;br /&gt;
=== button ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$mform-&amp;gt;addElement(&#039;button&#039;, &#039;intro&#039;, get_string(&amp;quot;buttonlabel&amp;quot;));&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A button element. If you want a submit or cancel button see &#039;submit&#039; element.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== autocomplete ===&lt;br /&gt;
{{Moodle 3.1}}&lt;br /&gt;
Available since Moodle 3.1&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$searchareas = \core_search\manager::get_search_areas_list(true);                                                           &lt;br /&gt;
$areanames = array();                                                                                                       &lt;br /&gt;
foreach ($searchareas as $areaid =&amp;gt; $searcharea) {                                                                          &lt;br /&gt;
    $areanames[$areaid] = $searcharea-&amp;gt;get_visible_name();                                                                  &lt;br /&gt;
}                                                                                                                           &lt;br /&gt;
$options = array(                                                                                                           &lt;br /&gt;
    &#039;multiple&#039; =&amp;gt; true,                                                                                                     &lt;br /&gt;
    &#039;noselectionstring&#039; =&amp;gt; get_string(&#039;allareas&#039;, &#039;search&#039;),                                                                &lt;br /&gt;
);         &lt;br /&gt;
$mform-&amp;gt;addElement(&#039;autocomplete&#039;, &#039;areaids&#039;, get_string(&#039;searcharea&#039;, &#039;search&#039;), $areanames, $options);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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 &#039;select&#039; 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:&lt;br /&gt;
* multiple (boolean - default false) - Allow more than one selected item. The data coming from the form will be an array in this case.&lt;br /&gt;
* noselectionstring (string - default &amp;lt;nowiki&amp;gt;&#039;&#039;&amp;lt;/nowiki&amp;gt;) - The text to display when nothing is selected.&lt;br /&gt;
* showsuggestions (boolean - default true) - Do not show the list of suggestions when the user starts typing.&lt;br /&gt;
* placeholder (string - default &amp;lt;nowiki&amp;gt;&#039;&#039;&amp;lt;/nowiki&amp;gt;) - The text to show in the search box when it is empty.&lt;br /&gt;
* casesensitive (boolean - default false) - Is the search case sensitive ?&lt;br /&gt;
* 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.&lt;br /&gt;
* ajax (string - default &amp;lt;nowiki&amp;gt;&#039;&#039;&amp;lt;/nowiki&amp;gt;) - This string is the name of an AMD module that can fetch and format results.&lt;br /&gt;
&lt;br /&gt;
More explanation on the &#039;ajax&#039; option. This should be the name of an AMD module that implements 2 functions:&lt;br /&gt;
&amp;lt;code javascript&amp;gt;&lt;br /&gt;
/**                                                                                                                         &lt;br /&gt;
 * Source of data for Ajax element.                                                                                         &lt;br /&gt;
 *                                                                                                                          &lt;br /&gt;
 * @param {String} selector The selector of the auto complete element.                                                      &lt;br /&gt;
 * @param {String} query The query string.                                                                                  &lt;br /&gt;
 * @param {Function} callback A callback function receiving an array of results.                                            &lt;br /&gt;
 * @return {Void}                                                                                                           &lt;br /&gt;
*/                                                                                                                         &lt;br /&gt;
transport: function(selector, query, callback) ...&lt;br /&gt;
&lt;br /&gt;
/**                                                                                                                         &lt;br /&gt;
 * Process the results for auto complete elements.                                                                          &lt;br /&gt;
 *                                                                                                                          &lt;br /&gt;
 * @param {String} selector The selector of the auto complete element.                                                      &lt;br /&gt;
 * @param {Array} results An array or results.                                                                              &lt;br /&gt;
 * @return {Array} New array of results.                                                                                    &lt;br /&gt;
 */                                                                                                                         &lt;br /&gt;
processResults: function(selector, results)...&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
A good example is here: [https://github.com/moodle/moodle/blob/MOODLE_31_STABLE/admin/tool/lp/amd/src/frameworks_datasource.js admin/tool/lp/amd/src/frameworks_datasource.js]&lt;br /&gt;
&lt;br /&gt;
When using the ajax option in an mform with validation etc - it is recommended to sub-class the php class &amp;quot;MoodleQuickForm_autocomplete&amp;quot; so that you can provide a list of name and&lt;br /&gt;
values to populate the form element if the form is re-displayed due to a validation error. An example is [https://github.com/moodle/moodle/blob/MOODLE_31_STABLE/admin/tool/lp/classes/form/framework_autocomplete.php admin/tool/lp/classes/form/framework_autocomplete.php].&lt;br /&gt;
&lt;br /&gt;
We have provided several useful subclasses of this form element already that are simple to use (course and tags).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt; &lt;br /&gt;
    // Course example.&lt;br /&gt;
    //  Valid options are:                                                                                     &lt;br /&gt;
    //                       &#039;multiple&#039; - boolean multi select                                                                      &lt;br /&gt;
    //                       &#039;exclude&#039; - array or int, list of course ids to never show                                             &lt;br /&gt;
    //                       &#039;requiredcapabilities&#039; - array of capabilities. Uses ANY to combine them.                              &lt;br /&gt;
    //                       &#039;limittoenrolled&#039; - boolean Limits to enrolled courses.                                                &lt;br /&gt;
    //                       &#039;includefrontpage&#039; - boolean Enables the frontpage to be selected.  &lt;br /&gt;
    $options = array(&#039;multiple&#039; =&amp;gt; true, &#039;includefrontpage&#039; =&amp;gt; true);                                                           &lt;br /&gt;
    $mform-&amp;gt;addElement(&#039;course&#039;, &#039;mappedcourses&#039;, get_string(&#039;courses&#039;), $options); &lt;br /&gt;
&lt;br /&gt;
    // Tags&lt;br /&gt;
    //  Valid options are:                                                                                     &lt;br /&gt;
    //                       &#039;showstandard&#039; - boolean One of the core_tag_tag constants to say which tags to display&lt;br /&gt;
    //                       &#039;component&#039; - string The component name and itemtype define the tag area&lt;br /&gt;
    //                       &#039;itemtype&#039; - string The component name and itemtype define the tag area&lt;br /&gt;
    $mform-&amp;gt;addElement(&#039;tags&#039;, &#039;interests&#039;, get_string(&#039;interestslist&#039;), array(&#039;itemtype&#039; =&amp;gt; &#039;user&#039;, &#039;component&#039; =&amp;gt; &#039;core&#039;));     &lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== checkbox ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$mform-&amp;gt;addElement(&#039;checkbox&#039;, &#039;ratingtime&#039;, get_string(&#039;ratingtime&#039;, &#039;forum&#039;));&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
You can have a 5th parameter $attributes, as on other elements.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;BEWARE:&#039;&#039;&#039; Unchecked checkboxes return nothing at all (as if they didn&#039;t exist). This can surprise the unwary. You may wish to use advcheckbox instead, which does return a value when not checked. &#039;Advcheckbox&#039; eliminates this problem. &lt;br /&gt;
&lt;br /&gt;
==== advcheckbox ====&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$mform-&amp;gt;addElement(&#039;advcheckbox&#039;, &#039;ratingtime&#039;, get_string(&#039;ratingtime&#039;, &#039;forum&#039;), &#039;Label displayed after checkbox&#039;, array(&#039;group&#039; =&amp;gt; 1), array(0, 1));&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Similar to the checkbox above, but with some important improvements:&lt;br /&gt;
&lt;br /&gt;
# The (optional) 5th parameter is a normal $attributes array, normally used to set HTML attributes for the &amp;lt;input&amp;gt; element. However, a special value of &#039;group&#039; can be given, which will add a class name to the element, and enable its grouping for a [[lib/formslib.php_add_checkbox_controller|checkbox controller]]&lt;br /&gt;
#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.&lt;br /&gt;
#It returns a 0 value when unchecked. Compare with the ordinary checkbox which does not return anything at all.&lt;br /&gt;
&lt;br /&gt;
=== choosecoursefile ===&lt;br /&gt;
{{Moodle 1.9}}&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$mform-&amp;gt;addElement(&#039;choosecoursefile&#039;, &#039;mediafile&#039;, get_string(&#039;mediafile&#039;, &#039;lesson&#039;), array(&#039;courseid&#039;=&amp;gt;$COURSE-&amp;gt;id));&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Choose a file from the course files area. The fourth option is a list of options for the element. &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Note: This has been superceded by [[#filepicker|filepicker]] in Moodle 2.&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
array(&#039;courseid&#039; =&amp;gt;null,  //if it is null (default then use global $COURSE&lt;br /&gt;
      &#039;height&#039;   =&amp;gt;500,   // height of the popup window&lt;br /&gt;
      &#039;width&#039;    =&amp;gt;750,   // width of the popup window&lt;br /&gt;
      &#039;options&#039;  =&amp;gt;&#039;none&#039;); //options string for the pop up window &lt;br /&gt;
                          //eg. &#039;menubar=0,location=0,scrollbars,resizable&#039;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can also pass an optional 5th parameter of attributes, as for other elements. The most useful way of using that is something like &lt;br /&gt;
&amp;lt;code php&amp;gt;array(&#039;maxlength&#039; =&amp;gt; 255, &#039;size&#039; =&amp;gt; 48)&amp;lt;/code&amp;gt;&lt;br /&gt;
to control the maxlength / size of the text box (note size will default to 48 if not specified)&lt;br /&gt;
&lt;br /&gt;
Finally, as this element is a group containing two elements (button + value), you can add validation rules by using the &#039;&#039;&#039;addGroupRule()&#039;&#039;&#039; method in this (complex) way:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;$mform-&amp;gt;addGroupRule(&#039;elementname&#039;, array(&#039;value&#039; =&amp;gt; array(array(list, of, rule, params, but, fieldname))));&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Where: &#039;&#039;&#039;&amp;quot;elementname&amp;quot;&#039;&#039;&#039; is the name of the choosecoursefile group element, &#039;&#039;&#039;&amp;quot;value&amp;quot;&#039;&#039;&#039; is the name of the text field within the group and the &#039;&#039;&#039;&amp;quot;list, of, addrule, params, but, fieldname&amp;quot;&#039;&#039;&#039; is exactly that, the list of fields in the normal addRule() function but ommiting the first one, the fieldname.&lt;br /&gt;
&lt;br /&gt;
For example, the [http://cvs.moodle.org/moodle/mod/resource/type/file/resource.class.php?view=markup file/url resource type], uses one &amp;quot;choosecoursefile&amp;quot; element, and it controls the maximum length of the field (255) with this use of addGroupRule():&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;$mform-&amp;gt;addGroupRule(&#039;reference&#039;, array(&#039;value&#039; =&amp;gt; array(array(get_string(&#039;maximumchars&#039;, &#039;&#039;, 255), &#039;maxlength&#039;, 255, &#039;client&#039;))));&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== date_selector ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$mform-&amp;gt;addElement(&#039;date_selector&#039;, &#039;assesstimefinish&#039;, get_string(&#039;to&#039;));&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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 :&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
array(&lt;br /&gt;
    &#039;startyear&#039; =&amp;gt; 1970, &lt;br /&gt;
    &#039;stopyear&#039;  =&amp;gt; 2020,&lt;br /&gt;
    &#039;timezone&#039;  =&amp;gt; 99,&lt;br /&gt;
    &#039;optional&#039;  =&amp;gt; false&lt;br /&gt;
);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=== date_time_selector ===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$mform-&amp;gt;addElement(&#039;date_time_selector&#039;, &#039;assesstimestart&#039;, get_string(&#039;from&#039;));&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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-&amp;gt;get_data(); the fourth param here is an array of options. The defaults for the options are:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
array(&lt;br /&gt;
    &#039;startyear&#039; =&amp;gt; 1970, &lt;br /&gt;
    &#039;stopyear&#039;  =&amp;gt; 2020,&lt;br /&gt;
    &#039;timezone&#039;  =&amp;gt; 99,&lt;br /&gt;
    &#039;step&#039;      =&amp;gt; 5&lt;br /&gt;
);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===duration===&lt;br /&gt;
{{Moodle 2.0}}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
        $mform-&amp;gt;addElement(&#039;duration&#039;, &#039;timelimit&#039;, get_string(&#039;timelimit&#039;, &#039;quiz&#039;));&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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:&lt;br /&gt;
&amp;lt;code php&amp;gt;array(&#039;optional&#039; =&amp;gt; true)&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
You can also pass an optional 5th parameter of attributes, as for other elements. The most useful way of using that is something like &lt;br /&gt;
&amp;lt;code php&amp;gt;array(&#039;size&#039; =&amp;gt; 5)&amp;lt;/code&amp;gt;&lt;br /&gt;
to control the size of the text box.&lt;br /&gt;
&lt;br /&gt;
=== editor ===&lt;br /&gt;
&lt;br /&gt;
This replaces the old htmleditor field type. It allows the user to enter rich text content in a variety of formats.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$mform-&amp;gt;addElement(&#039;editor&#039;, &#039;fieldname&#039;, get_string(&#039;labeltext&#039;, &#039;langfile&#039;));&lt;br /&gt;
$mform-&amp;gt;setType(&#039;fieldname&#039;, PARAM_RAW);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
NOTE: It won&#039;t work properly without the setType() as shown.&lt;br /&gt;
&lt;br /&gt;
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]].&lt;br /&gt;
&lt;br /&gt;
You can supply a fourth param to htmleditor of an array of options that are mostly related to file handling:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
array(&lt;br /&gt;
    &#039;subdirs&#039;=&amp;gt;0,&lt;br /&gt;
    &#039;maxbytes&#039;=&amp;gt;0,&lt;br /&gt;
    &#039;maxfiles&#039;=&amp;gt;0,&lt;br /&gt;
    &#039;changeformat&#039;=&amp;gt;0,&lt;br /&gt;
    &#039;context&#039;=&amp;gt;null,&lt;br /&gt;
    &#039;noclean&#039;=&amp;gt;0,&lt;br /&gt;
    &#039;trusttext&#039;=&amp;gt;0,&lt;br /&gt;
    &#039;enable_filemanagement&#039; =&amp;gt; true);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The option &#039;enable_filemanagement&#039; will display the file management button on true and remove it on false.&lt;br /&gt;
&lt;br /&gt;
To save the data if you don&#039;t care about files:&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$formdata = $mform-&amp;gt;get_data();&lt;br /&gt;
$text     = $formdata-&amp;gt;fieldname[&#039;text&#039;];&lt;br /&gt;
$format   = $formdata-&amp;gt;fieldname[&#039;format&#039;];&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note: Because the text editor might be &amp;quot;Atto&amp;quot; (depending on user preferences) and Atto has an &amp;quot;autosave&amp;quot; feature - it requires that the combination of $PAGE-&amp;gt;url and this elementid are unique. If not, the autosaved text for a different form may be restored into this form.&lt;br /&gt;
&lt;br /&gt;
=== file ===&lt;br /&gt;
&lt;br /&gt;
File upload input box with browse button. In the form definition type&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$mform-&amp;gt;addElement(&#039;file&#039;, &#039;attachment&#039;, get_string(&#039;attachment&#039;, &#039;forum&#039;));&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
after form submission and validation use&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
if ($data = $mform-&amp;gt;get_data()) {&lt;br /&gt;
      ...&lt;br /&gt;
    $mform-&amp;gt;save_files($destination_directory);&lt;br /&gt;
      ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If there is no requirement to save the file, you can read the file contents directly into a string as follows...&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
    $mform-&amp;gt;get_file_content(&#039;attachment&#039;);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you need advanced settings such as required file, different max upload size or name of uploaded file&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$this-&amp;gt;set_upload_manager(new upload_manager(&#039;attachment&#039;, true, false, $COURSE, false, 0, true, true, false));&lt;br /&gt;
            $mform-&amp;gt;addElement(&#039;file&#039;, &#039;attachment&#039;, get_string(&#039;attachment&#039;, &#039;forum&#039;));&lt;br /&gt;
            $mform-&amp;gt;addRule(&#039;attachment&#039;, null, &#039;required&#039;);&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
if ($data = $mform-&amp;gt;get_data()) {&lt;br /&gt;
      ...&lt;br /&gt;
    $mform-&amp;gt;save_files($destination_directory);&lt;br /&gt;
    $newfilename = $mform-&amp;gt;get_new_filename();&lt;br /&gt;
      ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
When porting old code it is also possible to use the upload manager directly for processing of uploaded files.&lt;br /&gt;
&lt;br /&gt;
Please note that if using set_upload_manager() it must be before addElement(&#039;file&#039;,..).&lt;br /&gt;
&lt;br /&gt;
{{Moodle 2.0}}&lt;br /&gt;
File uploading was rewritten in 2.0. Please see inline docs for now. This page will be updated when the new API stabilises.&lt;br /&gt;
&lt;br /&gt;
===filepicker===&lt;br /&gt;
{{Moodle 2.0}}&lt;br /&gt;
General replacement of &#039;&#039;file&#039;&#039; element.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$mform-&amp;gt;addElement(&#039;filepicker&#039;, &#039;userfile&#039;, get_string(&#039;file&#039;), null, array(&#039;maxbytes&#039; =&amp;gt; $maxbytes, &#039;accepted_types&#039; =&amp;gt; &#039;*&#039;));&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
See also [[Using the File API in Moodle forms]]&lt;br /&gt;
&lt;br /&gt;
=== hidden ===&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$mform-&amp;gt;addElement(&#039;hidden&#039;, &#039;reply&#039;, &#039;yes&#039;);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A hidden element. Set the element name (in this case &#039;&#039;&#039;reply&#039;&#039;&#039;) to the stated value (in this case &#039;&#039;&#039;yes&#039;&#039;&#039;).&lt;br /&gt;
&lt;br /&gt;
=== html ===&lt;br /&gt;
You can add arbitrary HTML to your Moodle form:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$mform-&amp;gt;addElement(&#039;html&#039;, &#039;&amp;lt;div class=&amp;quot;qheader&amp;quot;&amp;gt;&#039;);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
See [http://moodle.org/mod/forum/discuss.php?d=126935 &amp;quot;Question: Can I put a moodleform inside a table td?&amp;quot;] for a concrete example.&lt;br /&gt;
&lt;br /&gt;
=== htmleditor &amp;amp; format ===&lt;br /&gt;
&lt;br /&gt;
These elements are now deprecated. Please use the [[#editor|editor]] field type instead.&lt;br /&gt;
&lt;br /&gt;
===modgrade===&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
$mform-&amp;gt;addElement(&#039;modgrade&#039;, &#039;scale&#039;, get_string(&#039;grade&#039;), false);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
A helpbutton is automatically added.&lt;br /&gt;
&lt;br /&gt;
===modvisible===&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
$mform-&amp;gt;addElement(&#039;modvisible&#039;, &#039;visible&#039;, get_string(&#039;visible&#039;));&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
This is a custom element for selecting a grade visibility in an activity mod update form.&lt;br /&gt;
&lt;br /&gt;
===password===&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
$mform-&amp;gt;addElement(&#039;password&#039;, &#039;password&#039;, get_string(&#039;label&#039;), $attributes);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A password element. Fourth param is an array or string of attributes.&lt;br /&gt;
&lt;br /&gt;
===passwordunmask===&lt;br /&gt;
{{Moodle 1.9}}&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
$mform-&amp;gt;addElement(&#039;passwordunmask&#039;, &#039;password&#039;, get_string(&#039;label&#039;), $attributes);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A password element with option to show the password in plaintext. Fourth param is an array or string of attributes.&lt;br /&gt;
&lt;br /&gt;
=== radio ===&lt;br /&gt;
{{Moodle 2.3}}&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$radioarray=array();&lt;br /&gt;
$radioarray[] = $mform-&amp;gt;createElement(&#039;radio&#039;, &#039;yesno&#039;, &#039;&#039;, get_string(&#039;yes&#039;), 1, $attributes);&lt;br /&gt;
$radioarray[] = $mform-&amp;gt;createElement(&#039;radio&#039;, &#039;yesno&#039;, &#039;&#039;, get_string(&#039;no&#039;), 0, $attributes);&lt;br /&gt;
$mform-&amp;gt;addGroup($radioarray, &#039;radioar&#039;, &#039;&#039;, array(&#039; &#039;), false);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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&#039;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.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Since 2.3 it cannot be statically called anymore, so we need to call createElement from $mform reference.&lt;br /&gt;
&lt;br /&gt;
==== setDefault ====&lt;br /&gt;
&lt;br /&gt;
To set the default for a radio button group as above use the following :&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$mform-&amp;gt;setDefault(&#039;yesno&#039;, 0);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This would make the default &#039;no&#039;.&lt;br /&gt;
&lt;br /&gt;
===select===&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
$mform-&amp;gt;addElement(&#039;select&#039;, &#039;type&#039;, get_string(&#039;forumtype&#039;, &#039;forum&#039;), $FORUM_TYPES, $attributes);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
It is also possible to create a select with certain options disabled, using [http://stackoverflow.com/questions/2138089/how-can-i-use-quickform-to-add-disabled-select-options/2150275#2150275 this technique].&lt;br /&gt;
&lt;br /&gt;
You can set an &#039;onchange&#039; attribute when adding or creating the select element: &lt;br /&gt;
&lt;br /&gt;
$form-&amp;gt;addElement(&#039;select&#039;, &#039;iselTest&#039;, &#039;Test Select:&#039;, $arrayOfOptions, array(&#039;onchange&#039; =&amp;gt; &#039;javascript:myFunctionToDoSomething();&#039;));&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====multi-select====&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
$select = $mform-&amp;gt;addElement(&#039;select&#039;, &#039;colors&#039;, get_string(&#039;colors&#039;), array(&#039;red&#039;, &#039;blue&#039;, &#039;green&#039;), $attributes);&lt;br /&gt;
$select-&amp;gt;setMultiple(true);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=====setSelected=====&lt;br /&gt;
&lt;br /&gt;
To set the default selected item in a select element, you can use the &#039;setSelected&#039; method. The &#039;setSelected&#039; can either get a value or an array of values.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
$options = array(&lt;br /&gt;
    &#039;ff0000&#039; =&amp;gt; &#039;Red&#039;,&lt;br /&gt;
    &#039;00ff00&#039; =&amp;gt; &#039;Green&#039;,&lt;br /&gt;
    &#039;0000ff&#039; =&amp;gt; &#039;Blue&#039;&lt;br /&gt;
);&lt;br /&gt;
$select = $mform-&amp;gt;addElement(&#039;select&#039;, &#039;colors&#039;, get_string(&#039;colors&#039;), $options);&lt;br /&gt;
// This will select the colour blue.&lt;br /&gt;
$select-&amp;gt;setSelected(&#039;0000ff&#039;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Or for multpi-selection:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
$skillsarray = array(&lt;br /&gt;
    &#039;val1&#039; =&amp;gt; &#039;Skill A&#039;,&lt;br /&gt;
    &#039;val2&#039; =&amp;gt; &#039;Skill B&#039;,&lt;br /&gt;
    &#039;val3&#039; =&amp;gt; &#039;Skill C&#039;&lt;br /&gt;
);&lt;br /&gt;
$mform-&amp;gt;addElement(&#039;select&#039;, &#039;md_skills&#039;, get_string(&#039;skills&#039;, &#039;metadata&#039;), $skillsarray);&lt;br /&gt;
$mform-&amp;gt;getElement(&#039;md_skills&#039;)-&amp;gt;setMultiple(true);&lt;br /&gt;
// This will select the skills A and B.&lt;br /&gt;
$mform-&amp;gt;getElement(&#039;md_skills&#039;)-&amp;gt;setSelected(array(&#039;val1&#039;, &#039;val2&#039;));&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
However you probably don&#039;t want to do this. Instead you probably want to use setDefault, or set it using the form&#039;s setData method.&lt;br /&gt;
&lt;br /&gt;
===selectyesno===&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
$mform-&amp;gt;addElement(&#039;selectyesno&#039;, &#039;maxbytes&#039;, get_string(&#039;maxattachmentsize&#039;, &#039;forum&#039;));&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you want a yes / no select box this one automatically translates itself and has value 1 for yes and 0 for no.&lt;br /&gt;
&lt;br /&gt;
===selectwithlink===&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
$options = array();&lt;br /&gt;
$mform-&amp;gt;addElement(&#039;selectwithlink&#039;, &#039;scaleid&#039;, get_string(&#039;scale&#039;), $options, null, &lt;br /&gt;
    array(&#039;link&#039; =&amp;gt; $CFG-&amp;gt;wwwroot.&#039;/grade/edit/scale/edit.php?courseid=&#039;.$COURSE-&amp;gt;id, &#039;label&#039; =&amp;gt; get_string(&#039;scalescustomcreate&#039;)));&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
select type element with options containing link&lt;br /&gt;
===static===&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
$mform-&amp;gt;addElement(&#039;static&#039;, &#039;description&#039;, get_string(&#039;description&#039;, &#039;exercise&#039;),&lt;br /&gt;
    get_string(&#039;descriptionofexercise&#039;, &#039;exercise&#039;, $COURSE-&amp;gt;students));&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
===submit, reset and cancel===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//normally you use add_action_buttons instead of this code&lt;br /&gt;
$buttonarray=array();&lt;br /&gt;
$buttonarray[] = $mform-&amp;gt;createElement(&#039;submit&#039;, &#039;submitbutton&#039;, get_string(&#039;savechanges&#039;));&lt;br /&gt;
$buttonarray[] = $mform-&amp;gt;createElement(&#039;reset&#039;, &#039;resetbutton&#039;, get_string(&#039;revert&#039;));&lt;br /&gt;
$buttonarray[] = $mform-&amp;gt;createElement(&#039;cancel&#039;);&lt;br /&gt;
$mform-&amp;gt;addGroup($buttonarray, &#039;buttonar&#039;, &#039;&#039;, &#039; &#039;, false);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A &#039;Submit&#039; type element is a submit type form element which will submit the form. A &#039;Reset&#039; will not submit the form but will reset any changes the user has made to form contents. A &#039;Cancel&#039; 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.&lt;br /&gt;
&lt;br /&gt;
You should name your submit and reset buttons &#039;submitbutton&#039; and &#039;resetbutton&#039; or something similar (not &#039;submit&#039; and &#039;reset&#039;). This avoids problems in JavaScript of collisions between form element names and names of JavaScript methods of the form object.&lt;br /&gt;
&lt;br /&gt;
====add_action_buttons($cancel = true, $submitlabel=null);====&lt;br /&gt;
&lt;br /&gt;
You will normally use this helper function which is a method of moodleform to add all the &#039;action&#039; 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(&#039;savechanges&#039;). Note the &#039;&#039;&#039;$this&#039;&#039;&#039; not &#039;&#039;&#039;$mform&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
$this-&amp;gt;add_action_buttons();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===text===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
$mform-&amp;gt;addElement(&#039;text&#039;, &#039;name&#039;, get_string(&#039;forumname&#039;, &#039;forum&#039;), $attributes);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
For a simple text input element. (For text labels, use the &#039;static&#039; element.)  Your fourth parameter here can be a string or array of attributes for the text element. The following are equivalent :&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
$attributes=&#039;size=&amp;quot;20&amp;quot;&#039;;&lt;br /&gt;
$attributes=array(&#039;size&#039;=&amp;gt;&#039;20&#039;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Generally you are encouraged to use CSS instead of using attributes for styling.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
A format element can be used as a format select box. It will be non-selectable if you&#039;re using an html editor.&lt;br /&gt;
&lt;br /&gt;
The third param for this element is $useHtmlEditor and it defaults to null in which case an html editor is used if the browser and user profile support it.&lt;br /&gt;
&lt;br /&gt;
===textarea===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
$mform-&amp;gt;addElement(&#039;textarea&#039;, &#039;introduction&#039;, get_string(&amp;quot;introtext&amp;quot;, &amp;quot;survey&amp;quot;), &#039;wrap=&amp;quot;virtual&amp;quot; rows=&amp;quot;20&amp;quot; cols=&amp;quot;50&amp;quot;&#039;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
A textarea element. If you want an htmleditor use htmleditor element. Fourth element here is a string or array of attributes.&lt;br /&gt;
&lt;br /&gt;
===recaptcha===&lt;br /&gt;
{{Moodle 1.9}}&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
$mform-&amp;gt;addElement(&#039;recaptcha&#039;, &#039;recaptcha_field_name&#039;, $attributes);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
To check whether recaptcha is enabled at site level use:&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
if (!empty($CFG-&amp;gt;recaptchapublickey) &amp;amp;&amp;amp; !empty($CFG-&amp;gt;recaptchaprivatekey)) {&lt;br /&gt;
    //recaptcha is enabled&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===tags===&lt;br /&gt;
{{Moodle 2.0}}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
$mform-&amp;gt;addElement(&#039;tags&#039;, &#039;field_name&#039;, $lable, $options, $attributes);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Used for editing a list of tags, for example on a blog post.&lt;br /&gt;
&lt;br /&gt;
There is only one option available, &#039;display&#039;, 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.&lt;br /&gt;
&lt;br /&gt;
The value should be set/returned as an array of tags.&lt;br /&gt;
&lt;br /&gt;
===grading===&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$mform-&amp;gt;addElement(&#039;grading&#039;, &#039;advancedgrading&#039;, get_string(&#039;grade&#039;).&#039;:&#039;, array(&#039;gradinginstance&#039; =&amp;gt; $gradinginstance));&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Custom element for advanced grading plugins.&lt;br /&gt;
&lt;br /&gt;
When adding the &#039;grading&#039; element to the form, developer must pass an object of class gradingform_instance as $attributes[&#039;gradinginstance&#039;]. Otherwise an exception will be thrown.&lt;br /&gt;
&lt;br /&gt;
===questioncategory===&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$mform-&amp;gt;addElement(&#039;questioncategory&#039;, &#039;category&#039;, get_string(&#039;category&#039;, &#039;question&#039;),&lt;br /&gt;
    array(&#039;contexts&#039;=&amp;gt;$contexts, &#039;top&#039;=&amp;gt;true, &#039;currentcat&#039;=&amp;gt;$currentcat, &#039;nochildrenof&#039;=&amp;gt;$currentcat));&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
Creates a drop down element to select a question category.&lt;br /&gt;
&lt;br /&gt;
Options are:&lt;br /&gt;
&#039;&#039;&#039;contexts&#039;&#039;&#039; - (required) context in which question appears&lt;br /&gt;
&#039;&#039;&#039;currentcat&#039;&#039;&#039; - (optional) course category&lt;br /&gt;
&#039;&#039;&#039;top&#039;&#039;&#039; - (optional) if true will put top categories on top&lt;br /&gt;
&#039;&#039;&#039;nochildrenof&#039;&#039;&#039; - (optional) Format categories into an indented list reflecting the tree structure&lt;br /&gt;
&lt;br /&gt;
=== filetypes ===&lt;br /&gt;
{{Moodle 3.4}}&lt;br /&gt;
Available since Moodle 3.4&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$mform-&amp;gt;addElement(&#039;filetypes&#039;, &#039;allowedfiletypes&#039;, get_string(&#039;allowedfiletypes&#039;, &#039;tool_myplugin&#039;));&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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 &amp;quot;image&amp;quot;. The element integrates with the [[Core filetypes]] system so all default types and groups are presented, as well as those [[:en:Working with files#Site administration settings|defined locally by the admin]].&lt;br /&gt;
&lt;br /&gt;
As the list can be types in manually, the form processing code should always normalize it first via the provided utility methods:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$formdata = $mform-&amp;gt;get_data();&lt;br /&gt;
$filetypesutil = new \core_form\filetypes_util();&lt;br /&gt;
$allowedfiletypes = $filetypesutil-&amp;gt;normalize_file_types($formdata-&amp;gt;allowedfiletypes);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$filetypesutil = new \core_form\filetypes_util();&lt;br /&gt;
$options[&#039;accepted_types&#039;] = $filetypesutil-&amp;gt;normalize_file_types($allowedfiletypes);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
By default, user input is validated against the list of known file types and groups. This validation can be disabled via options.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Supported options&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
; onlytypes : Allow selection from these file types only; for example [&#039;onlytypes&#039; =&amp;gt; [&#039;web_image&#039;]].&lt;br /&gt;
; allowall : Allow to select &#039;All file types&#039;, defaults to true. Does not apply with onlytypes are set.&lt;br /&gt;
; allowunknown : Skip implicit validation against the list of known file types.&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$mform-&amp;gt;addElement(&#039;filetypes&#039;, &#039;doctypes&#039;, get_string(&#039;doctypes&#039;, &#039;tool_myplugin&#039;), [&#039;onlytypes&#039; =&amp;gt; [&#039;document&#039;], &#039;allowunknown&#039; =&amp;gt; true]);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==addGroup==&lt;br /&gt;
&lt;br /&gt;
A &#039;group&#039; in formslib is just a group of elements that will have a label and will be included on one line. &lt;br /&gt;
&lt;br /&gt;
For example typical code to include a submit and cancel button on the same line : &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
$buttonarray=array();&lt;br /&gt;
$buttonarray[] =&amp;amp; $mform-&amp;gt;createElement(&#039;submit&#039;, &#039;submitbutton&#039;, get_string(&#039;savechanges&#039;));&lt;br /&gt;
$buttonarray[] =&amp;amp; $mform-&amp;gt;createElement(&#039;submit&#039;, &#039;cancel&#039;, get_string(&#039;cancel&#039;));&lt;br /&gt;
$mform-&amp;gt;addGroup($buttonarray, &#039;buttonar&#039;, &#039;&#039;, array(&#039; &#039;), false);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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).&lt;br /&gt;
&lt;br /&gt;
Here&#039;s a bad example (don&#039;t do this for real, use the &#039;optional&#039; =&amp;gt; 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 &#039;availablefromgroup&#039; but it doesn&#039;t disable the controlling element the &#039;availablefromenabled&#039; checkbox:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
$availablefromgroup=array();&lt;br /&gt;
$availablefromgroup[] =&amp;amp; $mform-&amp;gt;createElement(&#039;date_selector&#039;, &#039;availablefrom&#039;, &#039;&#039;);&lt;br /&gt;
$availablefromgroup[] =&amp;amp; $mform-&amp;gt;createElement(&#039;checkbox&#039;, &#039;availablefromenabled&#039;, &#039;&#039;, get_string(&#039;enable&#039;));&lt;br /&gt;
$mform-&amp;gt;addGroup($availablefromgroup, &#039;availablefromgroup&#039;, get_string(&#039;availablefromdate&#039;, &#039;data&#039;), &#039;&amp;amp;nbsp;&#039;, false);&lt;br /&gt;
$mform-&amp;gt;disabledIf(&#039;availablefromgroup&#039;, &#039;availablefromenabled&#039;);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* If you want to put a group inside another array so that you can repeat items, use createElement instead of addGroup:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
$group = $mform-&amp;gt;createElement(&#039;group&#039;, &#039;groupname&#039;, get_string(&#039;label&#039;), $groupitems);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
* 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.:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
$group = $mform-&amp;gt;createElement(&#039;group&#039;, &#039;groupname&#039;, get_string(&#039;label&#039;), $groupitems, null, false);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==addRule==&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
$mform-&amp;gt;addRule(&#039;elementname&#039;, get_string(&#039;error&#039;), &#039;rule type&#039;, &#039;extraruledata&#039;, &#039;server&#039;(default), false, false);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The first param(element) is an element name and second(message) is the error message that will be displayed to the user.&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 * @param    string     $element       Form element name&lt;br /&gt;
 * @param    string     $message       Message to display for invalid data&lt;br /&gt;
 * @param    string     $type          Rule type, use getRegisteredRules() to get types&lt;br /&gt;
 * @param    string     $format        (optional)Required for extra rule data&lt;br /&gt;
 * @param    string     $validation    (optional)Where to perform validation: &amp;quot;server&amp;quot;, &amp;quot;client&amp;quot;&lt;br /&gt;
 * @param    boolean    $reset         Client-side validation: reset the form element to its original value if there is an error?&lt;br /&gt;
 * @param    boolean    $force         Force the rule to be applied, even if the target form element does not exist&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Common Rule Types&#039;&#039;&#039;&lt;br /&gt;
* required &lt;br /&gt;
* maxlength&lt;br /&gt;
* minlength&lt;br /&gt;
* rangelength&lt;br /&gt;
* email&lt;br /&gt;
* regex&lt;br /&gt;
* lettersonly&lt;br /&gt;
* alphanumeric&lt;br /&gt;
* numeric&lt;br /&gt;
* nopunctuation&lt;br /&gt;
* nonzero&lt;br /&gt;
* callback&lt;br /&gt;
* compare&lt;br /&gt;
&lt;br /&gt;
===Server side and Client side===&lt;br /&gt;
In case you use the &#039;&#039;Client side&#039;&#039; validation option, you can mainly check for an empty or not input field. unless you write some &#039;&#039;Client side&#039;&#039; 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.&lt;br /&gt;
In case you need a more complex validation checks which relay on Moodle&#039;s internal PHP libraries (or other/external PHP libraries) you better use the &#039;&#039;Server side&#039;&#039; 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&#039;s side.&lt;br /&gt;
&lt;br /&gt;
==setHelpButton==&lt;br /&gt;
{{Moodle 1.9}}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
$mform-&amp;gt;setHelpButton(&#039;lessondefault&#039;, array(&#039;lessondefault&#039;, get_string(&#039;lessondefault&#039;, &#039;lesson&#039;), &#039;lesson&#039;));&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
First param is an elementname and the second param is an array of params that are passed to helpbutton in weblib.php. Params are :&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 * @param string $page  The keyword that defines a help page&lt;br /&gt;
 * @param string $title The title of links, rollover tips, alt tags etc&lt;br /&gt;
 *           &#039;Help with&#039; (or the language equivalent) will be prefixed and &#039;...&#039; will be stripped.&lt;br /&gt;
 * @param string $module Which module is the page defined in&lt;br /&gt;
 * @param mixed $image Use a help image for the link?  (true/false/&amp;quot;both&amp;quot;)&lt;br /&gt;
 * @param boolean $linktext If true, display the title next to the help icon.&lt;br /&gt;
 * @param string $text If defined then this text is used in the page, and&lt;br /&gt;
 *           the $page variable is ignored.&lt;br /&gt;
 * @param boolean $return If true then the output is returned as a string, if false it is printed to the current page.&lt;br /&gt;
 * @param string $imagetext The full text for the helpbutton icon. If empty use default help.gif&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
Make sure you don&#039;t set boolean $return to false. &lt;br /&gt;
&lt;br /&gt;
You need to do use this method after addElement();&lt;br /&gt;
&lt;br /&gt;
==addHelpButton==&lt;br /&gt;
{{Moodle 2.0}}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$mform-&amp;gt;addHelpButton(&#039;api_key_field&#039;, &#039;api_key&#039;, &#039;block_extsearch&#039;);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In Moodle 2.0 the &amp;quot;setHelpButton&amp;quot; method has been deprecated in favor of the &amp;quot;addHelpButton&amp;quot; method, which has a simplified interface and uses $OUTPUT-&amp;gt;help_icon() on the back end. The following parameters are expected:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
/**&lt;br /&gt;
 * @param $elementname The name of the form element to add the help button for&lt;br /&gt;
 * @param $identifier The identifier for the help string and its title (see below)&lt;br /&gt;
 * @param $component The component name to look for the help string in&lt;br /&gt;
 */&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
Unlike in Moodle 1.9, it is no longer necessary to put your help pages in separate HTML files. Instead, the function looks for two strings:&lt;br /&gt;
&lt;br /&gt;
# get_string($identifier, $component) // The title of the help page&lt;br /&gt;
# get_string(&amp;quot;{$identifier}_help&amp;quot;, $component) // The content of the help page&lt;br /&gt;
&lt;br /&gt;
So you will need to have &#039;&#039;&#039;$identifier&#039;&#039;&#039; and &#039;&#039;&#039;{$identifier}_help&#039;&#039;&#039; 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. &lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$mform-&amp;gt;addHelpButton(&#039;shuffleanswers&#039;, &#039;shuffleanswers&#039;, &#039;qtype_multichoice&#039;);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
and so the language file includes the strings&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$string[&#039;shuffleanswers&#039;] = &#039;Shuffle the choices?&#039;; &lt;br /&gt;
$string[&#039;shuffleanswers_help&#039;] = &#039;If enabled,.....&#039;;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
You can also add the language string like&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$string[&#039;shuffleanswers_link&#039;] = &#039;question/shuffleanswers&#039;;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
to add a link to more help on Moodle docs. See [[String_API]] for more information about help icons.&lt;br /&gt;
&lt;br /&gt;
==setDefault==&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
$mform-&amp;gt;addElement(&#039;select&#039;, &#039;grade&#039;, get_string(&#039;gradeforsubmission&#039;, &#039;exercise&#039;), $grades);&lt;br /&gt;
$mform-&amp;gt;setHelpButton(&#039;grade&#039;, array(&#039;grade&#039;, get_string(&#039;gradeforsubmission&#039;, &#039;exercise&#039;), &#039;exercise&#039;));&lt;br /&gt;
$mform-&amp;gt;setDefault(&#039;grade&#039;, 100);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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 &#039;add&#039; rather than &#039;update&#039; function.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
$mform-&amp;gt;addElement(&#039;editor&#039;, &#039;desc&#039;, get_string(&#039;description&#039;));     &lt;br /&gt;
$mform-&amp;gt;setDefault(&#039;desc&#039;, array(&#039;text&#039;=&amp;gt;$defaulttext));&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note that when setting the default for an editor element you must use an array to define the default &amp;quot;text&amp;quot; value as shown above.&lt;br /&gt;
&lt;br /&gt;
==disabledIf==&lt;br /&gt;
&lt;br /&gt;
For any element or groups of element in a form you can conditionally disable the group or individual element depending on conditions.&lt;br /&gt;
&lt;br /&gt;
You can use $mform-&amp;gt;disabledIf($elementName, $dependentOn, $condition = &#039;notchecked&#039;, $value=&#039;1&#039;)&lt;br /&gt;
&lt;br /&gt;
* 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&#039;ve used as the second argument in addElement or addGroup.&lt;br /&gt;
* 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&#039;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.&lt;br /&gt;
* $condition will be &#039;notchecked&#039;, &#039;checked&#039;, &#039;noitemselected&#039;, &#039;eq&#039;, &#039;in&#039; or, if it is anything else, we test for &#039;neq&#039;.&lt;br /&gt;
** If $condition is &#039;eq&#039; or &#039;neq&#039; then we check the value of the dependentOn field and check for equality (==) or nonequality (!=) in js&lt;br /&gt;
** If $condition is &#039;checked&#039; or &#039;notchecked&#039; then we check to see if a checkbox is checked or not.&lt;br /&gt;
** If $condition is &#039;in&#039; then we check to see if a selected item is in the given list or not. (This was introduced in Moodle 2.7+)&lt;br /&gt;
** If $condition is &#039;noitemselected&#039; then we check to see whether nothing is selected in a dropdown list.&lt;br /&gt;
&lt;br /&gt;
Examples:&lt;br /&gt;
 // Disable my control unless a checkbox is checked.&lt;br /&gt;
 $mform-&amp;gt;disabledIf(&#039;mycontrol&#039;, &#039;somecheckbox&#039;);&lt;br /&gt;
 &lt;br /&gt;
 // Disable my control if a checkbox &#039;&#039;&#039;is&#039;&#039;&#039; checked.&lt;br /&gt;
 $mform-&amp;gt;disabledIf(&#039;mycontrol&#039;, &#039;somecheckbox&#039;, &#039;checked&#039;);&lt;br /&gt;
 &lt;br /&gt;
 // Disable my control when a dropdown has value 42.&lt;br /&gt;
 $mform-&amp;gt;disabledIf(&#039;mycontrol&#039;, &#039;someselect&#039;, &#039;eq&#039;, 42);&lt;br /&gt;
&lt;br /&gt;
 // Disable my control unless a dropdown has value 42.&lt;br /&gt;
 $mform-&amp;gt;disabledIf(&#039;mycontrol&#039;, &#039;someselect&#039;, &#039;neq&#039;, 42);&lt;br /&gt;
&lt;br /&gt;
The possible choices here are in the dependency manager in lib/form/form.js.&lt;br /&gt;
===A tricky case===&lt;br /&gt;
&lt;br /&gt;
You need to take care with disabledIf if you plan to use it with groups of checkboxes.&lt;br /&gt;
&lt;br /&gt;
Let&#039;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.&lt;br /&gt;
&lt;br /&gt;
To fix ideas:&lt;br /&gt;
&lt;br /&gt;
If the selection in the checkboxes group is:&lt;br /&gt;
&lt;br /&gt;
 mycheck_01 == 1&lt;br /&gt;
 mycheck_02 == 0&lt;br /&gt;
 mycheck_03 == 0&lt;br /&gt;
 mycheck_04 == 0&lt;br /&gt;
 mycheck_05 == 1&lt;br /&gt;
&lt;br /&gt;
the depending item must be enabled while ANY OTHER COMBINATION must disable the drop down menu.&lt;br /&gt;
&lt;br /&gt;
The following code will, apparently, fail:&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$mform-&amp;gt;disabledIf(&#039;dropdownmenu&#039;, &#039;mycheck_01&#039;, &#039;neq&#039;, &#039;1&#039;);&lt;br /&gt;
$mform-&amp;gt;disabledIf(&#039;dropdownmenu&#039;, &#039;mycheck_02&#039;, &#039;neq&#039;, &#039;0&#039;);&lt;br /&gt;
$mform-&amp;gt;disabledIf(&#039;dropdownmenu&#039;, &#039;mycheck_03&#039;, &#039;neq&#039;, &#039;0&#039;);&lt;br /&gt;
$mform-&amp;gt;disabledIf(&#039;dropdownmenu&#039;, &#039;mycheck_04&#039;, &#039;neq&#039;, &#039;0&#039;);&lt;br /&gt;
$mform-&amp;gt;disabledIf(&#039;dropdownmenu&#039;, &#039;mycheck_05&#039;, &#039;neq&#039;, &#039;1&#039;);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In fact, once you get the drop down menu enabled, you are free to unselect mycheck_01 whilst still having the depending item enabled.&lt;br /&gt;
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 &amp;quot;mycheck_01&amp;quot; and will not apply the corresponding rule.&lt;br /&gt;
&lt;br /&gt;
A working solution for this kind of issue seems to be:&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$mform-&amp;gt;disabledIf(&#039;dropdownmenu&#039;, &#039;mycheck_01&#039;, &#039;notchecked&#039;);&lt;br /&gt;
$mform-&amp;gt;disabledIf(&#039;dropdownmenu&#039;, &#039;mycheck_02&#039;, &#039;checked&#039;);&lt;br /&gt;
$mform-&amp;gt;disabledIf(&#039;dropdownmenu&#039;, &#039;mycheck_03&#039;, &#039;checked&#039;);&lt;br /&gt;
$mform-&amp;gt;disabledIf(&#039;dropdownmenu&#039;, &#039;mycheck_04&#039;, &#039;checked&#039;);&lt;br /&gt;
$mform-&amp;gt;disabledIf(&#039;dropdownmenu&#039;, &#039;mycheck_05&#039;, &#039;notchecked&#039;);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
==hideIf==&lt;br /&gt;
{{Moodle 3.4}}&lt;br /&gt;
For any element or groups of element in a form you can conditionally hide the group or individual element depending on conditions.&lt;br /&gt;
This uses the same syntax as disabledIf just with hideIf instead.&lt;br /&gt;
&lt;br /&gt;
==setType==&lt;br /&gt;
&lt;br /&gt;
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).&lt;br /&gt;
&lt;br /&gt;
===Most Commonly Used PARAM_* Types===&lt;br /&gt;
&lt;br /&gt;
These are the most commonly used PARAM_* types and their proper uses. More types can be seen in moodlelib.php starting around line 100.&lt;br /&gt;
&lt;br /&gt;
* PARAM_CLEAN is deprecated and you should try to use a more specific type.&lt;br /&gt;
* 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.&lt;br /&gt;
* 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.&lt;br /&gt;
* 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().&lt;br /&gt;
* 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.&lt;br /&gt;
* PARAM_ACTION is an alias of PARAM_ALPHA and is used for hidden fields specifying form actions.&lt;br /&gt;
&lt;br /&gt;
==disable_form_change_checker==&lt;br /&gt;
&lt;br /&gt;
By default, any Moodle form will pop-up an &amp;quot;Are you sure?&amp;quot; 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&lt;br /&gt;
&lt;br /&gt;
 $mform-&amp;gt;disable_form_change_checker()&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&lt;br /&gt;
* [http://www.midnighthax.com/quickform.php PEAR HTML QuickForm Getting Started Guide] by Keith Edmunds of Midnighthax.com&lt;br /&gt;
* [http://pear.php.net/manual/en/package.html.html-quickform.php PEAR::HTML_QuickForm manual]&lt;br /&gt;
&lt;br /&gt;
[[Category:Formslib]]&lt;br /&gt;
[[Category:Interfaces]]&lt;/div&gt;</summary>
		<author><name>Marcojones</name></author>
	</entry>
	<entry>
		<id>https://docs.moodle.org/dev/index.php?title=External_services_description&amp;diff=55302</id>
		<title>External services description</title>
		<link rel="alternate" type="text/html" href="https://docs.moodle.org/dev/index.php?title=External_services_description&amp;diff=55302"/>
		<updated>2018-12-28T09:33:15Z</updated>

		<summary type="html">&lt;p&gt;Marcojones: /* external_functions table */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Moodle_2.0}}&lt;br /&gt;
&lt;br /&gt;
== Purpose ==&lt;br /&gt;
This document explains how we describe and where we store the external services and functions in Moodle 2.0.&lt;br /&gt;
&lt;br /&gt;
===Service discovery===&lt;br /&gt;
We store the service descriptions and a part of the function descriptions in the component/db/services.php file. Function implementations are located in externallib.php files - this file name is not mandatory, but it is strongly recommended. externallib.php files also contain the other part of the function descriptions (the function parameters descriptions).&lt;br /&gt;
&lt;br /&gt;
During the upgrades the descriptions are parsed by a service discovery function that fills the database tables. Administrative UI may be used to change some configuration details. Services can also be defined via the admin UI, but it is recommended to use the new local plugin (look at the readme.txt into the Moodle local folder) when adding custom new services.&lt;br /&gt;
&lt;br /&gt;
===Administration pages===&lt;br /&gt;
Moodle administrators will be able to manage services. By default all services will be disabled.&lt;br /&gt;
&lt;br /&gt;
List of administration functionalities:&lt;br /&gt;
* enable a service (all the functions into this service will be available)&lt;br /&gt;
* associate a web service user (the user has web service capability) to some services =&amp;gt; a user can only call a service that he is associated with&lt;br /&gt;
* create a custom service (name the service + add and remove existing external functions from this service)&lt;br /&gt;
* search easily function by component in order to create a custom service&lt;br /&gt;
&lt;br /&gt;
===external_functions table===&lt;br /&gt;
This table lists the web service functions. It makes sense to call it external_functions as 1 web service function &amp;lt;=&amp;gt; 1 external function. This table maps the web service function name to the actual implementation of that function.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;nicetable&amp;quot;&lt;br /&gt;
! Field&lt;br /&gt;
! Type&lt;br /&gt;
! Default&lt;br /&gt;
! Description&lt;br /&gt;
|-&lt;br /&gt;
| &#039;&#039;&#039;id&#039;&#039;&#039; &lt;br /&gt;
| int(10)&lt;br /&gt;
| auto-incrementing&lt;br /&gt;
| &lt;br /&gt;
|-&lt;br /&gt;
| &#039;&#039;&#039;name&#039;&#039;&#039;&lt;br /&gt;
| varchar(200)&lt;br /&gt;
| &lt;br /&gt;
| the web service name (e.g. the unique name of the external function in the web service API) - a unique identifier for each function; ex.: core_get_users, mod_assignment_submit&lt;br /&gt;
|-&lt;br /&gt;
| classname&lt;br /&gt;
| varchar(100)&lt;br /&gt;
| &lt;br /&gt;
| name of the class that contains method implementation; ex.: core_user_external, mod_assignment_external&lt;br /&gt;
|-&lt;br /&gt;
| methodname&lt;br /&gt;
| varchar(100)&lt;br /&gt;
| &lt;br /&gt;
| static method; ex.: get_users, submit&lt;br /&gt;
|-&lt;br /&gt;
| classpath&lt;br /&gt;
| varchar(255)&lt;br /&gt;
| NULL&lt;br /&gt;
| optional path to file with class definition - recommended for core classes only, null means use component/externallib.php; this path is relative to dirroot; ex.: user/externallib.php&lt;br /&gt;
|-&lt;br /&gt;
| component&lt;br /&gt;
| varchar(100)&lt;br /&gt;
| &lt;br /&gt;
| Component where function defined, needed for automatic updates. Service description file is found in the db folder of this component.&lt;br /&gt;
|-&lt;br /&gt;
| &amp;lt;font color=&amp;quot;green&amp;quot;&amp;gt;description&amp;lt;/font&amp;gt;&lt;br /&gt;
| &amp;lt;font color=&amp;quot;green&amp;quot;&amp;gt;text&amp;lt;/font&amp;gt;&lt;br /&gt;
|&lt;br /&gt;
| &amp;lt;font color=&amp;quot;green&amp;quot;&amp;gt;A short human readable description of the function. It will be used to generate documentation and help the administrator to search a web service function. (NB: decide later if it&#039;s really improving the performance compare to add an access to the phpfile)&amp;lt;/font&amp;gt;&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
Detailed function description is stored as a complex PHP structure in the implementation class using suffix _parameters and _returns.&lt;br /&gt;
&lt;br /&gt;
===external_services table===&lt;br /&gt;
A &#039;&#039;service&#039;&#039; is defined as a group of external functions. The main purpose of these &#039;&#039;services&#039;&#039; is to allow defining of granular access control for multiple external systems.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;nicetable&amp;quot;&lt;br /&gt;
! Field&lt;br /&gt;
! Type&lt;br /&gt;
! Default&lt;br /&gt;
! Description&lt;br /&gt;
|-&lt;br /&gt;
| &#039;&#039;&#039;id&#039;&#039;&#039; &lt;br /&gt;
| int(10)&lt;br /&gt;
| auto-incrementing&lt;br /&gt;
| &lt;br /&gt;
|-&lt;br /&gt;
| &#039;&#039;&#039;name&#039;&#039;&#039; &lt;br /&gt;
| varchar(150)&lt;br /&gt;
| &lt;br /&gt;
| Name of service (gradeexport_xml_export, mod_chat_export) - appears on the admin page. This name is not human readable when displayed into administration. We will use lang file to translate them automatically if a lang string exist.&amp;lt;/font&amp;gt;&lt;br /&gt;
|-&lt;br /&gt;
| enabled&lt;br /&gt;
| int(1)&lt;br /&gt;
| 0&lt;br /&gt;
| service enabled, for security reasons some services may be disabled- administrators may disable any service via the admin UI&lt;br /&gt;
|-&lt;br /&gt;
| requiredcapability&lt;br /&gt;
| varchar(255)&lt;br /&gt;
| NULL&lt;br /&gt;
| if capability name specified, user needs to have this permission in security context or in system context if context restriction not specified&lt;br /&gt;
|-&lt;br /&gt;
| restrictedusers&lt;br /&gt;
| int(1)&lt;br /&gt;
| 1&lt;br /&gt;
| 1 means on users explicitly listed in external_services_users may access this service, 0 means any user may use this service&lt;br /&gt;
|-&lt;br /&gt;
| component&lt;br /&gt;
| varchar(100)&lt;br /&gt;
| NULL&lt;br /&gt;
| Component where service defined - null means custom service defined in admin UI.&lt;br /&gt;
|-&lt;br /&gt;
| timecreated&lt;br /&gt;
| bigint(10)&lt;br /&gt;
| &lt;br /&gt;
| The time the service was enabled or defined?&lt;br /&gt;
|-&lt;br /&gt;
| timemodified&lt;br /&gt;
| bigint(10)&lt;br /&gt;
| &lt;br /&gt;
| The last time the service was updated&lt;br /&gt;
|- &lt;br /&gt;
| shortname&lt;br /&gt;
| varchar(255)&lt;br /&gt;
| &lt;br /&gt;
| The short name of the service&lt;br /&gt;
|- &lt;br /&gt;
| downloadfiles&lt;br /&gt;
| tinyint(1)&lt;br /&gt;
| &lt;br /&gt;
| A flag for something to do with download and files?&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
===external_services_functions table===&lt;br /&gt;
Lists all functions that are available in each service.&lt;br /&gt;
&lt;br /&gt;
{| class=&amp;quot;nicetable&amp;quot;&lt;br /&gt;
! Field&lt;br /&gt;
! Type&lt;br /&gt;
! Default&lt;br /&gt;
! Description&lt;br /&gt;
|-&lt;br /&gt;
| &#039;&#039;&#039;id&#039;&#039;&#039; &lt;br /&gt;
| int(10)&lt;br /&gt;
| auto-incrementing&lt;br /&gt;
| &lt;br /&gt;
|-&lt;br /&gt;
| &#039;&#039;&#039;externalserviceid&#039;&#039;&#039; &lt;br /&gt;
| int(10)&lt;br /&gt;
| &lt;br /&gt;
| foreign key, reference external_services.id&lt;br /&gt;
|-&lt;br /&gt;
| &#039;&#039;&#039;functionname&#039;&#039;&#039; &lt;br /&gt;
| varchar(200)&lt;br /&gt;
| &lt;br /&gt;
| unique name of external function: references external_functions.name; the string value here simplifies service discovery and maintenance&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
=== Function description ===&lt;br /&gt;
&lt;br /&gt;
We need to describe each function in detail, including input and output, so that we can:&lt;br /&gt;
&lt;br /&gt;
* help programmers quickly understand what they have to send and what to expect&lt;br /&gt;
* validate all incoming data as automatically as possible for security/correctness&lt;br /&gt;
* generate WSDL files for SOAP&lt;br /&gt;
* generate documentation for other protocols&lt;br /&gt;
&lt;br /&gt;
There are three main parts working together to do this:&lt;br /&gt;
&lt;br /&gt;
====services.php====&lt;br /&gt;
&lt;br /&gt;
In the db/services.php of each component, is a structure something like this to describe the web service functions, and optionally, any larger services built up of several functions.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$functions = array(&lt;br /&gt;
    &#039;moodle_user_create_users&#039; =&amp;gt; array(           //web service name (unique in all Moodle)&lt;br /&gt;
        &#039;classname&#039;   =&amp;gt; &#039;moodle_user_external&#039;, //class containing the function implementation&lt;br /&gt;
        &#039;methodname&#039;  =&amp;gt; &#039;create_users&#039;,              //name of the function into the class&lt;br /&gt;
        &#039;classpath&#039;   =&amp;gt; &#039;user/externallib.php&#039;,     //file containing the class (only used for core external function, not needed if your file is &#039;component/externallib.php&#039;),&lt;br /&gt;
        &#039;description&#039; =&amp;gt; &#039;create some users&#039;,&lt;br /&gt;
        &#039;type&#039; =&amp;gt; &#039;write&#039;,&lt;br /&gt;
        &#039;services&#039; =&amp;gt; array(MOODLE_OFFICIAL_MOBILE_SERVICE)    // Optional, only available for Moodle 3.1 onwards. List of built-in services (by shortname) where the function will be included. Services created manually via the Moodle interface are not supported.&lt;br /&gt;
    )&lt;br /&gt;
);&lt;br /&gt;
&lt;br /&gt;
$services = array( &lt;br /&gt;
    &#039;servicename&#039; =&amp;gt; array(&lt;br /&gt;
        &#039;functions&#039; =&amp;gt; array (&#039;functionname&#039;, &#039;secondfunctionname&#039;), //web service function name&lt;br /&gt;
        &#039;requiredcapability&#039; =&amp;gt; &#039;some/capability:specified&#039;,                  &lt;br /&gt;
        &#039;restrictedusers&#039; = &amp;gt;1,&lt;br /&gt;
        &#039;enabled&#039;=&amp;gt;0, //used only when installing the services&lt;br /&gt;
    )&lt;br /&gt;
);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The function name is arbitrary, but it must be globally unique so we highly recommend using the component name as prefix (and &amp;quot;moodle&amp;quot; for core functions).&lt;br /&gt;
&lt;br /&gt;
The actual param description and description of returned values can be obtained from the same class by static method calls by adding &#039;_parameters&#039; and &#039;_returns&#039; to the methodname value.&lt;br /&gt;
&lt;br /&gt;
====externallib.php====&lt;br /&gt;
&lt;br /&gt;
It&#039;s the file referenced as the location for the web service function implementation. It also contains complete descriptions of the required parameters.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Base description classes:&#039;&#039;&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
abstract class external_description {&lt;br /&gt;
    public $desc; //human readable description&lt;br /&gt;
    public $required;&lt;br /&gt;
&lt;br /&gt;
    public function __construct($desc, $required) {&lt;br /&gt;
        $this-&amp;gt;desc = $desc;&lt;br /&gt;
        $this-&amp;gt;required = $required;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
class external_value extends external_description {&lt;br /&gt;
    public $type;&lt;br /&gt;
    public $default;&lt;br /&gt;
    public $allownull;&lt;br /&gt;
&lt;br /&gt;
    public function __construct($type, $desc=&#039;&#039;, $required=VALUE_REQUIRED, $default=null, $allownull=true) {&lt;br /&gt;
        parent::_construct($desc, $required);&lt;br /&gt;
        $this-&amp;gt;type      = $type;&lt;br /&gt;
        $this-&amp;gt;default   = $default;&lt;br /&gt;
        $this-&amp;gt;allownull = $allownull;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
class external_single_structure extends external_description {&lt;br /&gt;
    public $keys; //an associative array of external_description&lt;br /&gt;
&lt;br /&gt;
    public function __construct(array $keys, $desc=&#039;&#039;, $required=VALUE_REQUIRED) {&lt;br /&gt;
        parent::_construct($desc, $required);&lt;br /&gt;
        $this-&amp;gt;keys = $keys; //key=&amp;gt;external_description&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
class external_multiple_structure extends external_description {&lt;br /&gt;
    public $content; //the content type of the list =&amp;gt; external_description&lt;br /&gt;
&lt;br /&gt;
    public function __construct(external_description $content, $desc=&#039;&#039;, $required=VALUE_REQUIRED) {&lt;br /&gt;
        parent::_construct($desc, $required);&lt;br /&gt;
        $this-&amp;gt;content = $content;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
class external_function_parameters extends external_single_structure {&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Externallib.php examples:&#039;&#039;&amp;lt;br/&amp;gt;&lt;br /&gt;
These examples include param/return value descriptions and function implementations. See the create_users function for difference between Mandatory/Optional/Default. &lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
class moodle_group_external extends external_api { //see following chapter &#039;function implementation&#039; to have a look to the external_api class&lt;br /&gt;
    public static function add_member_parameters() {&lt;br /&gt;
        return new external_function_parameters(&lt;br /&gt;
            array(&lt;br /&gt;
                &#039;groupid&#039; =&amp;gt; new external_value(PARAM_INT, &#039;some group id&#039;),&lt;br /&gt;
                &#039;userid&#039;  =&amp;gt; new external_value(PARAM_INT, &#039;some user id&#039;)&lt;br /&gt;
            )&lt;br /&gt;
        );&lt;br /&gt;
    }&lt;br /&gt;
    public static function add_member($groupid, $userid) {&lt;br /&gt;
        $params = self::validate_parameters(self::add_member_parameters(), array(&#039;groupid&#039;=&amp;gt;$groupid, &#039;userid&#039;=&amp;gt;$userid));&lt;br /&gt;
&lt;br /&gt;
        // all the parameter/behavioural checks and security constrainsts go here,&lt;br /&gt;
        // throwing exceptions if neeeded and and calling low level (grouplib)&lt;br /&gt;
        // add_member() function that will be one in charge of the functionality without&lt;br /&gt;
        // further checks.&lt;br /&gt;
&lt;br /&gt;
    }&lt;br /&gt;
    public static function add_member_returns() {&lt;br /&gt;
        return null;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
    public static function add_members_parameters() {&lt;br /&gt;
        return new external_function_parameters(&lt;br /&gt;
            array(&lt;br /&gt;
                &#039;membership&#039; =&amp;gt; new external_multiple_structure(&lt;br /&gt;
                    self::add_member_parameters()&lt;br /&gt;
                )&lt;br /&gt;
            )&lt;br /&gt;
        );&lt;br /&gt;
    }&lt;br /&gt;
    public static function add_members(array $membership) {&lt;br /&gt;
        $params = self::validate_parameters(self::add_members_parameters(), array(&#039;membership&#039;=&amp;gt;$membership));&lt;br /&gt;
        foreach($params[&#039;membership&#039;] as $one) { // simply one iterator over the &amp;quot;single&amp;quot; function if possible&lt;br /&gt;
            self::add_member($one-&amp;gt;groupid, $one-&amp;gt;userid);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
    public static function add_members_returns() {&lt;br /&gt;
        return null;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
    public static function get_groups_parameters() {&lt;br /&gt;
        return new external_function_parameters(&lt;br /&gt;
            array(&lt;br /&gt;
                &#039;groups&#039; =&amp;gt; new external_multiple_structure(&lt;br /&gt;
                    new external_single_structure(&lt;br /&gt;
                        array(&lt;br /&gt;
                            &#039;groupid&#039; =&amp;gt; new external_value(PARAM_INT, &#039;some group id&#039;)&lt;br /&gt;
                        )&lt;br /&gt;
                    )&lt;br /&gt;
                )&lt;br /&gt;
            )&lt;br /&gt;
        );&lt;br /&gt;
    }&lt;br /&gt;
    public static function get_groups(array $groups) {&lt;br /&gt;
        $params = self::validate_parameters(self::get_groups_parameters(), array(&#039;groups&#039;=&amp;gt;$groups));&lt;br /&gt;
&lt;br /&gt;
        // all the parameter/behavioural checks and security constrainsts go here,&lt;br /&gt;
        // throwing exceptions if needed and and calling low level (grouplib)&lt;br /&gt;
        // get_groups() function that will be one in charge of the functionality without&lt;br /&gt;
        // further checks.&lt;br /&gt;
&lt;br /&gt;
    }&lt;br /&gt;
    public static function get_groups_returns() {&lt;br /&gt;
        return new external_multiple_structure(&lt;br /&gt;
            new external_single_structure(&lt;br /&gt;
                array(&lt;br /&gt;
                    &#039;id&#039; =&amp;gt; new external_value(PARAM_INT, &#039;some group id&#039;),&lt;br /&gt;
                    &#039;name&#039; =&amp;gt; new external_value(PARAM_TEXT, &#039;multilang compatible name, course unique&#039;),&lt;br /&gt;
                    &#039;description&#039; =&amp;gt; new external_value(PARAM_RAW, &#039;just some text&#039;),&lt;br /&gt;
                    &#039;enrolmentkey&#039; =&amp;gt; new external_value(PARAM_RAW, &#039;group enrol secret phrase&#039;)&lt;br /&gt;
                )&lt;br /&gt;
            )&lt;br /&gt;
        );&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
class moodle_user_external extends external_api {&lt;br /&gt;
    public static function create_users_parameters() {&lt;br /&gt;
        new external_function_parameters(&lt;br /&gt;
            array(&lt;br /&gt;
                &#039;users&#039; =&amp;gt; new external_multiple_structure(&lt;br /&gt;
                    new external_single_structure(&lt;br /&gt;
                        array(&lt;br /&gt;
                            &#039;username&#039;    =&amp;gt; new external_value(PARAM_RAW, &#039;Username policy is defined in Moodle security config&#039;),&lt;br /&gt;
                            &#039;password&#039;    =&amp;gt; new external_value(PARAM_RAW, &#039;Plain text password consisting of any characters&#039;),&lt;br /&gt;
                            &#039;firstname&#039;   =&amp;gt; new external_value(PARAM_NOTAGS, &#039;The first name(s) of the user&#039;),&lt;br /&gt;
                            &#039;lastname&#039;    =&amp;gt; new external_value(PARAM_NOTAGS, &#039;The family name of the user&#039;),&lt;br /&gt;
                            &#039;email&#039;       =&amp;gt; new external_value(PARAM_EMAIL, &#039;A valid and unique email address&#039;),&lt;br /&gt;
                            &#039;auth&#039;        =&amp;gt; new external_value(PARAM_SAFEDIR, &#039;Auth plugins include manual, ldap,&lt;br /&gt;
                                                                imap, etc&#039;, VALUE_DEFAULT,&#039;manual&#039;, false),&lt;br /&gt;
                            &#039;idnumber&#039;    =&amp;gt; new external_value(PARAM_RAW, &#039;An arbitrary ID code number perhaps from the institution&#039;,&lt;br /&gt;
                                                                VALUE_DEFAULT, null),&lt;br /&gt;
                            &#039;emailstop&#039;   =&amp;gt; new external_value(PARAM_NUMBER, &#039;Email is blocked: 1 is blocked and 0 otherwise&#039;,&lt;br /&gt;
                                                                VALUE_DEFAULT, 0),&lt;br /&gt;
                            &#039;lang&#039;        =&amp;gt; new external_value(PARAM_SAFEDIR, &#039;Language code such as &amp;quot;en_utf8&amp;quot; must exist on server&#039;,&lt;br /&gt;
                                                                VALUE_DEFAULT, $CFG-&amp;gt;lang, false),&lt;br /&gt;
                            &#039;theme&#039;       =&amp;gt; new external_value(PARAM_SAFEDIR, &#039;Theme name such as &amp;quot;standard&amp;quot; must exist on server&#039;,&lt;br /&gt;
                                                                VALUE_OPTIONAL),&lt;br /&gt;
                            &#039;timezone&#039;    =&amp;gt; new external_value(PARAM_ALPHANUMEXT, &#039;Timezone code such as Australia/Perth,or 99 for default&#039;,&lt;br /&gt;
                                                                VALUE_OPTIONAL),&lt;br /&gt;
                            &#039;mailformat&#039;  =&amp;gt; new external_value(PARAM_INTEGER, &#039;Mail format code is 0 for plain text, 1 for HTML etc&#039;,&lt;br /&gt;
                                                                VALUE_OPTIONAL),&lt;br /&gt;
                            &#039;description&#039; =&amp;gt; new external_value(PARAM_TEXT, &#039;User profile description, as HTML&#039;, VALUE_OPTIONAL),&lt;br /&gt;
                            &#039;city&#039;        =&amp;gt; new external_value(PARAM_NOTAGS, &#039;Home city of the user&#039;, VALUE_OPTIONAL),&lt;br /&gt;
                            &#039;country&#039;     =&amp;gt; new external_value(PARAM_ALPHA, &#039;Home country code of the user, such as AU or CZ&#039;,&lt;br /&gt;
                                                                VALUE_OPTIONAL),&lt;br /&gt;
                            &#039;preferences&#039; =&amp;gt; new external_multiple_structure(&lt;br /&gt;
                                new external_single_structure(&lt;br /&gt;
                                    array(&lt;br /&gt;
                                        &#039;type&#039;  =&amp;gt; new external_value(PARAM_ALPHANUMEXT, &#039;The name of the preference&#039;),&lt;br /&gt;
                                        &#039;value&#039; =&amp;gt; new external_value(PARAM_RAW, &#039;The value of the preference&#039;)&lt;br /&gt;
                                    )&lt;br /&gt;
                                ), &#039;User preferences&#039;, VALUE_OPTIONAL),&lt;br /&gt;
                            &#039;customfields&#039; =&amp;gt; new external_multiple_structure(&lt;br /&gt;
                                new external_single_structure(&lt;br /&gt;
                                    array(&lt;br /&gt;
                                        &#039;type&#039;  =&amp;gt; new external_value(PARAM_ALPHANUMEXT, &#039;The name of the custom field&#039;),&lt;br /&gt;
                                        &#039;value&#039; =&amp;gt; new external_value(PARAM_RAW, &#039;The value of the custom field&#039;)&lt;br /&gt;
                                    )&lt;br /&gt;
                                ), &#039;User custom fields&#039;, VALUE_OPTIONAL)&lt;br /&gt;
                        )&lt;br /&gt;
                    )&lt;br /&gt;
                )&lt;br /&gt;
            )&lt;br /&gt;
        );&lt;br /&gt;
    }&lt;br /&gt;
    public static function create_users(array $users) {&lt;br /&gt;
        $params = self::validate_parameters(self::create_users_parameters(), array(&#039;users&#039;=&amp;gt;$users));&lt;br /&gt;
&lt;br /&gt;
        foreach ($params[&#039;users&#039;] as $user) {&lt;br /&gt;
            // all the parameter/behavioural checks and security constrainsts go here,&lt;br /&gt;
            // throwing exceptions if neeeded and and calling low level (userlib)&lt;br /&gt;
            // add_user() function that will be one in charge of the functionality without&lt;br /&gt;
            // further checks.&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
    public static function create_users_returns() {&lt;br /&gt;
        return new external_multiple_structure(&lt;br /&gt;
            new external_value(&#039;userid&#039;, PARAM_INT, &#039;id of the created user&#039;)&lt;br /&gt;
        );&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note the use of Moodle-oriented PARAM_XXXX constants to define the format of each field.  These are used by the validation function &#039;&#039;validate_parameters()&#039;&#039; to verify the data and throw an exception and abort the operation completely if the data changed during cleaning (ie it was malformed).&lt;br /&gt;
&lt;br /&gt;
====Params====&lt;br /&gt;
&lt;br /&gt;
We use the clean_param function to check data.  We have added in &#039;&#039;moodlelib.php&#039;&#039; some new checks for common Moodle data so that we get better cleaning.  eg &lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
...&lt;br /&gt;
        case PARAM_AUTH:&lt;br /&gt;
            $param = clean_param($param, PARAM_SAFEDIR);&lt;br /&gt;
            if (exists_auth_plugin($param)) {&lt;br /&gt;
                return $param;&lt;br /&gt;
            } else {&lt;br /&gt;
                return &#039;&#039;;&lt;br /&gt;
            }&lt;br /&gt;
&lt;br /&gt;
        case PARAM_LANG:&lt;br /&gt;
            $param = clean_param($param, PARAM_SAFEDIR);&lt;br /&gt;
            $langs = get_list_of_languages(false, true);&lt;br /&gt;
            if (in_array($param, $langs)) {&lt;br /&gt;
                return $param;&lt;br /&gt;
            } else {&lt;br /&gt;
                return &#039;&#039;;  // Specified language is not installed&lt;br /&gt;
            }&lt;br /&gt;
&lt;br /&gt;
        case PARAM_THEME:&lt;br /&gt;
            $param = clean_param($param, PARAM_SAFEDIR);&lt;br /&gt;
            if (file_exists($CFG-&amp;gt;dirroot.&#039;/theme/&#039;.$param)) {&lt;br /&gt;
                return $param;&lt;br /&gt;
            } else {&lt;br /&gt;
                return &#039;&#039;;  // Specified theme is not installed&lt;br /&gt;
            }&lt;br /&gt;
...&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=====Parameters types=====&lt;br /&gt;
&lt;br /&gt;
Note, this list will almost certainly be out of date by the time you read it. Do yourself a favour, and look at the list in lib/moodlelib.php. That is guaranteed to be up-to-date.&lt;br /&gt;
&lt;br /&gt;
* &#039;PARAM_ALPHA&#039;,    &#039;alpha&#039;&lt;br /&gt;
* &#039;PARAM_ALPHAEXT&#039;, &#039;alphaext&#039;&lt;br /&gt;
* &#039;PARAM_ALPHANUM&#039;, &#039;alphanum&#039;&lt;br /&gt;
* &#039;PARAM_ALPHANUMEXT&#039;, &#039;alphanumext&#039;&lt;br /&gt;
* &#039;PARAM_AUTH&#039;,  &#039;auth&#039;&lt;br /&gt;
* &#039;PARAM_BASE64&#039;,   &#039;base64&#039;&lt;br /&gt;
* &#039;PARAM_BOOL&#039;,     &#039;bool&#039;&lt;br /&gt;
* &#039;PARAM_CAPABILITY&#039;,   &#039;capability&#039;&lt;br /&gt;
* &#039;PARAM_CLEANHTML&#039;, &#039;cleanhtml&#039;&lt;br /&gt;
* &#039;PARAM_EMAIL&#039;,   &#039;email&#039;&lt;br /&gt;
* &#039;PARAM_FILE&#039;,   &#039;file&#039;&lt;br /&gt;
* &#039;PARAM_FLOAT&#039;,  &#039;float&#039;&lt;br /&gt;
* &#039;PARAM_HOST&#039;,     &#039;host&#039;&lt;br /&gt;
* &#039;PARAM_INT&#039;,      &#039;int&#039;&lt;br /&gt;
* &#039;PARAM_LANG&#039;,  &#039;lang&#039;&lt;br /&gt;
* &#039;PARAM_LOCALURL&#039;, &#039;localurl&#039;&lt;br /&gt;
* &#039;PARAM_NOTAGS&#039;,   &#039;notags&#039;&lt;br /&gt;
* &#039;PARAM_PATH&#039;,     &#039;path&#039;&lt;br /&gt;
* &#039;PARAM_PEM&#039;,      &#039;pem&#039;&lt;br /&gt;
* &#039;PARAM_PERMISSION&#039;,   &#039;permission&#039;&lt;br /&gt;
* &#039;PARAM_RAW&#039;, &#039;raw&#039;&lt;br /&gt;
* &#039;PARAM_RAW_TRIMMED&#039;, &#039;raw_trimmed&#039;&lt;br /&gt;
* &#039;PARAM_SAFEDIR&#039;,  &#039;safedir&#039;&lt;br /&gt;
* &#039;PARAM_SAFEPATH&#039;,  &#039;safepath&#039;&lt;br /&gt;
* &#039;PARAM_SEQUENCE&#039;,  &#039;sequence&#039;&lt;br /&gt;
* &#039;PARAM_TAG&#039;,   &#039;tag&#039;&lt;br /&gt;
* &#039;PARAM_TAGLIST&#039;,   &#039;taglist&#039;&lt;br /&gt;
* &#039;PARAM_TEXT&#039;,  &#039;text&#039;&lt;br /&gt;
* &#039;PARAM_THEME&#039;,  &#039;theme&#039;&lt;br /&gt;
* &#039;PARAM_URL&#039;,      &#039;url&#039;&lt;br /&gt;
* &#039;PARAM_USERNAME&#039;,    &#039;username&#039;&lt;br /&gt;
* &#039;PARAM_STRINGID&#039;,    &#039;stringid&#039;&lt;br /&gt;
* &#039;PARAM_CLEAN&#039;,    &#039;clean&#039;&lt;br /&gt;
* &#039;PARAM_INTEGER&#039;,  &#039;int&#039;&lt;br /&gt;
* &#039;PARAM_NUMBER&#039;,  &#039;float&#039;&lt;br /&gt;
* &#039;PARAM_ACTION&#039;,   &#039;alphanumext&#039;&lt;br /&gt;
* &#039;PARAM_FORMAT&#039;,   &#039;alphanumext&#039;&lt;br /&gt;
* &#039;PARAM_MULTILANG&#039;,  &#039;text&#039;&lt;br /&gt;
* &#039;PARAM_TIMEZONE&#039;, &#039;timezone&#039;&lt;br /&gt;
* &#039;PARAM_CLEANFILE&#039;, &#039;file&#039;&lt;br /&gt;
* &#039;PARAM_COMPONENT&#039;, &#039;component&#039;&lt;br /&gt;
* &#039;PARAM_AREA&#039;, &#039;area&#039;&lt;br /&gt;
* &#039;PARAM_PLUGIN&#039;, &#039;plugin&#039;&lt;br /&gt;
&lt;br /&gt;
=== Function implementation ===&lt;br /&gt;
&lt;br /&gt;
As you probably understood when you read the previous chapter examples, the functions are generally stored in externallib.php files, as methods in a class that extends &#039;&#039;&#039;&#039;external_api&#039;&#039;&#039;&#039;.  The actual file location is referenced by &#039;&#039;&#039;&#039;classpath&#039;&#039;&#039;&#039; in the services.php description.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
class moodle_user_external extends external_api {&lt;br /&gt;
    public static function create_users($users)&lt;br /&gt;
    $params = self::validate_parameters(self::create_users_parameters(), array(&#039;users&#039;=&amp;gt;$users)); //ws object are associative array, ws list are non associative array&lt;br /&gt;
 &lt;br /&gt;
        foreach ($params[&#039;users&#039;] as $user) {&lt;br /&gt;
            // all the parameter/behavioural checks and security constraints go here,&lt;br /&gt;
            // throwing exceptions if needed and and calling low level (userlib)&lt;br /&gt;
            // add_user() function that will be one in charge of the functionality without&lt;br /&gt;
            // further checks.&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note: there is more examples in the previous chapter&lt;br /&gt;
&lt;br /&gt;
external_api file:&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
/**&lt;br /&gt;
 * Base class for external api methods.&lt;br /&gt;
 */&lt;br /&gt;
class external_api {&lt;br /&gt;
&lt;br /&gt;
     ...&lt;br /&gt;
&lt;br /&gt;
     /**&lt;br /&gt;
     * Validates submitted function parameters, if anything is incorrect&lt;br /&gt;
     * invalid_parameter_exception is thrown.&lt;br /&gt;
     * This is a simple recursive method which is intended to be called from&lt;br /&gt;
     * each implementation method of external API.&lt;br /&gt;
     * @param external_description $description description of parameters&lt;br /&gt;
     * @param mixed $params the actual parameters&lt;br /&gt;
     * @return mixed params with added defaults for optional items, invalid_parameters_exception thrown if any problem found&lt;br /&gt;
     */&lt;br /&gt;
    public static function validate_parameters(external_description $description, $params) {&lt;br /&gt;
         ...&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    ...&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== Way to fill the database tables ===&lt;br /&gt;
The Moodle upgrade takes care of the updates. We added two functions &#039;&#039;lib/upgradelib.php/external_update_description()&#039;&#039; and &#039;&#039;lib/upgradelib.php/external_delete_description()&#039;&#039; that update all web service descriptions into the database. &#039;&#039;lib/upgradelib.php/external_update_description()&#039;&#039; is also called during Moodle installation process.&lt;br /&gt;
&lt;br /&gt;
=== Return values are filtered by the servers ===&lt;br /&gt;
Web service functions should be able to return whatever they want. Each server should be looking at the web services description and returns the expected values.&lt;br /&gt;
&lt;br /&gt;
Some bulk requests may terminate unexpectedly in the middle of processing elements, these partial failures should be indicated by special exceptions classes which include list of completed elements and original exception. &amp;lt;font color=&amp;quot;green&amp;quot;&amp;gt;TODO: special exceptions and the way to manage them need to be detailed&amp;lt;/font&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=See also=&lt;br /&gt;
* [[Web services]]&lt;br /&gt;
* [[External services security]]&lt;br /&gt;
&lt;br /&gt;
[[Category:Web Services]]&lt;/div&gt;</summary>
		<author><name>Marcojones</name></author>
	</entry>
	<entry>
		<id>https://docs.moodle.org/dev/index.php?title=Data_manipulation_API&amp;diff=55277</id>
		<title>Data manipulation API</title>
		<link rel="alternate" type="text/html" href="https://docs.moodle.org/dev/index.php?title=Data_manipulation_API&amp;diff=55277"/>
		<updated>2018-12-17T10:54:23Z</updated>

		<summary type="html">&lt;p&gt;Marcojones: /* Getting a hashed array of records */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Moodle_2.0}}This page describes the functions available to access data in the Moodle database. You should &#039;&#039;&#039;exclusively&#039;&#039;&#039; use these functions in order to retrieve or modify database content because these functions provide a high level of abstraction and guarantee that your database manipulation will work against different RDBMSes.&lt;br /&gt;
&lt;br /&gt;
Where possible, tricks and examples will be documented here in order to make developers&#039; lives a bit easier. Of course, feel free to clarify, complete and add more information to  this documentation. It will be welcome, absolutely!&lt;br /&gt;
&lt;br /&gt;
== Main info ==&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Important note:&#039;&#039;&#039; All the functions shown on this page are for use in &#039;&#039;&#039;Moodle 2.0 upwards&#039;&#039;&#039;, where we changed the [[DB layer 2.0|DB layer]] to support some new features. If you need information for previous Moodle version, take a look to the [[DML functions - pre 2.0|DML functions - pre 2.0]] page. For a detailed reference of changes, see the [[DB layer 2.0 migration docs|migration docs]].&lt;br /&gt;
&lt;br /&gt;
* All the function calls on this page are public methods of the $DB global object, so you&#039;ll need to &amp;quot;import&amp;quot; it within your functions (not needed in global scripts) with one simple:&lt;br /&gt;
&amp;lt;code php&amp;gt;global $DB;&amp;lt;/code&amp;gt;&lt;br /&gt;
* The $DB global object is an instance of the moodle_database class, which is defined in [http://git.moodle.org/gw?p=moodle.git;a=blob;f=lib/dml/moodle_database.php;h=2a6676c84e7c77b0534f18a13ba584f58a8ed024;hb=refs/heads/master moodle_database.php]&lt;br /&gt;
* All the $table parameters in the functions are meant to be the table name &#039;&#039;without&#039;&#039; prefixes.&lt;br /&gt;
&amp;lt;code php&amp;gt;$user = $DB-&amp;gt;get_record(&#039;user&#039;, array(&#039;id&#039;=&amp;gt;&#039;1&#039;));&amp;lt;/code&amp;gt;&lt;br /&gt;
* When using the xxx_sql() functions, table names must be enclosed between curly braces.&lt;br /&gt;
&amp;lt;code php&amp;gt;$user = $DB-&amp;gt;get_record_sql(&#039;SELECT * FROM {user} WHERE id = ?&#039;, array(1));&amp;lt;/code&amp;gt;&lt;br /&gt;
* All the $conditions parameters in the functions are arrays of fieldname=&amp;gt;fieldvalue elements.&lt;br /&gt;
&amp;lt;code php&amp;gt;$user = $DB-&amp;gt;get_record(&#039;user&#039;, array(&#039;firstname&#039;=&amp;gt;&#039;Martin&#039;, &#039;lastname&#039;=&amp;gt;&#039;Dougiamas&#039;));&amp;lt;/code&amp;gt;&lt;br /&gt;
* All the $params parameters in the functions are arrays of values used to fill placeholders in SQL statements. Both the question mark and named placeholders can be used. Note that named params &#039;&#039;&#039;must be unique&#039;&#039;&#039; even if the value passed is the same.&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
/// Question mark placeholders:&lt;br /&gt;
   $DB-&amp;gt;get_record_sql(&#039;SELECT * FROM {user} WHERE firstname = ? AND lastname = ?&#039;, &lt;br /&gt;
                       array(&#039;Martin&#039;, &#039;Dougiamas&#039;));&lt;br /&gt;
&lt;br /&gt;
/// Named placeholders:&lt;br /&gt;
   $DB-&amp;gt;get_record_sql(&#039;SELECT * FROM {user} WHERE firstname = :firstname AND lastname = :lastname&#039;,&lt;br /&gt;
                       array(&#039;firstname&#039;=&amp;gt;&#039;Martin&#039;, &#039;lastname&#039;=&amp;gt;&#039;Dougiamas&#039;));&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== The functions ==&lt;br /&gt;
&lt;br /&gt;
===Getting a single record===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
o $DB-&amp;gt;get_record($table, array $conditions, $fields=&#039;*&#039;, $strictness=IGNORE_MISSING) &lt;br /&gt;
  /// Get a single database record as an object where all the given conditions met.&lt;br /&gt;
  /// @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;&lt;br /&gt;
  ///                        IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);&lt;br /&gt;
  ///                        MUST_EXIST means throw exception if no record or multiple records found&lt;br /&gt;
o $DB-&amp;gt;get_record_select($table, $select, array $params=null, $fields=&#039;*&#039;, $strictness=IGNORE_MISSING)&lt;br /&gt;
  /// Get a single database record as an object which match a particular WHERE clause.&lt;br /&gt;
o $DB-&amp;gt;get_record_sql($sql, array $params=null, $strictness=IGNORE_MISSING)&lt;br /&gt;
  /// Get a single database record as an object using a SQL statement.&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Getting a hashed array of records===&lt;br /&gt;
Each of the following methods return an array of objects. The array is indexed by the first column of the fields returned by the query. Thus to assure consistent data, it appears to be best practice to ensure that your query include an &amp;quot;id column&amp;quot; as the first field. (When developing custom tables, be sure to make id your first column for this reason!)&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
o $DB-&amp;gt;get_records($table, array $conditions=null, $sort=&#039;&#039;, $fields=&#039;*&#039;, $limitfrom=0, $limitnum=0) &lt;br /&gt;
  /// Get a number of records as an array of objects where all the given conditions met.&lt;br /&gt;
o $DB-&amp;gt;get_records_select($table, $select, array $params=null, $sort=&#039;&#039;, $fields=&#039;*&#039;, $limitfrom=0, $limitnum=0) &lt;br /&gt;
  /// Get a number of records as an array of objects which match a particular WHERE clause.&lt;br /&gt;
o $DB-&amp;gt;get_records_sql($sql, array $params=null, $limitfrom=0, $limitnum=0)&lt;br /&gt;
  /// Get a number of records as an array of objects using a SQL statement.&lt;br /&gt;
o $DB-&amp;gt;get_records_list($table, $field, array $values, $sort=&#039;&#039;, $fields=&#039;*&#039;, $limitfrom=&#039;&#039;, $limitnum=&#039;&#039;) &lt;br /&gt;
  /// Get a number of records as an array of objects where one field match one list of values.&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Getting data as key/value pairs in an associative array===&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
o $DB-&amp;gt;get_records_menu($table, array $conditions=null, $sort=&#039;&#039;, $fields=&#039;*&#039;, $limitfrom=0, $limitnum=0) &lt;br /&gt;
  /// Get the first two columns from a number of records as an associative array where all the given conditions met.&lt;br /&gt;
o $DB-&amp;gt;get_records_select_menu($table, $select, array $params=null, $sort=&#039;&#039;, $fields=&#039;*&#039;, $limitfrom=0, $limitnum=0)&lt;br /&gt;
  /// Get the first two columns from a number of records as an associative array which match a particular WHERE clause.&lt;br /&gt;
o $DB-&amp;gt;get_records_sql_menu($sql, array $params=null, $limitfrom=0, $limitnum=0)&lt;br /&gt;
  /// Get the first two columns from a number of records as an associative array using a SQL statement.&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Seeing how many records match a given criterion===&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
o $DB-&amp;gt;count_records($table, array $conditions=null) &lt;br /&gt;
  /// Count the records in a table where all the given conditions met.&lt;br /&gt;
o $DB-&amp;gt;count_records_select($table, $select, array $params=null, $countitem=&amp;quot;COUNT(&#039;x&#039;)&amp;quot;) &lt;br /&gt;
  /// Count the records in a table which match a particular WHERE clause.&lt;br /&gt;
o $DB-&amp;gt;count_records_sql($sql, array $params=null) &lt;br /&gt;
  /// Get the result of an SQL SELECT COUNT(...) query.&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Seeing if one record exists===&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
o $DB-&amp;gt;record_exists($table, array $conditions=null) &lt;br /&gt;
  /// Test whether a record exists in a table where all the given conditions met.&lt;br /&gt;
o $DB-&amp;gt;record_exists_select($table, $select, array $params=null) &lt;br /&gt;
  /// Test whether any records exists in a table which match a particular WHERE clause.&lt;br /&gt;
o $DB-&amp;gt;record_exists_sql($sql, array $params=null) &lt;br /&gt;
  /// Test whether a SQL SELECT statement returns any records.&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Examples====&lt;br /&gt;
=====moodle_database::get_records()=====&lt;br /&gt;
Get a number of records as an array of objects where all the given conditions met.&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
///Get all records where foo = bar&lt;br /&gt;
$result = $DB-&amp;gt;get_records($table,array(&#039;foo&#039;=&amp;gt;&#039;bar&#039;));&lt;br /&gt;
&lt;br /&gt;
///Get all records where foo = bar and jon = doe&lt;br /&gt;
$result = $DB-&amp;gt;get_records($table,array(&#039;foo&#039; =&amp;gt; &#039;bar&#039; , &#039;jon&#039; =&amp;gt; &#039;doe&#039;));&lt;br /&gt;
&lt;br /&gt;
///Get all records where foo = bar, but only return the fields foo,bar,jon,doe&lt;br /&gt;
$result = $DB-&amp;gt;get_records($table,array(&#039;foo&#039;=&amp;gt;&#039;bar&#039;),null,&#039;foo,bar,jon,doe&#039;);&lt;br /&gt;
///The previous example would cause data issues unless the &#039;foo&#039; field happens to have unique values.&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=====moodle_database::get_records_select()=====&lt;br /&gt;
Get a number of records as an array of objects which match a particular WHERE clause. Note that the array keys will be the id of the object so you must not rely on the first item having a key of 0.&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
///Get all records where jon = &#039;doe&#039; and bob is not = &#039;tom&#039;&lt;br /&gt;
///The &#039;select&#039; parameter is (if not empty) is dropped directly into the WHERE clause without alteration.&lt;br /&gt;
$table = &#039;foo&#039;;&lt;br /&gt;
$select = &amp;quot;jon = &#039;doe&#039; AND bob &amp;lt;&amp;gt; &#039;tom&#039;&amp;quot;; //is put into the where clause&lt;br /&gt;
$result = $DB-&amp;gt;get_records_select($table,$select);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=====moodle_database::get_records_sql()=====&lt;br /&gt;
Get a number of records as an array of objects using a SQL statement. Defined as an abstract function in moodle_database, this method is implemented per database type.&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
///Get all records from &#039;table&#039; where foo = bar&lt;br /&gt;
$result = $DB-&amp;gt;get_records_sql(&#039;SELECT * FROM {table} WHERE foo = ?&#039;, array(&#039;bar&#039;));&lt;br /&gt;
&lt;br /&gt;
///Get all records from &#039;table&#039; where foo = &#039;bar&#039; and bob = &#039;tom&#039;&lt;br /&gt;
///This is somewhat similar to how Drupal makes its queries&lt;br /&gt;
$result = $DB-&amp;gt;get_records_sql(&#039;SELECT * FROM {table} WHERE foo = ? AND bob = ?&#039;, array( &#039;bar&#039; , &#039;tom&#039; ));&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=====moodle_database::get_records_list()=====&lt;br /&gt;
Get a number of records as an array of objects where one field match one list of values.&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
///Get all records where the values(&#039;bar&#039;, &#039;elephant&#039;, &#039;moodle&#039;) are found in the field &#039;foo&#039;&lt;br /&gt;
$result = $DB-&amp;gt;get_records_list($table, &#039;foo&#039;, array( &#039;bar&#039;, &#039;elephant&#039;, &#039;moodle&#039;));&lt;br /&gt;
&lt;br /&gt;
///Get all records where the values(&#039;bar&#039;, &#039;elephant&#039;, &#039;moodle&#039;) are found in the field &#039;foo&#039;&lt;br /&gt;
///Only returning the fields &#039;id&#039;, &#039;test&#039; and &#039;taco&#039;&lt;br /&gt;
$result = $DB-&amp;gt;get_records_list($table, &#039;foo&#039;, array( &#039;bar&#039;, &#039;elephant&#039;, &#039;moodle&#039;), null, &#039;id,test,taco&#039;);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=====moodle_database::get_records_menu()=====&lt;br /&gt;
Get the first two columns from a number of records as an associative array where all the given conditions met. &lt;br /&gt;
You can choose the two fields or leave the parameter blank and the method will return the first two columns of the table.&lt;br /&gt;
Returns an associative array. &lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
///Get all records from table &#039;foo&#039; where column &#039;foo&#039; is equal to the value &#039;bar&#039;&lt;br /&gt;
$table = &#039;foo&#039;; ///name of table&lt;br /&gt;
$conditions = array(&#039;foo&#039;=&amp;gt;&#039;bar&#039;); ///the name of the field (key) and the desired value&lt;br /&gt;
&lt;br /&gt;
$result = $DB-&amp;gt;get_records_menu($table,$conditions));&lt;br /&gt;
&lt;br /&gt;
///Get all records from table &#039;foo&#039; where column &#039;foo&#039; is equal to the value &#039;bar&#039;&lt;br /&gt;
///Returning the values from the columns &#039;id&#039; and &#039;tacos&#039;&lt;br /&gt;
$table = &#039;foo&#039;; ///name of table&lt;br /&gt;
$conditions = array(&#039;foo&#039;=&amp;gt;&#039;bar&#039;); ///the name of the field (key) and the desired value&lt;br /&gt;
$sort = &#039;id&#039;; //field or fields you want to sort the result by&lt;br /&gt;
$fields = &#039;id, tacos&#039;; ///list of fields to return&lt;br /&gt;
&lt;br /&gt;
$result = $DB-&amp;gt;get_records_menu($table,$conditions,$sort,$fields));  //If you do not specify $fields, the first two columns of the table will be returned&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
The result of this last example will look something like:&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
/// The value of the id field  is 909 and the value of the &#039;tacos&#039; column is 6&lt;br /&gt;
array(1) { [909]=6 }&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=====moodle_database::get_records_select_menu()=====&lt;br /&gt;
Get the first two columns from a number of records as an associative array which match a particular WHERE clause.&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
///Get all records where jon = &#039;doe&#039; and bob is not = &#039;tom&#039;&lt;br /&gt;
///The &#039;select&#039; parameter is (if not empty) is dropped directly into the WHERE clause without alteration.&lt;br /&gt;
$table = &#039;foo&#039;;&lt;br /&gt;
$select = &#039;jon = ? AND bob &amp;lt;&amp;gt; ? &#039;; //is put into the where clause&lt;br /&gt;
$result = $DB-&amp;gt;get_records_select_menu($table, $select, array(&#039;doe&#039;, &#039;tom&#039;));&lt;br /&gt;
&lt;br /&gt;
$table = &#039;foo&#039;;&lt;br /&gt;
$select = &#039;jon = ? AND bob &amp;lt;&amp;gt; ? &#039;; //is put into the where clause&lt;br /&gt;
$params = array(&#039;doe&#039;, &#039;tom&#039;);&lt;br /&gt;
$fields = &#039;id, tacos&#039;;//return these fields&lt;br /&gt;
$sort = &#039;id&#039;; //field or fields you want to sort the result by&lt;br /&gt;
$result = $DB-&amp;gt;get_records_select_menu($table,$select,$params,$sort,$fields);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The result of this last example will look something like:&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
/// The value of the id field  is 909 and the value of the &#039;tacos&#039; column is 6&lt;br /&gt;
array(1) { [909]=6 }&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=====moodle_database::get_records_sql_menu()=====&lt;br /&gt;
Get the first two columns from a number of records as an associative array using a SQL statement.&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
///Get all records from table foo where bar = 6&lt;br /&gt;
$sql = &#039;SELECT * FROM foo WHERE bar = ?&#039;;&lt;br /&gt;
$params = array(6);&lt;br /&gt;
&lt;br /&gt;
$result = $DB-&amp;gt;get_records_sql_menu($sql,$params);&lt;br /&gt;
&lt;br /&gt;
///Get all records from table foo where bar = 6&lt;br /&gt;
$sql = &#039;SELECT id,tacos FROM foo WHERE bar = ?&#039;;&lt;br /&gt;
$params = array(6);&lt;br /&gt;
&lt;br /&gt;
$result = $DB-&amp;gt;get_records_sql_menu($sql,$params);&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The result of this last example will look something like:&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
/// The value of the id field  is 909 and the value of the &#039;tacos&#039; column is 6&lt;br /&gt;
array(1) { [909]=6 } &lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Getting a particular field value from one record===&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
o $DB-&amp;gt;get_field($table, $return, array $conditions, $strictness=IGNORE_MISSING)&lt;br /&gt;
  /// Get a single field value from a table record where all the given conditions met.&lt;br /&gt;
  /// @param int $strictness&lt;br /&gt;
  ///   IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;&lt;br /&gt;
  ///   IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);&lt;br /&gt;
  ///   MUST_EXIST means throw exception if no record or multiple records found&lt;br /&gt;
o $DB-&amp;gt;get_field_select($table, $return, $select, array $params=null, $strictness=IGNORE_MISSING)&lt;br /&gt;
  /// Get a single field value from a table record which match a particular WHERE clause.&lt;br /&gt;
o $DB-&amp;gt;get_field_sql($sql, array $params=null, $strictness=IGNORE_MISSING)&lt;br /&gt;
  /// Get a single field value (first field) using a SQL statement.&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Getting a particular field value from various records===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
o $DB-&amp;gt;get_fieldset_select($table, $return, $select, array $params=null)&lt;br /&gt;
  /// Selects records and return values of chosen field as an array which match a particular WHERE clause.&lt;br /&gt;
o $DB-&amp;gt;get_fieldset_sql($sql, array $params=null)&lt;br /&gt;
  /// Selects records and return values (first field) as an array using a SQL statement.&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Setting a particular field in the database===&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
o $DB-&amp;gt;set_field($table, $newfield, $newvalue, array $conditions=null)&lt;br /&gt;
  /// Set a single field in every table record where all the given conditions met.&lt;br /&gt;
o $DB-&amp;gt;set_field_select($table, $newfield, $newvalue, $select, array $params=null)&lt;br /&gt;
  /// Set a single field in every table record which match a particular WHERE clause.&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Deleting Records===&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
o $DB-&amp;gt;delete_records($table, array $conditions=null) &lt;br /&gt;
  /// Delete the records from a table where all the given conditions met.&lt;br /&gt;
o $DB-&amp;gt;delete_records_select($table, $select, array $params=null)&lt;br /&gt;
  /// Delete one or more records from a table which match a particular WHERE clause.&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Inserting Records===&lt;br /&gt;
The method to insert records is called aptly enough, insert_record(). The method accepts 4 parameters, but the fourth, &amp;quot;bulk&amp;quot;, in most implementations is unused. Note, you cannot specify the record id using this method. If you need to specify an id use $DB-&amp;gt;insert_record_raw() with $customsequence set to true or use $DB-&amp;gt;execute().&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
  $DB-&amp;gt;insert_record($table, $dataobject, $returnid=true, $bulk=false) &lt;br /&gt;
  /// Insert a record into a table and return the &amp;quot;id&amp;quot; field if required.&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Starting with Moodle 2.7, you can do bulk record inserts using the following method call: {{Moodle_2.7}} &lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
/**&lt;br /&gt;
* Insert multiple records into database as fast as possible.&lt;br /&gt;
*&lt;br /&gt;
* Order of inserts is maintained, but the operation is not atomic, use transactions if necessary.&lt;br /&gt;
*&lt;br /&gt;
* This method is intended for inserting of large number of small objects, do not use for huge objects with text or binary fields.&lt;br /&gt;
*&lt;br /&gt;
* @param string $table  The database table to be inserted into&lt;br /&gt;
* @param array|Traversable $dataobjects list of objects to be inserted, must be compatible with foreach&lt;br /&gt;
* @return void&lt;br /&gt;
*/&lt;br /&gt;
  $DB-&amp;gt;insert_records($table, $dataobjects)&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Example(s)====&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$record = new stdClass();&lt;br /&gt;
$record-&amp;gt;name         = &#039;overview&#039;;&lt;br /&gt;
$record-&amp;gt;displayorder = &#039;10000&#039;;&lt;br /&gt;
$lastinsertid = $DB-&amp;gt;insert_record(&#039;quiz_report&#039;, $record, false);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$record1 = new stdClass();&lt;br /&gt;
$record1-&amp;gt;name         = &#039;overview&#039;;&lt;br /&gt;
$record1-&amp;gt;displayorder = &#039;10000&#039;;&lt;br /&gt;
$record2 = new stdClass();&lt;br /&gt;
$record2-&amp;gt;name         = &#039;overview&#039;;&lt;br /&gt;
$record2-&amp;gt;displayorder = &#039;10000&#039;;&lt;br /&gt;
$records = array($record1, $record2);&lt;br /&gt;
$DB-&amp;gt;insert_records(&#039;quiz_report&#039;, $records);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Updating Records===&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
o $DB-&amp;gt;update_record($table, $dataobject, $bulk=false)&lt;br /&gt;
  /// Update a record in a table.&lt;br /&gt;
  /// &lt;br /&gt;
  /// $dataobject is an object containing needed data&lt;br /&gt;
  /// Relies on $dataobject having a variable &amp;quot;id&amp;quot; to&lt;br /&gt;
  /// specify the record to update&lt;br /&gt;
  /// &lt;br /&gt;
  /// @param string $table The database table to be checked against.&lt;br /&gt;
  /// @param object $dataobject An object with contents equal to fieldname=&amp;gt;fieldvalue.&lt;br /&gt;
  ///        Must have an entry for &#039;id&#039; to map to the table specified.&lt;br /&gt;
  /// @param bool $bulk true means repeated updates expected&lt;br /&gt;
  /// @return bool true&lt;br /&gt;
  /// @throws dml_exception if an error occurs.&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you need to perform a more complex update using arbitrary SQL, you can use the &#039;execute&#039; method. Only use this when nothing more specific will work&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
o $DB-&amp;gt;execute($sql, array $params=null)&lt;br /&gt;
  /// Executes a general sql query. Should be used only when no other method suitable.&lt;br /&gt;
  /// Do NOT use this to make changes in db structure, use database_manager methods instead!&lt;br /&gt;
  /// @param string $sql query&lt;br /&gt;
  /// @param array $params query parameters&lt;br /&gt;
  /// @return bool true&lt;br /&gt;
  /// @throws dml_exception A DML specific exception is thrown for any errors.&lt;br /&gt;
 &amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Using Recordsets===&lt;br /&gt;
&lt;br /&gt;
Where the number of records to be retrieved from DB is high, the &#039;&#039;&#039;get_records_xxx()&#039;&#039;&#039; functions above are far from optimal, because they load all the records in memory at the same time. Under those circumstances, it is highly recommended to use these &#039;&#039;&#039;get_recordset_xxx()&#039;&#039;&#039; functions instead, which use one nice mechanism to iterate over all the target records and save a lot of memory.&lt;br /&gt;
&lt;br /&gt;
Only one thing is &#039;&#039;&#039;absolutely important&#039;&#039;&#039;: Don&#039;t forget to close the recordsets after using them! (This will free up a lot of resources in the RDBMS).&lt;br /&gt;
&lt;br /&gt;
Here is the general way to iterate over records using the &#039;&#039;&#039;get_recordset_xxx()&#039;&#039;&#039; functions:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$rs = $DB-&amp;gt;get_recordset(....) {&lt;br /&gt;
foreach ($rs as $record) {&lt;br /&gt;
    // Do whatever you want with this record&lt;br /&gt;
}&lt;br /&gt;
$rs-&amp;gt;close(); // Don&#039;t forget to close the recordset!&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
And this is the list of available functions (100% paired with the get_records_xxx() above):&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
o $DB-&amp;gt;get_recordset($table, array $conditions=null, $sort=&#039;&#039;, $fields=&#039;*&#039;, $limitfrom=0, $limitnum=0) &lt;br /&gt;
  /// Get a number of records as a moodle_recordset where all the given conditions met.&lt;br /&gt;
o $DB-&amp;gt;get_recordset_select($table, $select, array $params=null, $sort=&#039;&#039;, $fields=&#039;*&#039;, $limitfrom=0, $limitnum=0) &lt;br /&gt;
  /// Get a number of records as a moodle_recordset which match a particular WHERE clause.&lt;br /&gt;
o $DB-&amp;gt;get_recordset_sql($sql, array $params=null, $limitfrom=0, $limitnum=0);&lt;br /&gt;
  /// Get a number of records as a moodle_recordset using a SQL statement.&lt;br /&gt;
 &lt;br /&gt;
o $DB-&amp;gt;get_recordset_list($table, $field=&#039;&#039;, $values=&#039;&#039;, $sort=&#039;&#039;, $fields=&#039;*&#039;, $limitfrom=&#039;&#039;, $limitnum=&#039;&#039;) &lt;br /&gt;
  /// Get a number of records as a moodle_recordset where one field matches one list of values.&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Unlike get_record functions, you cannot use &amp;lt;tt&amp;gt;$rs == true&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;!empty($rs)&amp;lt;/tt&amp;gt; to determine if any records were found.&lt;br /&gt;
Recordsets implement the standard PHP Iterator interface (http://uk.php.net/manual/en/class.iterator.php)&lt;br /&gt;
&lt;br /&gt;
So,&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
if ($rs-&amp;gt;valid()) {&lt;br /&gt;
    // The recordset contains records.&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Delegated transactions===&lt;br /&gt;
&lt;br /&gt;
* Please note some databases do not support transactions (such as the MyISAM MySQL database engine), however all server administrators are strongly encouraged to migrate to databases that support transactions (such as the InnoDB MySQL database engine).&lt;br /&gt;
* Previous versions supported only one level of transaction. Since Moodle 2.0, the DML layer emulates delegated transactions that allow nesting of transactions.&lt;br /&gt;
* Transactions should not be used much in Moodle core; they are intended for various plugins such as web services, enrol and auth plugins.&lt;br /&gt;
* Some subsystems (such as messaging) do not support transactions because is it is not possible to rollback in external systems.&lt;br /&gt;
&lt;br /&gt;
A transaction is started by:&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$transaction = $DB-&amp;gt;start_delegated_transaction();&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and finished by:&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$transaction-&amp;gt;allow_commit();&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Usually a transaction is rolled back when an exception is thrown. &amp;lt;code&amp;gt;$transaction-&amp;gt;rollback($ex);&amp;lt;/code&amp;gt; must be used very carefully because it might break compatibility with databases that do not support transactions. Transactions cannot be used as part of expected code flow; they can be used only as an emergency protection of data consistency.&lt;br /&gt;
&lt;br /&gt;
See more details in [[DB layer 2.0 delegated transactions]] or MDL-20625.&lt;br /&gt;
&lt;br /&gt;
====Example(s)====&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
global $DB;&lt;br /&gt;
try {&lt;br /&gt;
     $transaction = $DB-&amp;gt;start_delegated_transaction();&lt;br /&gt;
     // Insert a record&lt;br /&gt;
     $DB-&amp;gt;insert_record(&#039;foo&#039;, $object);&lt;br /&gt;
     $DB-&amp;gt;insert_record(&#039;bar&#039;, $otherobject);&lt;br /&gt;
&lt;br /&gt;
     // Assuming the both inserts work, we get to the following line.&lt;br /&gt;
     $transaction-&amp;gt;allow_commit();&lt;br /&gt;
} catch(Exception $e) {&lt;br /&gt;
     $transaction-&amp;gt;rollback($e);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===SQL compatibility functions===&lt;br /&gt;
&lt;br /&gt;
In order have real cross-db compatibility, there are some helper functions used to build SQL fragments based on the DB Moodle is running. Using them we&#039;ll avoid conditional queries here and there and have those &amp;quot;incompatibilities&amp;quot; fixed once and for ever.&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
o $DB-&amp;gt;sql_bitand($int1, $int2) &lt;br /&gt;
  /// Returns the SQL text to be used in order to perform one bitwise AND &lt;br /&gt;
  /// operation between 2 integers.&lt;br /&gt;
o $DB-&amp;gt;sql_bitnot($int1) &lt;br /&gt;
  /// Returns the SQL text to be used in order to perform one bitwise NOT &lt;br /&gt;
  /// operation with 1 integer.&lt;br /&gt;
o $DB-&amp;gt;sql_bitor($int1, $int2)&lt;br /&gt;
  /// Returns the SQL text to be used in order to perform one bitwise OR &lt;br /&gt;
  /// operation between 2 integers.&lt;br /&gt;
o $DB-&amp;gt;sql_bitxor($int1, $int2) &lt;br /&gt;
  /// Returns the SQL text to be used in order to perform one bitwise XOR &lt;br /&gt;
  /// operation between 2 integers.&lt;br /&gt;
 &lt;br /&gt;
o $DB-&amp;gt;sql_null_from_clause()&lt;br /&gt;
  /// Returns the FROM clause required by some DBs in all SELECT statements.&lt;br /&gt;
 &lt;br /&gt;
o $DB-&amp;gt;sql_ceil($fieldname)&lt;br /&gt;
  /// Returns the correct CEIL expression applied to fieldname.&lt;br /&gt;
o $DB-&amp;gt;sql_equal($fieldname, $param, $casesensitive = true, $accentsensitive = true, $notequal = false) (available since Moodle 3.2)&lt;br /&gt;
  /// Returns the proper SQL to perform cross-db varchar comparisons when case-sensitiveness is mission-critical.&lt;br /&gt;
o $DB-&amp;gt;sql_like($fieldname, $param, $casesensitive = true, $accentsensitive = true, $notlike = false, $escapechar = &#039; \\ &#039;)&lt;br /&gt;
  /// Returns the proper SQL to do LIKE. For example:&lt;br /&gt;
  $DB-&amp;gt;get_records_sql(&#039;SELECT ...  WHERE &#039;.$DB-&amp;gt;sql_like(&#039;idnumber&#039;, &#039;:idnum&#039;).&#039; ... &#039;, array( &#039;idnum&#039; =&amp;gt; &#039;%foo%&#039;));&lt;br /&gt;
  /// Note: Apply $DB-&amp;gt;sql_like_escape(...) to the param values when its user input from a form. Don&#039;t forget to add the % character(s) to the param value&lt;br /&gt;
&lt;br /&gt;
o $DB-&amp;gt;sql_length($fieldname)&lt;br /&gt;
  /// Returns the SQL text to be used to calculate the length in characters of one expression.&lt;br /&gt;
o $DB-&amp;gt;sql_modulo($int1, $int2)&lt;br /&gt;
  /// Returns the SQL text to be used in order to calculate module - remainder after division&lt;br /&gt;
o $DB-&amp;gt;sql_position($needle, $haystack)&lt;br /&gt;
  /// Returns the SQL for returning searching one string for the location of another.&lt;br /&gt;
  /// Note: If using placeholders BOTH in $needle and $haystack, they MUST be named placeholders.&lt;br /&gt;
o $DB-&amp;gt;sql_substr($expr, $start, $length=false)&lt;br /&gt;
  /// Returns the proper substr() SQL text used to extract substrings from DB.&lt;br /&gt;
  /// Note: This fuction has changed in Moodle 2.0 and now at least 2 params are mandatory.&lt;br /&gt;
  /// Note: Now it returns the whole SQL text to be used instead of only the function name.&lt;br /&gt;
 &lt;br /&gt;
o $DB-&amp;gt;sql_cast_char2int($fieldname, $text=false)&lt;br /&gt;
  /// Returns the SQL to be used in order to CAST one CHAR column to INTEGER.&lt;br /&gt;
o $DB-&amp;gt;sql_cast_char2real($fieldname, $text=false)&lt;br /&gt;
  /// Returns the SQL to be used in order to CAST one CHAR column to REAL number.&lt;br /&gt;
 &lt;br /&gt;
o $DB-&amp;gt;sql_compare_text($fieldname, $numchars=32) &lt;br /&gt;
  /// Returns the SQL text to be used to compare one TEXT (clob) column.&lt;br /&gt;
  /// with one VARCHAR column.&lt;br /&gt;
o $DB-&amp;gt;sql_order_by_text($fieldname, $numchars=32)&lt;br /&gt;
  /// Returns the SQL text to be used to order by one TEXT (clob) column.&lt;br /&gt;
 &lt;br /&gt;
o $DB-&amp;gt;sql_concat()&lt;br /&gt;
  /// Returns the proper SQL to do CONCAT between the elements passed.&lt;br /&gt;
o $DB-&amp;gt;sql_concat_join($separator=&amp;quot;&#039; &#039;&amp;quot;, $elements=array())&lt;br /&gt;
  /// Returns the proper SQL to do CONCAT between the elements passed using one separator.&lt;br /&gt;
o $DB-&amp;gt;sql_fullname($first=&#039;firstname&#039;, $last=&#039;lastname&#039;)&lt;br /&gt;
  /// Returns the proper SQL to concatenate $firstname and $lastname.&lt;br /&gt;
 &lt;br /&gt;
o $DB-&amp;gt;sql_isempty($tablename, $fieldname, $nullablefield, $textfield)&lt;br /&gt;
  /// Returns the proper SQL to know if one field is empty.&lt;br /&gt;
o $DB-&amp;gt;sql_isnotempty($tablename, $fieldname, $nullablefield, $textfield)&lt;br /&gt;
  /// Returns the proper SQL to know if one field is not empty.&lt;br /&gt;
&lt;br /&gt;
o $DB-&amp;gt;get_in_or_equal($items, $type=SQL_PARAMS_QM, $prefix=&#039;param&#039;, $equal=true, $onemptyitems=false)&lt;br /&gt;
  /// Constructs &#039;IN()&#039; or &#039;=&#039; sql fragment&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Debug fuctions===&lt;br /&gt;
&lt;br /&gt;
If you execute&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$DB-&amp;gt;set_debug(true)&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
then $DB will outout the SQL of every query executed, along with timing information. This can be useful when debugging your code. Obviously, all such calls should be removed before code is submitted for integration.&lt;br /&gt;
&lt;br /&gt;
==Special cases==&lt;br /&gt;
&lt;br /&gt;
===get_course===&lt;br /&gt;
&lt;br /&gt;
From Moodle 2.5.1 onwards, you should use the get_course function instead of using get_record(&#039;course&#039;, ...) if you want to get a course record based on its ID, especially if there is a significant possibility that the course being retrieved is either the current course for the page, or the site course. Those two course records have probably already been loaded, and using this function will save a database query. &lt;br /&gt;
&lt;br /&gt;
As another advantage, the code is shorter and easier to read.&lt;br /&gt;
&lt;br /&gt;
Replace:&lt;br /&gt;
&lt;br /&gt;
    $course = $DB-&amp;gt;get_record(&#039;course&#039;, array(&#039;id&#039; =&amp;gt; $courseid), &#039;*&#039;, MUST_EXIST);&lt;br /&gt;
&lt;br /&gt;
With:&lt;br /&gt;
 &lt;br /&gt;
    $course = get_course($courseid);&lt;br /&gt;
&lt;br /&gt;
===get_courses===&lt;br /&gt;
&lt;br /&gt;
If you want to get all the current courses in your Moodle, use get_courses() without parameter:&lt;br /&gt;
&lt;br /&gt;
    $courses = get_courses();&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==See also==&lt;br /&gt;
&lt;br /&gt;
* [[SQL coding style]]&lt;br /&gt;
* [[Core APIs]]&lt;br /&gt;
* [[DML exceptions|DML exceptions]]: New DML code is throwing exceptions instead of returning false if anything goes wrong&lt;br /&gt;
* [[DML drivers|DML drivers]]: Database drivers for new DML layer&lt;br /&gt;
* [[DML functions - pre 2.0|DML functions - pre 2.0]]: &#039;&#039;&#039;(deprecated!)&#039;&#039;&#039; For information valid before Moodle 2.0.&lt;br /&gt;
* [[DDL functions|DDL functions]]: Where all the functions used to handle DB objects ([[wikipedia:Data_Definition_Language|DDL]]) are defined.&lt;br /&gt;
* [[DB layer 2.0 examples|DB layer 2.0 examples]]: To see some code examples using various DML functions.&lt;br /&gt;
* [[DB layer 2.0 migration docs|DB layer 2.0 migration docs]]: Information about how to modify your code to work with the new Moodle 2.0 DB layer.&lt;br /&gt;
* [[DTL functions|DTL functions]]: Exporting, importing and moving of data stored in SQL databases&lt;br /&gt;
&lt;br /&gt;
[[Category:DB]]&lt;br /&gt;
[[Category:XMLDB]]&lt;br /&gt;
[[Category:API]]&lt;/div&gt;</summary>
		<author><name>Marcojones</name></author>
	</entry>
	<entry>
		<id>https://docs.moodle.org/dev/index.php?title=Output_API&amp;diff=55257</id>
		<title>Output API</title>
		<link rel="alternate" type="text/html" href="https://docs.moodle.org/dev/index.php?title=Output_API&amp;diff=55257"/>
		<updated>2018-12-11T11:26:48Z</updated>

		<summary type="html">&lt;p&gt;Marcojones: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Template:Work in progress}}&lt;br /&gt;
&lt;br /&gt;
{{ Moodle 2.9 }}&lt;br /&gt;
&lt;br /&gt;
This page is a fresh attempt to explain how renderers, renderables, themes and templates all work together for Moodle 2.9. &lt;br /&gt;
&lt;br /&gt;
It will work with Moodle 3.x, if you additionally follow instructions given [https://moodle.org/mod/forum/discuss.php?d=322196 here] (creating version.php file).&lt;br /&gt;
&lt;br /&gt;
Lets start with building a page that is part of an admin tool.&lt;br /&gt;
&lt;br /&gt;
E.g. &lt;br /&gt;
/admin/tool/demo/index.php&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
// Standard GPL and phpdocs&lt;br /&gt;
require_once(__DIR__ . &#039;/../../../config.php&#039;);&lt;br /&gt;
require_once($CFG-&amp;gt;libdir.&#039;/adminlib.php&#039;);&lt;br /&gt;
&lt;br /&gt;
admin_externalpage_setup(&#039;tooldemo&#039;);&lt;br /&gt;
&lt;br /&gt;
// Set up the page.&lt;br /&gt;
$title = get_string(&#039;pluginname&#039;, &#039;tool_demo&#039;);&lt;br /&gt;
$pagetitle = $title;&lt;br /&gt;
$url = new moodle_url(&amp;quot;/admin/tool/demo/index.php&amp;quot;);&lt;br /&gt;
$PAGE-&amp;gt;set_url($url);&lt;br /&gt;
$PAGE-&amp;gt;set_title($title);&lt;br /&gt;
$PAGE-&amp;gt;set_heading($title);&lt;br /&gt;
&lt;br /&gt;
$output = $PAGE-&amp;gt;get_renderer(&#039;tool_demo&#039;);&lt;br /&gt;
&lt;br /&gt;
echo $output-&amp;gt;header();&lt;br /&gt;
echo $output-&amp;gt;heading($pagetitle);&lt;br /&gt;
&lt;br /&gt;
$renderable = new \tool_demo\output\index_page(&#039;Some text&#039;);&lt;br /&gt;
echo $output-&amp;gt;render($renderable);&lt;br /&gt;
&lt;br /&gt;
echo $output-&amp;gt;footer();&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Explaining this demo step by step we have firstly the standard config and includes, plus the admin_externalpage_setup(&#039;tooldemo&#039;) which calls require_login and performs permissions checks for admin pages.&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
&lt;br /&gt;
// Standard GPL and phpdocs&lt;br /&gt;
require_once(__DIR__ . &#039;/../../../config.php&#039;);&lt;br /&gt;
require_once($CFG-&amp;gt;libdir.&#039;/adminlib.php&#039;);&lt;br /&gt;
&lt;br /&gt;
admin_externalpage_setup(&#039;tooldemo&#039;);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Then we load the title of the page from a lang string (see [[String_API]] ). We use this string to set some $PAGE properties (url title and heading). &lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
   &lt;br /&gt;
// Set up the page.&lt;br /&gt;
$title = get_string(&#039;pluginname&#039;, &#039;tool_demo&#039;);&lt;br /&gt;
$pagetitle = $title;&lt;br /&gt;
$url = new moodle_url(&amp;quot;/admin/tool/demo/index.php&amp;quot;);&lt;br /&gt;
$PAGE-&amp;gt;set_url($url);&lt;br /&gt;
$PAGE-&amp;gt;set_title($title);&lt;br /&gt;
$PAGE-&amp;gt;set_heading($title);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
What is $PAGE and where did it come from ?&lt;br /&gt;
&lt;br /&gt;
$PAGE is a global variable used to track the state of the page that is being returned. It is an instance of the moodle_page class defined in lib/pagelib.php. See [[Page_API]] for more information on the $PAGE variable.&lt;br /&gt;
&lt;br /&gt;
The most important properties stored in $PAGE are the page context, the url, the layout, title and headings. $PAGE also gives access to some other important classes such as $PAGE-&amp;gt;requires, which is an instance of the page_requirements_manager (lib/outputrequirementslib.php). The page_requirements_manager class lets us set dependencies on e.g. javascript and css to be inserted in the correct place in the page (The order things are inserted in the page is hugely important for performance). &lt;br /&gt;
&lt;br /&gt;
$PAGE also lets us load specific renderers for a plugin, or plugin and subtype. We will cover renderers in more detail next.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$output = $PAGE-&amp;gt;get_renderer(&#039;tool_demo&#039;);&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This gets an instance of the plugin_renderer_base class that we use to create all output for our page. Themers can subclass this renderer to override specific render methods in order to customise Moodle&#039;s output. See [[Output_renderers]] for more information, and [[Overriding_a_renderer]] for information about how themers can customise a renderer. &lt;br /&gt;
&lt;br /&gt;
Note - some pages use the global variable $OUTPUT to generate their output. This is a generic renderer used for core pages etc, but plugins should always use a more specific plugin renderer. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
echo $output-&amp;gt;header();&lt;br /&gt;
echo $output-&amp;gt;heading($pagetitle);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This code prints the header of the page and adds one heading to the page at the top of the content region. Page headings are very important in Moodle and should be applied consistently. See [[HTML_Guidelines]] for more information on how and where to use  headings.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$renderable = new \tool_demo\output\index_page(&#039;Some text&#039;);&lt;br /&gt;
echo $output-&amp;gt;render($renderable);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is the most interesting part of our page. We are creating a renderable and telling our renderer to render it. The renderable is usually more complex than this, it should hold all the data required for the renderer to display the page. This means we should perform all our logic such as database queries, page parameters and access checks in advance and the results should be passed as data to the renderable. The renderable then just takes that data and returns a HTML representation of it. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
echo $output-&amp;gt;footer();&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This prints the HTML for the bottom of the page. It is very important because it also prints out things that were added to the page_requirements_manager and need to be printed in the footer. Things like javascript includes, navigation tree setup, closing open containers tags etc. The reason all javascripts are added to the footer of the page is for performance. If you add javascript includes to the top of the page, or inline with the content the browser must stop and execute the javascript before it can render the page. See https://developers.google.com/speed/docs/insights/BlockingJS for more information.&lt;br /&gt;
&lt;br /&gt;
In the code above, we created a renderable. This is a class that you have to add to your plugin. It holds all the data required to display something on the page. Here is the renderable for this example:&lt;br /&gt;
&lt;br /&gt;
/admin/tool/demo/classes/output/index_page.php&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
// Standard GPL and phpdocs&lt;br /&gt;
namespace tool_demo\output;                                                                                                         &lt;br /&gt;
                                                                                                                                    &lt;br /&gt;
use renderable;                                                                                                                     &lt;br /&gt;
use renderer_base;                                                                                                                  &lt;br /&gt;
use templatable;                                                                                                                    &lt;br /&gt;
use stdClass;                                                                                                                       &lt;br /&gt;
             &lt;br /&gt;
class index_page implements renderable, templatable {                                                                               &lt;br /&gt;
    /** @var string $sometext Some text to show how to pass data to a template. */                                                  &lt;br /&gt;
    var $sometext = null;                                                                                                           &lt;br /&gt;
            &lt;br /&gt;
    public function __construct($sometext) {                                                                                        &lt;br /&gt;
        $this-&amp;gt;sometext = $sometext;                                                                                                &lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    /**                                                                                                                             &lt;br /&gt;
     * Export this data so it can be used as the context for a mustache template.                                                   &lt;br /&gt;
     *                                                                                                                              &lt;br /&gt;
     * @return stdClass                                                                                                             &lt;br /&gt;
     */                                                                                                                             &lt;br /&gt;
    public function export_for_template(renderer_base $output) {                                                                    &lt;br /&gt;
        $data = new stdClass();                                                                                                     &lt;br /&gt;
        $data-&amp;gt;sometext = $this-&amp;gt;sometext;                                                                                          &lt;br /&gt;
        return $data;                                                                                                               &lt;br /&gt;
    }&lt;br /&gt;
}         &lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This class implements the renderable interface, which has no methods, and the templatable interface, which means that this class could be rendered with a template, so it must implement the &amp;quot;export_for_template&amp;quot; method. So in this example, the class accepts data via it&#039;s constructor, and stores that data in class variables. It does nothing else fancy with the data in this example (but it could). Note that the export_for_template function should only return simple types (arrays, stdClass, bool, int, float, string).&lt;br /&gt;
&lt;br /&gt;
Now lets look at the renderer for this plugin.&lt;br /&gt;
&lt;br /&gt;
admin/tool/demo/classes/output/renderer.php&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
// Standard GPL and phpdocs&lt;br /&gt;
namespace tool_demo\output;                                                                                                         &lt;br /&gt;
                                                                                                                                    &lt;br /&gt;
defined(&#039;MOODLE_INTERNAL&#039;) || die;                                                                                                  &lt;br /&gt;
                                                                                                                                    &lt;br /&gt;
use plugin_renderer_base;  &lt;br /&gt;
&lt;br /&gt;
class renderer extends plugin_renderer_base {&lt;br /&gt;
    /**                                                                                                                             &lt;br /&gt;
     * Defer to template.                                                                                                           &lt;br /&gt;
     *                                                                                                                              &lt;br /&gt;
     * @param index_page $page                                                                                                      &lt;br /&gt;
     *                                                                                                                              &lt;br /&gt;
     * @return string html for the page                                                                                             &lt;br /&gt;
     */                                                                                                                             &lt;br /&gt;
    public function render_index_page($page) {                                                                                      &lt;br /&gt;
        $data = $page-&amp;gt;export_for_template($this);                                                                                  &lt;br /&gt;
        return parent::render_from_template(&#039;tool_demo/index_page&#039;, $data);                                                         &lt;br /&gt;
    }           &lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The renderer exists to provide render_x methods for all renderables used in the plugin. A theme designer can provide a custom version of this renderer that changes the behaviour of any of the render methods and so to customize their theme. In this example, the render method for the index page (render_index_page) does 2 things. It asks the renderable to export it&#039;s data so that it is suitable for passing as the context to a template, and then renders a specific template with this context. A themer could either manipulate the data in the render method (e.g. removing menu entries), or change the template (change the generated html) to customize the output. &lt;br /&gt;
&lt;br /&gt;
The template used in this plugin is located in the plugins templates folder. The template can also be overridden by a themer. &lt;br /&gt;
&lt;br /&gt;
admin/tool/demo/templates/index_page.mustache&lt;br /&gt;
&amp;lt;code xml&amp;gt;&lt;br /&gt;
&amp;lt;div class=&amp;quot;hero-unit&amp;quot;&amp;gt;                                                                                                             &lt;br /&gt;
  &amp;lt;h1&amp;gt;Heading&amp;lt;/h1&amp;gt;                                                                                                                  &lt;br /&gt;
  &amp;lt;p&amp;gt;{{sometext}}&amp;lt;/p&amp;gt;                                                                                                               &lt;br /&gt;
&amp;lt;/div&amp;gt; &lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This is the mustache template for this demo. It uses some bootstrap classes directly to position and style the content on the page. {{sometext}} is replaced with the variable from the context when this template is rendered. For more information on templates see [[Templates]].&lt;/div&gt;</summary>
		<author><name>Marcojones</name></author>
	</entry>
</feed>