Note:

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

Moodle App Plugins Development Guide: Difference between revisions

From MoodleDocs
No edit summary
(39 intermediate revisions by 10 users not shown)
Line 4: Line 4:
==Before 3.5==
==Before 3.5==


Since Moodle 3.1 Moodle plugins could be supported in the Mobile app, but only by writing an Angular JS/Ionic module, compiling it to a zip, and including that in your plugin. See [[Moodle Mobile Remote add-ons|Remote add-ons]] for details.
Since Moodle 3.1 Moodle plugins could be supported in the Mobile app, but only by writing an Angular JS/Ionic module, compiling it to a zip, and including that in your plugin. See [[Moodle_Mobile_2_(Ionic_1)_Remote_add-ons|Remote add-ons]] for details.


In Moodle 3.5 the app switched to a new way to suport plugins that was much easier for developers.
In Moodle 3.5 the app switched to a new way to support plugins that was much easier for developers.
* This new way will allow developers to support plugins using PHP code, templates and Ionic markup (html components).
* This new way will allow developers to support plugins using PHP code, templates and Ionic markup (html components).
* The use of JavaScript is optional (but some type of advanced plugins may require it)
* The use of JavaScript is optional (but some type of advanced plugins may require it)
Line 77: Line 77:
                     'mobile_course_view' => [],
                     'mobile_course_view' => [],
                     'mobile_issues_view' => [],
                     'mobile_issues_view' => [],
                 ]. // Function that needs to be downloaded for offline.
                 ], // Function that needs to be downloaded for offline.
             ],
             ],
         ],
         ],
Line 115: Line 115:


;Lang:
;Lang:
: The language pack string ids used in the plugin by all the handlers. Please note that you should avoid adding all the plugin string ids (including those unused) because the Web Service that returns the plugin information will include the translation of each string id for every language installed in the platform.
: <nowiki>The language pack string ids used in the plugin by all the handlers. Normally these will be strings from your own plugin, however, you can list any strings you need here (e.g. ['cancel', 'moodle']). If you do this, be warned that in the app you will then need to refer to that string as {{ 'plugin.myplugin.cancel' | translate }} (not {{ 'plugin.moodle.cancel' | translate }})</nowiki>
: Please only include the strings you actually need. The Web Service that returns the plugin information will include the translation of each string id for every language installed in the platform, and this will then be cached, so listing too many strings is very wasteful.


There are additional attributes supported by the mobile.php list, see “Mobile.php supported options” section below.
There are additional attributes supported by the mobile.php list, see “Mobile.php supported options” section below.
Line 132: Line 133:
<?php
<?php
namespace mod_certificate\output;
namespace mod_certificate\output;
defined('MOODLE_INTERNAL') || die();


use context_module;
use context_module;
Line 162: Line 161:
         require_login($args->courseid , false , $cm, true, true);
         require_login($args->courseid , false , $cm, true, true);


         $context = context_module::instance($cm->id);
         $context = \context_module::instance($cm->id);


         require_capability ('mod/certificate:view', $context);
         require_capability ('mod/certificate:view', $context);
Line 172: Line 171:
         // Get certificates from external (taking care of exceptions).
         // Get certificates from external (taking care of exceptions).
         try {
         try {
             $issued = mod_certificate_external::issue_certificate($cm->instance);
             $issued = \mod_certificate_external::issue_certificate($cm->instance);
             $certificates = mod_certificate_external::get_issued_certificates($cm->instance);
             $certificates = \mod_certificate_external::get_issued_certificates($cm->instance);
             $issues = array_values($certificates['issues']); // Make it mustache compatible.
             $issues = array_values($certificates['issues']); // Make it mustache compatible.
         } catch (Exception $e) {
         } catch (Exception $e) {
Line 411: Line 410:
The first and most important thing to know is that you don’t need a local mobile environment, you can just use the Chrome or Chromium browser to add mobile support to your plugins!
The first and most important thing to know is that you don’t need a local mobile environment, you can just use the Chrome or Chromium browser to add mobile support to your plugins!


Open this URL (with Chrome or Chromium browser): https://mobileapp.moodledemo.net/ and you will see a web version of the mobile app completely functional (except for some native features). This URL is updated with the latest integration version of the app.
Open this URL (with Chrome or Chromium browser): https://mobileapp.moodledemo.net/ and you will see a web version of the mobile app completely functional (except for some native features). This URL is updated with the latest integration version of the app.  
 
Alternatively, you can use the [https://download.moodle.org/desktop/ Moodle Desktop App] that is based in the master (latest stable) version of the app, it is based on Chromium so you can enable the "Developer Tools" and inspect the HTML, inject javascript, debug, etc...
 
To enable "Developer Tools" in Moodle Desktop (and the Chrome or Chromium browser);
* In MacOS: Cmd + Option + I
* In Windows or Linux: Ctrl + Shift + I


Please test that your site works correctly in the web version before starting any development.
Please test that your site works correctly in the web version before starting any development.
Line 427: Line 432:
===Development workflow===
===Development workflow===


First of all, we recommend creating a simple ''mobile.php'' for displaying a new main menu option (even if your plugin won’t be in the main menu, just to verify that you are able to extend the app plugins). Then open the webapp (https://mobileapp.moodledemo.net/) or refresh the browser if it was already open. Check that you can correctly  see the new menu option you included.
First of all, we recommend creating a simple ''mobile.php'' for displaying a new main menu option (even if your plugin won’t be in the main menu, just to verify that you are able to extend the app plugins). Then open the webapp (https://mobileapp.moodledemo.net/) or refresh the browser if it was already open. Alternatively, you can use the Moodle Desktop app, it is based on Chromium so you can enable the "Developer Tools" and inspect the HTML, inject javascript, debug, etc...
 
Check that you can correctly  see the new menu option you included.


Then, develop the main function of the app returning a “Hello world” or basic code (without using templates) to see that everything works together. After adding the classes/output/mobile.php file it is very important to “Purge all caches” to avoid problems with the auto-loading cache.
Then, develop the main function of the app returning a “Hello world” or basic code (without using templates) to see that everything works together. After adding the classes/output/mobile.php file it is very important to “Purge all caches” to avoid problems with the auto-loading cache.
Line 442: Line 449:


For plugins using the Javascript API you may develop making use of the console.log function to add trace messages in your code that will be displayed in the browser console.
For plugins using the Javascript API you may develop making use of the console.log function to add trace messages in your code that will be displayed in the browser console.
Within the app, make sure to turn on the option: '''App settings''' / '''General''' / '''Display debug messages'''. This means popup errors from the app will show more information.


==Mobile.php supported options==
==Mobile.php supported options==
Line 455: Line 464:
* '''restricttoenrolledcourses''' (optional): Only used if the delegate has a isEnabledForCourse function. If true or not defined, the handler will only be shown for courses the user is enrolled in. For more info about displaying the plugin only for certain courses, please see [[Mobile_support_for_plugins#Display_the_plugin_only_if_certain_conditions_are_met|Display the plugin only if certain conditions are met]].
* '''restricttoenrolledcourses''' (optional): Only used if the delegate has a isEnabledForCourse function. If true or not defined, the handler will only be shown for courses the user is enrolled in. For more info about displaying the plugin only for certain courses, please see [[Mobile_support_for_plugins#Display_the_plugin_only_if_certain_conditions_are_met|Display the plugin only if certain conditions are met]].
* '''styles''' (optional): An array with two properties: ''url'' and ''version''. The URL should point to a CSS file, either using an absolute URL or a relative URL. This file will be downloaded and applied by the app. It's recommended to include styles that will only affect your plugin templates. The version number is used to determine if the file needs to be downloaded again, you should change the version number everytime you change the CSS file.
* '''styles''' (optional): An array with two properties: ''url'' and ''version''. The URL should point to a CSS file, either using an absolute URL or a relative URL. This file will be downloaded and applied by the app. It's recommended to include styles that will only affect your plugin templates. The version number is used to determine if the file needs to be downloaded again, you should change the version number everytime you change the CSS file.
* '''moodlecomponent''' (optional): If your plugin supports a component in the app different than the one defined by your plugin, you can use this property to specify it. For example, you can create a local plugin to support a certain course format, activity, etc. The component of your plugin in Moodle would be ''local_whatever'', but in "moodlecomponent" you can specify that this handler will implement ''format_whatever'' or ''mod_whatever''. This property was introduced in the version 3.6.1 of the app.


===Options only for CoreCourseOptionsDelegate===
===Options only for CoreCourseOptionsDelegate===


* '''displaydata''' (mandatory): title, class.
* '''displaydata''' (mandatory): title, class.
* '''priority''' (optional): Priority of the handler. Higher priority is displayed first.  
* '''priority''' (optional): Priority of the handler. Higher priority is displayed first.
* '''ismenuhandler''': (optional) Supported from the 3.7.1 version of the app. Set it to true if you want your plugin to be displayed in the contextual menu of the course instead of in the top tabs. The contextual menu is displayed when you click in the 3-dots button at the top right of the course.


===Options only for CoreMainMenuDelegate===
===Options only for CoreMainMenuDelegate===


* '''displaydata''' (mandatory): title, icon, class.
* '''displaydata''' (mandatory):
** title:  a language string identifier that was included in the 'lang' section
** icon: the name of an ionic icon. Valid strings are found here: https://infinitered.github.io/ionicons-version-3-search/ and search for ion-md. Do not include the 'md-' in the string. (eg 'md-information-circle' should be 'information-circle')
** class
* '''priority''' (optional): Priority of the handler. Higher priority is displayed first. Main Menu plugins are always displayed in the "More" tab, they cannot be displayed as tabs in the bottom bar.
* '''priority''' (optional): Priority of the handler. Higher priority is displayed first. Main Menu plugins are always displayed in the "More" tab, they cannot be displayed as tabs in the bottom bar.


Line 469: Line 483:


* '''displaydata''' (mandatory): icon, class.
* '''displaydata''' (mandatory): icon, class.
* '''method''' (optional): The function to call to retrieve the main page content. In this delegate the method is optional. If the method is not set, the module won't be clickable.
* '''offlinefunctions''': (optional) List of functions to call when prefetching the module. It can be a get_content method or a WS. You can filter the params received by the WS. By default, WS will receive these params: courseid, cmid, userid. Other valid values that will be added if they are present in the list of params: courseids (it will receive a list with the courses the user is enrolled in), component + 'id' (e.g. certificateid).
* '''offlinefunctions''': (optional) List of functions to call when prefetching the module. It can be a get_content method or a WS. You can filter the params received by the WS. By default, WS will receive these params: courseid, cmid, userid. Other valid values that will be added if they are present in the list of params: courseids (it will receive a list with the courses the user is enrolled in), component + 'id' (e.g. certificateid).
* '''downloadbutton''': (optional) Whether to display download button in the module. If not defined, the button will be shown if there is any offlinefunction.
* '''downloadbutton''': (optional) Whether to display download button in the module. If not defined, the button will be shown if there is any offlinefunction.
Line 478: Line 493:
* '''displayprefetch''': (optional) Supported from the 3.6 version of the app. Whether the module should display the download option in the top-right menu. This can be done in JavaScript too: this.displayPrefetch = false;
* '''displayprefetch''': (optional) Supported from the 3.6 version of the app. Whether the module should display the download option in the top-right menu. This can be done in JavaScript too: this.displayPrefetch = false;
* '''displaysize''': (optional) Supported from the 3.6 version of the app. Whether the module should display the downloaded size in the top-right menu. This can be done in JavaScript too: this.displaySize = false;
* '''displaysize''': (optional) Supported from the 3.6 version of the app. Whether the module should display the downloaded size in the top-right menu. This can be done in JavaScript too: this.displaySize = false;
* '''coursepagemethod''': (optional) Supported from the 3.8 version of the app. If set, this method will be called when the course is rendered and the HTML returned will be displayed in the course page for the module. Please notice the HTML returned should not contain directives or components, only default HTML.


===Options only for CoreCourseFormatDelegate===
===Options only for CoreCourseFormatDelegate===
Line 499: Line 515:


* '''displaydata''' (mandatory): title, icon.
* '''displaydata''' (mandatory): title, icon.
* '''priority''' (optional): Priority of the handler. Higher priority is displayed first.  
* '''priority''' (optional): Priority of the handler. Higher priority is displayed first.
 
===Options only for CoreBlockDelegate===
 
* '''displaydata''' (optional): title, class, type. If ''title'' is not supplied, it will default to "plugins.block_blockname.pluginname", where ''blockname'' is the name of the block. If ''class'' is not supplied, it will default to "block_blockname", where ''blockname'' is the name of the block. Possible values of ''type'':
** "title": Your block will only display the block title, and when it's clicked it will open a new page to display the block contents (the template returned by the block's method).
** "prerendered": Your block will display the content and footer returned by the WebService to get the blocks (e.g. core_block_get_course_blocks), so your block's method will never be called.
** any other value: Your block will immediately call the method specified in mobile.php and it will use the template to render the block.
* '''fallback''': (optional) Supported from the 3.9.0 version of the app. This option allows you to specify a block to use in the app instead of your block. E.g. you can make the app display the "My overview" block instead of your block in the app by setting: 'fallback' => 'myoverview'. The fallback will only be used if you don't specify a ''method'' and the ''type'' is different than ''title'' or ''prerendered''..


==Delegates==
==Delegates==
Line 525: Line 549:
====CoreCourseFormatDelegate====
====CoreCourseFormatDelegate====


You must use this delegate for supporting course formats.
You must use this delegate for supporting course formats.  When you open a course from the course list in the mobile app, it will check if there is a CoreCourseFormatDelegate handler for the format that site uses.  If so, it will display the course using that handler.  Otherwise, it will use the default app course format.  More information is available on [[Creating mobile course formats]].


====CoreSettingsDelegate====
====CoreSettingsDelegate====
Line 534: Line 558:


You must use this delegate to support a message output plugin.
You must use this delegate to support a message output plugin.
====CoreBlockDelegate====
You must use this delegate to support a block. As of Moodle App 3.7.0, blocks are only displayed in Site Home and Dashboard, but they'll be supported in other places of the app soon (e.g. in the course page).


===Templates downloaded on login and rendered using JS data===
===Templates downloaded on login and rendered using JS data===
Line 570: Line 598:
* CoreFileUploaderDelegate
* CoreFileUploaderDelegate
* CorePluginFileDelegate
* CorePluginFileDelegate
* CoreFilterDelegate


==Available components and directives==
==Available components and directives==
Line 587: Line 616:
===Custom core components and directives===
===Custom core components and directives===


These are some useful custom components and directives (only available in the mobile app). Please notice that this isn’t the full list of components and directives of the app, it’s just an extract of the most common ones.
These are some useful custom components and directives (only available in the mobile app). Please note that this isn’t the full list of components and directives of the app, it’s just an extract of the most common ones.
 
For a full list of components, go to https://github.com/moodlehq/moodlemobile2/tree/master/src/components
 
For a full list of directives, go to https://github.com/moodlehq/moodlemobile2/tree/master/src/directives


====core-format-text====
====core-format-text====
Line 622: Line 655:
Data that can be passed to the directive:
Data that can be passed to the directive:


* '''capture''' (boolean): Optional. Whether the link needs to be captured by the app (check if the link can be handled by the app instead of opening it in a browser).
* '''capture''' (boolean): Optional, default false. Whether the link needs to be captured by the app (check if the link can be handled by the app instead of opening it in a browser).
* '''inApp''' (boolean): Optional. True to open in embedded browser, false to open in system browser.
* '''inApp''' (boolean): Optional, default false. True to open in embedded browser, false to open in system browser.
* '''autoLogin''' (string): Optional. If the link should be open with auto-login. Accepts the following values:
* '''autoLogin''' (string): Optional, default "check". If the link should be open with auto-login. Accepts the following values:
** "yes" -> Always auto-login.
** "yes" -> Always auto-login.
** "no" -> Never auto-login.
** "no" -> Never auto-login.
Line 773: Line 806:
* '''title''' (string): The title to display with the new content. Only if samePage=false.
* '''title''' (string): The title to display with the new content. Only if samePage=false.
* '''samePage''' (boolean): Whether to display the content in same page or open a new one. Defaults to new page.
* '''samePage''' (boolean): Whether to display the content in same page or open a new one. Defaults to new page.
* '''useOtherData''' (any): Whether to include ''otherdata'' (from the ''get_content'' WS call) in the args for the new ''get_content'' call. The format is the same as in ''useOtherDataForWS''. If not supplied, no other data will be added. If supplied but empty (null, false or empty string) all the ''otherdata'' will be added. If it’s an array, it will only copy the properties whose names are in the array.
* '''useOtherData''' (any): Whether to include ''otherdata'' (from the ''get_content'' WS call) in the args for the new ''get_content'' call. If not supplied, no other data will be added. If supplied but empty ('''null, false or empty string''') all the ''otherdata'' will be added. If it’s an array, it will only copy the properties whose names are in the array. Please notice that [useOtherData]="" is the same as not supplying it, so nothing will be copied. Also, objects or arrays in otherdata will be converted to a JSON encoded string.
* '''form''' (string): ID or name to identify a form in the template. The form will be obtained from ''document.forms''. If supplied and form is found, the form data will be retrieved and sent to the new ''get_content'' WS call. If your form contains an ion-radio, ion-checkbox or ion-select, please see [[Mobile_support_for_plugins#Values_of_ion-radio.2C_ion-checkbox_or_ion-select_aren.27t_sent_to_my_WS|Values of ion-radio, ion-checkbox or ion-select aren't sent to my WS]].
* '''form''' (string): ID or name to identify a form in the template. The form will be obtained from ''document.forms''. If supplied and form is found, the form data will be retrieved and sent to the new ''get_content'' WS call. If your form contains an ion-radio, ion-checkbox or ion-select, please see [[Mobile_support_for_plugins#Values_of_ion-radio.2C_ion-checkbox_or_ion-select_aren.27t_sent_to_my_WS|Values of ion-radio, ion-checkbox or ion-select aren't sent to my WS]].


Line 803: Line 836:
* '''params''' (object): The params for the WS call.
* '''params''' (object): The params for the WS call.
* '''preSets''' (object): Extra options for the WS call: whether to use cache or not, etc.
* '''preSets''' (object): Extra options for the WS call: whether to use cache or not, etc.
* '''useOtherDataForWS''' (any): Whether to include ''otherdata'' (from the ''get_content'' WS call) in the params for the WS call. If not supplied, no other data will be added. If supplied but empty (null, false or empty string) all the ''otherdata'' will be added. If it’s an array, it will only copy the properties whose names are in the array.
* '''useOtherDataForWS''' (any): Whether to include ''otherdata'' (from the ''get_content'' WS call) in the params for the WS call. If not supplied, no other data will be added. If supplied but empty ('''null, false or empty string''') all the ''otherdata'' will be added. If it’s an array, it will only copy the properties whose names are in the array. Please notice that [useOtherDataForWS]="" is the same as not supplying it, so nothing will be copied. Also, objects or arrays in otherdata will be converted to a JSON encoded string.
* '''form''' (string): ID or name to identify a form in the template. The form will be obtained from ''document.forms''. If supplied and form is found, the form data will be retrieved and sent to the WS. If your form contains an ion-radio, ion-checkbox or ion-select, please see [[Mobile_support_for_plugins#Values_of_ion-radio.2C_ion-checkbox_or_ion-select_aren.27t_sent_to_my_WS|Values of ion-radio, ion-checkbox or ion-select aren't sent to my WS]].
* '''form''' (string): ID or name to identify a form in the template. The form will be obtained from ''document.forms''. If supplied and form is found, the form data will be retrieved and sent to the WS. If your form contains an ion-radio, ion-checkbox or ion-select, please see [[Mobile_support_for_plugins#Values_of_ion-radio.2C_ion-checkbox_or_ion-select_aren.27t_sent_to_my_WS|Values of ion-radio, ion-checkbox or ion-select aren't sent to my WS]].
* '''confirmMessage''' (string): Message to confirm the action when the user clicks the element. If not supplied, no confirmation. If supplied but empty, default message ("Are you sure?").
* '''confirmMessage''' (string): Message to confirm the action when the user clicks the element. If not supplied, no confirmation. If supplied but empty, default message ("Are you sure?").
Line 854: Line 887:
* '''params''' (object): The params for the WS call.
* '''params''' (object): The params for the WS call.
* '''preSets''' (object): Extra options for the WS call: whether to use cache or not, etc.
* '''preSets''' (object): Extra options for the WS call: whether to use cache or not, etc.
* '''useOtherDataForWS''' (any): Whether to include ''otherdata'' (from the ''get_content'' WS call) in the params for the WS call. If not supplied, no other data will be added. If supplied but empty (null, false or empty string) all the ''otherdata'' will be added. If it’s an array, it will only copy the properties whose names are in the array.
* '''useOtherDataForWS''' (any): Whether to include ''otherdata'' (from the ''get_content'' WS call) in the params for the WS call. If not supplied, no other data will be added. If supplied but empty ('''null, false or empty string''') all the ''otherdata'' will be added. If it’s an array, it will only copy the properties whose names are in the array. Please notice that [useOtherDataForWS]="" is the same as not supplying it, so nothing will be copied. Also, objects or arrays in otherdata will be converted to a JSON encoded string.
* '''form''' (string): ID or name to identify a form in the template. The form will be obtained from ''document.forms''. If supplied and form is found, the form data will be retrieved and sent to the WS. If your form contains an ion-radio, ion-checkbox or ion-select, please see [[Mobile_support_for_plugins#Values_of_ion-radio.2C_ion-checkbox_or_ion-select_aren.27t_sent_to_my_WS|Values of ion-radio, ion-checkbox or ion-select aren't sent to my WS]].
* '''form''' (string): ID or name to identify a form in the template. The form will be obtained from ''document.forms''. If supplied and form is found, the form data will be retrieved and sent to the WS. If your form contains an ion-radio, ion-checkbox or ion-select, please see [[Mobile_support_for_plugins#Values_of_ion-radio.2C_ion-checkbox_or_ion-select_aren.27t_sent_to_my_WS|Values of ion-radio, ion-checkbox or ion-select aren't sent to my WS]].
* '''confirmMessage''' (string): Message to confirm the action when the user clicks the element. If not supplied, no confirmation. If supplied but empty, default message ("Are you sure?").
* '''confirmMessage''' (string): Message to confirm the action when the user clicks the element. If not supplied, no confirmation. If supplied but empty, default message ("Are you sure?").
Line 910: Line 943:
* '''params''' (object): The params for the WS call.
* '''params''' (object): The params for the WS call.
* '''preSets''' (object): Extra options for the WS call: whether to use cache or not, etc.
* '''preSets''' (object): Extra options for the WS call: whether to use cache or not, etc.
* '''useOtherDataForWS''' (any): Whether to include ''otherdata'' (from the ''get_content'' WS call) in the params for the WS call. If not supplied, no other data will be added. If supplied but empty (null, false or empty string) all the ''otherdata'' will be added. If it’s an array, it will only copy the properties whose names are in the array.
* '''useOtherDataForWS''' (any): Whether to include ''otherdata'' (from the ''get_content'' WS call) in the params for the WS call. If not supplied, no other data will be added. If supplied but empty ('''null, false or empty string''') all the ''otherdata'' will be added. If it’s an array, it will only copy the properties whose names are in the array. Please notice that [useOtherDataForWS]="" is the same as not supplying it, so nothing will be copied. Also, objects or arrays in otherdata will be converted to a JSON encoded string.
* '''form''' (string): ID or name to identify a form in the template. The form will be obtained from ''document.forms''. If supplied and form is found, the form data will be retrieved and sent to the WS. If your form contains an ion-radio, ion-checkbox or ion-select, please see [[Mobile_support_for_plugins#Values_of_ion-radio.2C_ion-checkbox_or_ion-select_aren.27t_sent_to_my_WS|Values of ion-radio, ion-checkbox or ion-select aren't sent to my WS]].
* '''form''' (string): ID or name to identify a form in the template. The form will be obtained from ''document.forms''. If supplied and form is found, the form data will be retrieved and sent to the WS. If your form contains an ion-radio, ion-checkbox or ion-select, please see [[Mobile_support_for_plugins#Values_of_ion-radio.2C_ion-checkbox_or_ion-select_aren.27t_sent_to_my_WS|Values of ion-radio, ion-checkbox or ion-select aren't sent to my WS]].
* '''onSuccess''' (Function): A function to call when the WS call is successful (HTTP call successful and no exception returned). This field was added in v3.5.2.
* '''onSuccess''' (Function): A function to call when the WS call is successful (HTTP call successful and no exception returned). This field was added in v3.5.2.
Line 932: Line 965:
You might want to display your plugin in the mobile app only if certain dynamic conditions are met, so the plugin would be displayed only for some users. This can be achieved using the "init" method (for more info, please see the [[Mobile_support_for_plugins#Initialization|Initialization]] section ahead).
You might want to display your plugin in the mobile app only if certain dynamic conditions are met, so the plugin would be displayed only for some users. This can be achieved using the "init" method (for more info, please see the [[Mobile_support_for_plugins#Initialization|Initialization]] section ahead).


All the init methods are called as soon as your plugin is retrieved. If you don't want your plugin to be displayed for the current user, then you should return an exception in this init method. It's recommended to include a message explaining why the plugin isn't available for the current user, this exception will be logged in the Javascript console.
All the init methods are called as soon as your plugin is retrieved. If you don't want your plugin to be displayed for the current user, then you should return this in the init method (only for Moodle 3.8 and onwards).
 
<code php>
return [
    'disabled' => true
];</code>
 
If the Moodle version is older than 3.8, then the init method should return this:
 
<code php>
return [
    'javascript' => 'this.HANDLER_DISABLED'
];</code>


On the other hand, you might want to display a plugin only for certain courses (''CoreCourseOptionsDelegate'') or only if the user is viewing certain users' profiles (''CoreUserDelegate''). This can be achieved with the init method too.
On the other hand, you might want to display a plugin only for certain courses (''CoreCourseOptionsDelegate'') or only if the user is viewing certain users' profiles (''CoreUserDelegate''). This can be achieved with the init method too.
Line 1,103: Line 1,148:
</code>
</code>


===Initialization===
===Use the rich text editor===


All handlers can specify a “''init''” method in the mobile.php file. This method is meant to return some JavaScript code that needs to be executed as soon as the plugin is retrieved.
The rich text editor included in the app requires a FormControl to work. You can use the library FormBuilder to create this control (or to create a whole FormGroup if you prefer).


When the app retrieves all the handlers, the first thing it will do is call the ''tool_mobile_get_content'' WebService with the init method. This WS call will only receive the default args.
With the following Javascript you'll be able to create a FormControl:
 
<code javascript>
this.control = this.FormBuilder.control(this.CONTENT_OTHERDATA.rte);
</code>
 
In the example above we're using a value returned in OTHERDATA as the initial value of the rich text editor, but you can use whatever you want.
 
Then you need to pass this control to the rich text editor in your template:
 
<code>
<ion-item>
    <core-rich-text-editor item-content [control]="control" placeholder="Enter your text here" name="rte_answer"></core-rich-text-editor>
</ion-item>
</code>
 
Finally, there are several ways to send the value in the rich text editor to a WebService to save it. This is one of the simplest options:
 
<code>
<button ion-button block type="submit" core-site-plugins-call-ws name="my_webservice" [params]="{rte: control.value}" ....
</code>
 
As you can see, we're passing the value of the rich text editor as a parameter to our WebService.
 
===Initialization===
 
All handlers can specify a “''init''” method in the mobile.php file. This method is meant to return some JavaScript code that needs to be executed as soon as the plugin is retrieved.
 
When the app retrieves all the handlers, the first thing it will do is call the ''tool_mobile_get_content'' WebService with the init method. This WS call will only receive the default args.


The app will immediately execute the JavaScript code returned by this WS call. This JavaScript can be used to manually register your handlers in the delegates you want, without having to rely on the default handlers built based on the mobile.php data.
The app will immediately execute the JavaScript code returned by this WS call. This JavaScript can be used to manually register your handlers in the delegates you want, without having to rely on the default handlers built based on the mobile.php data.
Line 1,126: Line 1,199:
     MyAddonClass: new MyAddonClass()
     MyAddonClass: new MyAddonClass()
};
};
result:
result;
</code>
</code>
Then, for the rest of Javascript code of your handler (e.g. for the “main” method) you can use this variable like this:
Then, for the rest of Javascript code of your handler (e.g. for the “main” method) you can use this variable like this:
Line 1,234: Line 1,307:
     this.name = "AddonModCertificateModulePrefetchHandler";
     this.name = "AddonModCertificateModulePrefetchHandler";
     this.modName = "certificate";
     this.modName = "certificate";
     this.component = "mmaModCertificate";
     this.component = "mod_certificate"; // This must match the plugin identifier from db/mobile.php, otherwise the download link in the context menu will not update correctly.
     this.updatesNames = /^configuration$|^.*files$/;
     this.updatesNames = /^configuration$|^.*files$/;
}
}
Line 1,376: Line 1,449:
===Using the JavaScript API===
===Using the JavaScript API===


The Javascript API is partly supported right now, only the ''CoreUserProfileFieldDelegate'' supports it now. This API allows you to override any of the functions of the default handler.  
The Javascript API is partly supported right now, only the delegates specified in the section [[Mobile_support_for_plugins#Templates_downloaded_on_login_and_rendered_using_JS_data_2|Templates downloaded on login and rendered using JS data]] supports it now. This API allows you to override any of the functions of the default handler.  


The “method” specified in a handler registered in the ''CoreUserProfileFieldDelegate'' will be called immediately after the init method, and the Javascript returned by this method will be run. If this Javascript code returns an object with certain functions, these function will override the ones in the default handler.
The “method” specified in a handler registered in the ''CoreUserProfileFieldDelegate'' will be called immediately after the init method, and the Javascript returned by this method will be run. If this Javascript code returns an object with certain functions, these function will override the ones in the default handler.
Line 1,432: Line 1,505:
</code>
</code>


==Troubleshooting==
===Translate dynamic strings===


=== Invalid response received ===
If you wish to have an element that displays a localised string based on value from your template you can doing something like:


You might receive this error when using the "core-site-plugins-call-ws" directive or similar. By default, the app expects all WebService calls to return an object, if your WebService returns another type (string, bool, ...) then you need to specify it using the preSets attribute of the directive. For example, if your WS returns a boolean value, then you should specify it like this:
<code>
<ion-card>
    <ion-card-content translate>
        plugin.mod_myactivity.<% status %>
    </ion-card-content>
</ion-card>
</code>


[preSets]="{typeExpected: 'boolean'}"
This could save you from having to write something like when only one value should be displayed:


In a similar way, if your WebService returns null you need to tell the app not to expect any result using the preSets:
<code>
<ion-card>
    <ion-card-content>
        <%#isedting%>{{ 'plugin.mod_myactivity.editing' | translate }}<%/isediting%>
        <%#isopen%>{{ 'plugin.mod_myactivity.open' | translate }}<%/isopen%>
        <%#isclosed%>{{ 'plugin.mod_myactivity.closed' | translate }}<%/isclosed%>
    </ion-card-content>
</ion-card>
</code>
 
===Using strings with dates===
 
If you have a string that you wish to pass a formatted date for example in the Moodle language file you have:
 
<code php>
$string['strwithdate'] = 'This string includes a date of {$a->date} in the middle of it.';
</code>
 
You can localise the string correctly in your template using something like the following:
 
<code>
{{ 'plugin.mod_myactivity.strwithdate' | translate: {$a: { date: <% timestamp %> * 1000 | coreFormatDate: "dffulldate" } } }}
</code>
 
A Unix timestamp must be multiplied by 1000 as the Mobile App expects millisecond timestamps, where as Unix timestamps are in seconds.
 
===Support push notification clicks===
 
If your plugin sends push notifications to the app, you might want to open a certain page in the app when the notification is clicked. There are several ways to achieve this.
 
The easiest way is to include a ''contexturl'' in your notification. When the notification is clicked, the app will try to open the ''contexturl''.
 
Please notice that the ''contexturl'' will also be displayed in web. If you want to use a specific URL for the app, different than the one displayed in web, you can do so by returning a ''customdata'' array that contains an ''appurl'' property:
 
<code php>
$notification->customdata = [
    'appurl' => $myurl->out(),
];
</code>
 
In both cases you will have to create a link handler to treat the URL. For more info on how to create the link handler, please see [[Mobile_support_for_plugins#Advanced_link_handler|how to create an advanced link handler]].
 
If you want to do something that only happens when the notification is clicked, not when the link is clicked, you'll have to implement a push click handler yourself. The way to create it is similar to [[Mobile_support_for_plugins#Advanced_link_handler|creating an advanced link handler]], but you'll have to use ''CorePushNotificationsDelegate'' and your handler will have to implement the properties and functions defined in the interface [https://github.com/moodlehq/moodlemobile2/blob/master/src/core/pushnotifications/providers/delegate.ts#L24 CorePushNotificationsClickHandler].
 
===Implement a module similar to mod_label===
 
In Moodle 3.8 or higher, if your plugin doesn't support ''FEATURE_NO_VIEW_LINK'' and you don't specify a ''coursepagemethod'' then the module will only display the module description in the course page and it won't be clickable in the app, just like mod_label. You can decide if you want the module icon to be displayed or not (if you don't want it to be displayed, then don't define it in ''displaydata'').
 
However, if your plugin needs to work in previous versions of Moodle or you want to display something different than the description then you need a different approach.
 
If your plugin wants to render something in the course page instead of just the module name and description you should specify the property ''coursepagemethod'' in the mobile.php. The template returned by this method will be rendered in the course page. Please notice the HTML returned should not contain directives or components, only default HTML.
 
If you don't want your module to be clickable then you just need to remove the ''method'' from mobile.php. With these 2 changes you can have a module that behaves like mod_label in the app.
 
===Use Ionic navigation lifecycle functions===
 
Ionic let pages define some functions that will be called when certain navigation lifecycle events happen. For more info about these functions, see [https://ionicframework.com/blog/navigating-lifecycle-events/ this page].
 
You can define these functions in your plugin javascript:
 
<code javascript>
this.ionViewCanLeave = function() {
    ...
};</code>
 
So for example you can make your plugin ask for confirmation if the user tries to leave the page when he has some unsaved data.
 
==Troubleshooting==
 
=== Invalid response received ===
 
You might receive this error when using the "core-site-plugins-call-ws" directive or similar. By default, the app expects all WebService calls to return an object, if your WebService returns another type (string, bool, ...) then you need to specify it using the preSets attribute of the directive. For example, if your WS returns a boolean value, then you should specify it like this:
 
[preSets]="{typeExpected: 'boolean'}"
 
In a similar way, if your WebService returns null you need to tell the app not to expect any result using the preSets:


[preSets]="{responseExpected: false}"
[preSets]="{responseExpected: false}"
Line 1,599: Line 1,753:
* Certificate: [https://moodle.org/plugins/mod_certificate Moodle plugins directory entry] and [https://github.com/markn86/moodle-mod_certificate in github].
* Certificate: [https://moodle.org/plugins/mod_certificate Moodle plugins directory entry] and [https://github.com/markn86/moodle-mod_certificate in github].
* Attendance [https://moodle.org/plugins/mod_attendance Moodle plugins directory entry] and [https://github.com/danmarsden/moodle-mod_attendance in github].
* Attendance [https://moodle.org/plugins/mod_attendance Moodle plugins directory entry] and [https://github.com/danmarsden/moodle-mod_attendance in github].
* ForumNG (unfinished support) [https://moodle.org/plugins/mod_forumng Moodle plugins directory entry] and [https://github.com/moodleou/moodle-mod_forumng in github].
* News block [https://github.com/moodleou/moodle-block_news in github].
* H5P activity module  [https://moodle.org/plugins/mod_hvp Moodle plugins directory entry] and [https://github.com/h5p/h5p-moodle-plugin in github].


See the complete list in the plugins database [https://moodle.org/plugins/browse.php?list=award&id=6 here] (it may contain some outdated plugins)
See the complete list in the plugins database [https://moodle.org/plugins/browse.php?list=award&id=6 here] (it may contain some outdated plugins)
=== Mobile app support award ===
If you want your plugin to be awarded in the plugins directory and marked as supporting the mobile app, please feel encouraged to contact us via email [mailto:mobile@moodle.com mobile@moodle.com].
Don't forget to include a link to your plugin page and the location of its code repository.
See [https://moodle.org/plugins/?q=award:mobile-app the list of awarded plugins] in the plugins directory
[[Category:Mobile]]
[[Category:Mobile]]

Revision as of 16:58, 9 November 2020

This template is unused and can be deleted.

Before 3.5

Since Moodle 3.1 Moodle plugins could be supported in the Mobile app, but only by writing an Angular JS/Ionic module, compiling it to a zip, and including that in your plugin. See Remote add-ons for details.

In Moodle 3.5 the app switched to a new way to support plugins that was much easier for developers.

  • This new way will allow developers to support plugins using PHP code, templates and Ionic markup (html components).
  • The use of JavaScript is optional (but some type of advanced plugins may require it)
  • Developers won’t need to set up a Mobile development environment, they will be able to test using the latest version of the official app (although setting up a local Mobile environment is recommended for complex plugins).

This means that remote add-ons won’t be necessary anymore, and developers won’t have to learn Ionic 3 / Angular and set up a new mobile development environment to migrate them. Plugins using the old Remote add-ons mechanism will have to be migrated to the new simpler way (following this documentation)

This new way is natively supported in Moodle 3.5. For previous versions you will need to install the Moodle Mobile Additional Features plugin.

How it works

The overall idea is to allow Moodle plugins to extend different areas in the app with just PHP server side code and Ionic 3 markup (custom html elements that are called components) using a set of custom Ionic directives and components.

Developers will have to:

  1. Create a db/mobile.php file in their plugins. In this file developers will be able to indicate which areas of the app they want to extend, for example, adding a new option in the main menu, implementing an activity module not supported, including a new option in the course menu, including a new option in the user profile, etc. All the areas supported are described further in this document.
  2. Create new functions in a reserved namespace that will return the content of the new options. The content should be returned rendered (html). The template should use Ionic components so that it looks native (custom html elements) but it can be generated using mustache templates.

Let’s clarify some points:

  • You don’t need to create new Web Service functions (although you will be able to use them for advanced features). You just need plain php functions that will be placed in a reserved namespace.
  • Those functions will be exported via the Web Service function tool_mobile_get_content
  • As arguments of your functions you will always receive the userid, some relevant details of the app (app version, current language in the app, etc…) and some specific data depending on the type of plugin (courseid, cmid, …).
  • We provide a list of custom Ionic components and directives (html tags) that will provide dynamic behaviour, like indicating that you are linking a file that can be downloaded, or to allow a transition to new pages into the app calling a specific function in the server, submit form data to the server etc..

Types of plugins

We could classify all the plugins in 3 different types:

Templates generated and downloaded when the user opens the plugins

Templates downloaded when requested.png

With this type of plugin, the template of your plugin will be generated and downloaded when the user opens your plugin in the app. This means that your function will receive some context params. For example, if you're developing a course module plugin you will receive the courseid and the cmid (course module ID). You can see the list of delegates that support this type of plugin in the Delegates section.

Templates downloaded on login and rendered using JS data

Templates downloaded on login.png

With this type of plugin, the template for your plugin will be downloaded when the user logins in the app and will be stored in the device. This means that your function will not receive any context params, and you need to return a generic template that will be built with JS data like the ones in the Mobile app. When the user opens a page that includes your plugin, your template will receive the required JS data and your template will be rendered. You can see the list of delegates that support this type of plugin in the Delegates section.

Pure Javascript plugins

You can always implement your whole plugin yourself using Javascript instead of using our API. In fact, this is required if you want to implement some features like capturing links in the Mobile app. You can see the list of delegates that only support this type of plugin in the Delegates section.

Step by step example

In this example, we are going to update an existing plugin (Certificate activity module) that currently uses a Remote add-on. This is a simple activity module that displays the certificate issued for the current user along with the list of the dates of previously issued certificates. It also stores in the course log that the user viewed a certificate. This module also works offline: when the user downloads the course or activity, the data is pre-fetched and can be viewed offline.

The example code can be downloaded from here (https://github.com/markn86/moodle-mod_certificate/commit/003fbac0d80fd96baf428255500980bf95a7a0d6)

TIP: Make sure to (purge all cache) after making an edit to one of the following files for your changes to be taken into account.

Step 1. Update the db/mobile.php file

In this case, we are updating an existing file but for new plugins, you should create this new file.

$addons = [

   'mod_certificate' => [ // Plugin identifier
       'handlers' => [ // Different places where the plugin will display content.
           'coursecertificate' => [ // Handler unique name (alphanumeric).
               'displaydata' => [
                   'icon' => $CFG->wwwroot . '/mod/certificate/pix/icon.gif',
                   'class' => ,
               ],
      
               'delegate' => 'CoreCourseModuleDelegate', // Delegate (where to display the link to the plugin)
               'method' => 'mobile_course_view', // Main function in \mod_certificate\output\mobile
               'offlinefunctions' => [
                   'mobile_course_view' => [],
                   'mobile_issues_view' => [],
               ], // Function that needs to be downloaded for offline.
           ],
       ],
       'lang' => [ // Language strings that are used in all the handlers.
           ['pluginname', 'certificate'],
           ['summaryofattempts', 'certificate'],
           ['getcertificate', 'certificate'],
           ['requiredtimenotmet', 'certificate'],
           ['viewcertificateviews', 'certificate'],
       ],
   ],

];

Plugin identifier
A unique name for the plugin, it can be anything (there’s no need to match the module name).
Handlers (Different places where the plugin will display content)
A plugin can be displayed in different views in the app. Each view should have a unique name inside the plugin scope (alphanumeric).
Display data
This is only needed for certain types of plugins. Also, depending on the type of delegate it may require additional (or less fields), in this case we are indicating the module icon.
Delegate
Where to display the link to the plugin, see the Delegates chapter in this documentation for all the possible options.
Method
This is the method in the Moodle \(component)\output\mobile class to be executed the first time the user clicks in the new option displayed in the app.
Offlinefunctions
These are the functions that need to be downloaded for offline usage. This is the list of functions that need to be called and stored when the user downloads a course for offline usage. Please note that you can add functions here that are not even listed in the mobile.php file.
In our example, downloading for offline access will mean that we'll execute the functions for getting the certificate and issued certificates passing as parameters the current userid (and courseid when we are using the mod or course delegate). If we have the result of those functions stored in the app, we'll be able to display the certificate information even if the user is offline.
Offline functions will be mostly used to display information for final users, any further interaction with the view won’t be supported offline (for example, trying to send information when the user is offline).
You can indicate here other Web Services functions, indicating the parameters that they might need from a defined subset (currently userid and courseid)
Prefetching the module will also download all the files returned by the methods in these offline functions (in the files array).
Note: If your functions use additional custom parameters (for example, if you implement multiple pages within a module's view function by using a 'page' parameter in addition to the usual cmid, courseid, userid) then the app will not know which additional parameters to supply. In this case, do not list the function in offlinefunctions; instead, you will need to manually implement a module prefetch handler.
Lang
The language pack string ids used in the plugin by all the handlers. Normally these will be strings from your own plugin, however, you can list any strings you need here (e.g. ['cancel', 'moodle']). If you do this, be warned that in the app you will then need to refer to that string as {{ 'plugin.myplugin.cancel' | translate }} (not {{ 'plugin.moodle.cancel' | translate }})
Please only include the strings you actually need. The Web Service that returns the plugin information will include the translation of each string id for every language installed in the platform, and this will then be cached, so listing too many strings is very wasteful.

There are additional attributes supported by the mobile.php list, see “Mobile.php supported options” section below.

Step 2. Creating the main function

The main function displays the current issued certificate (or several warnings if it’s not possible to issue a certificate). It also displays a link to view the dates of previously issued certificates.

All the functions must be created in the plugin or subsystem classes/output directory, the name of the class must be mobile.

For this example (mod_certificate plugin) the namespace name will be mod_certificate\output.

File contents: mod/certificate/classes/output/mobile.php

<?php namespace mod_certificate\output;

use context_module; use mod_certificate_external;

/**

* Mobile output class for certificate
*
* @package    mod_certificate
* @copyright  2018 Juan Leyva
* @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/

class mobile {

   /**
    * Returns the certificate course view for the mobile app.
    * @param  array $args Arguments from tool_mobile_get_content WS
    *
    * @return array       HTML, javascript and otherdata
    */
   public static function mobile_course_view($args) {
       global $OUTPUT, $USER, $DB;
       $args = (object) $args;
       $cm = get_coursemodule_from_id('certificate', $args->cmid);
       // Capabilities check.
       require_login($args->courseid , false , $cm, true, true);
       $context = \context_module::instance($cm->id);
       require_capability ('mod/certificate:view', $context);
       if ($args->userid != $USER->id) {
           require_capability('mod/certificate:manage', $context);
       }
       $certificate = $DB->get_record('certificate', array('id' => $cm->instance));
       // Get certificates from external (taking care of exceptions).
       try {
           $issued = \mod_certificate_external::issue_certificate($cm->instance);
           $certificates = \mod_certificate_external::get_issued_certificates($cm->instance);
           $issues = array_values($certificates['issues']); // Make it mustache compatible.
       } catch (Exception $e) {
           $issues = array();
       }
       // Set timemodified for each certificate.
       foreach ($issues as $issue) {
           if (empty($issue->timemodified)) {
                   $issue->timemodified = $issue->timecreated;
           }
       }
       $showget = true;
       if ($certificate->requiredtime && !has_capability('mod/certificate:manage', $context)) {
           if (certificate_get_course_time($certificate->course) < ($certificate->requiredtime * 60)) {
                   $showget = false;
           }
       }
       $certificate->name = format_string($certificate->name);
       list($certificate->intro, $certificate->introformat) =
                       external_format_text($certificate->intro, $certificate->introformat, $context->id,'mod_certificate', 'intro');
       $data = array(
           'certificate' => $certificate,
           'showget' => $showget && count($issues) > 0,
           'issues' => $issues,
           'issue' => $issues[0],
           'numissues' => count($issues),
           'cmid' => $cm->id,
           'courseid' => $args->courseid
       );
       return [
           'templates' => [
               [
                   'id' => 'main',
                   'html' => $OUTPUT->render_from_template('mod_certificate/mobile_view_page', $data),
               ],
           ],
           'javascript' => ,
           'otherdata' => ,
           'files' => $issues,
       ];
   }

}

Let’s go through the function code to analyse the different parts.

Function declaration
The function name is the same as the one used in the mobile.php file (method field). There is only one argument “$args” which is an array containing all the information sent by the mobile app (the courseid, userid, appid, appversionname, appversioncode, applang, appcustomurlscheme…)
Function implementation
In the first part of the function, we check permissions and capabilities (like a view.php script would do normally). Then we retrieve the certificate information that’s necessary to display the template.

Finally, we return:

  • The rendered template (notice that we could return more than one template but we usually would only need one). By default the app will always render the first template received, the rest of the templates can be used if the plugin defines some Javascript code.
  • JavaScript: Empty, because we don’t need any in this case
  • Other data: Empty as well, because we don’t need any additional data to be used by directives or components in the template. This field will be published as an object supporting 2-way-data-bind to the template.
  • Files: A list of files that the app should be able to download (for offline usage mostly)

Step 3. Creating the template for the main function

This is the most important part of your plugin because it contains the code that will be rendered on the mobile app.

In this template we’ll be using Ionic and custom directives and components available in the Mobile app.

All the HTML attributes starting with ion- are ionic components. Most of the time the component name is self-explanatory but you may refer to a detailed guide here: https://ionicframework.com/docs/components/

All the HTML attributes starting with core- are custom components of the Mobile app.

File contents: mod/certificate/templates/mobile_view_page.mustache

{{=<% %>=}}

   <core-course-module-description description="<% certificate.intro %>" component="mod_certificate" componentId="<% cmid %>"></core-course-module-description>
   <ion-list>
       <ion-list-header>

Template:'plugin.mod certificate.summaryofattempts'

       </ion-list-header>
       <%#issues%>
           <ion-item>
               <button ion-button block color="light" core-site-plugins-new-content title="<% certificate.name %>" component="mod_certificate" method="mobile_issues_view" [args]="{cmid: <% cmid %>, courseid: <% courseid %>}">
                   Template:'plugin.mod certificate.viewcertificateviews'
               </button>
           </ion-item>
       <%/issues%>
       <%#showget%>
       <ion-item>
           <button ion-button block core-course-download-module-main-file moduleId="<% cmid %>" courseId="<% certificate.course %>" component="mod_certificate" [files]="[{fileurl: '<% issue.fileurl %>', filename: '<% issue.filename %>', timemodified: '<% issue.timemodified %>', mimetype: '<% issue.mimetype %>'}]">
               <ion-icon name="cloud-download" item-start></ion-icon>
               Template:'plugin.mod certificate.getcertificate'
           </button>
       </ion-item>
       <%/showget%>
       <%^showget%>
       <ion-item>

Template:'plugin.mod certificate.requiredtimenotmet'

       </ion-item>
       <%/showget%>
       <span core-site-plugins-call-ws-on-load name="mod_certificate_view_certificate" [params]="{certificateid: <% certificate.id %>}" [preSets]="{getFromCache: 0, saveToCache: 0}">
   </ion-list>

In the first line of the template we switch delimiters to avoid conflicting with Ionic delimiters (that are curly brackets like mustache).

Then we display the module description using <core-course-module-description that is a component used to include the course module description.

For displaying the certificate information we create a list of elements, adding a header on top. The following line Template:'plugin.mod certificate.summaryofattempts' indicates that the Mobile app will translate the summaryofattempts string id (here we could’ve used mustache translation but it is usually better to delegate the strings translations to the app). The string id has this format:

“plugin” + plugin identifier (from mobile.php) + string id (the string must be indicated in the lang field in mobile.php).

Then we display a button to transition to another page if there are certificates issued. The attribute (directive) core-site-plugins-new-content indicates that if the user clicks the button, we need to call the function “mobile_issues_view” in the component “mod_certificate” passing as arguments the cmid and courseid. The content returned by this function will be displayed in a new page (see Step 4 for the code of this new page).

Just after this button we display another one but this time for downloading an issued certificate. The core-course-download-module-main-file directive indicates that clicking this button is for downloading the whole activity and opening the main file. This means that, when the user clicks this button, the whole certificate activity will be available in offline.

Finally, just before the ion-list is closed, we use the core-site-plugins-call-ws-on-load directive to indicate that once the page is loaded, we need to call to a Web Service function in the server, in this case we are calling the mod_certificate_view_certificate that will log that the user viewed this page.

As you can see, no JavaScript was necessary at all. We used plain HTML elements and attributes that did all the complex dynamic logic (like calling a Web Service) behind the scenes.

Step 4. Adding an additional page

Partial file contents: mod/certificate/classes/output/mobile.php

   /**
    * Returns the certificate issues view for the mobile app.
    * @param  array $args Arguments from tool_mobile_get_content WS
    *
    * @return array       HTML, javascript and otherdata
    */
   public static function mobile_issues_view($args) {
       global $OUTPUT, $USER, $DB;
       $args = (object) $args;
       $cm = get_coursemodule_from_id('certificate', $args->cmid);
       // Capabilities check.
       require_login($args->courseid , false , $cm, true, true);
       $context = context_module::instance($cm->id);
       require_capability ('mod/certificate:view', $context);
       if ($args->userid != $USER->id) {
           require_capability('mod/certificate:manage', $context);
       }
       $certificate = $DB->get_record('certificate', array('id' => $cm->instance));
       // Get certificates from external (taking care of exceptions).
       try {
           $issued = mod_certificate_external::issue_certificate($cm->instance);
           $certificates = mod_certificate_external::get_issued_certificates($cm->instance);
           $issues = array_values($certificates['issues']); // Make it mustache compatible.
       } catch (Exception $e) {
           $issues = array();
       }
       $data = [
           'issues' => $issues
       ];
       return [
           'templates' => [
               [
                   'id' => 'main',
                   'html' => $OUTPUT->render_from_template('mod_certificate/mobile_view_issues', $data),
               ],
           ],
           'javascript' => ,
           'otherdata' => ,
       ];
   }

This function for the new page was added just after the mobile_course_view function, the code is quite similar: Capabilities checks, retrieves the information required for the template and returns the template rendered.

The code of the mustache template is also very simple:

File contents: mod/certificate/templates/mobile_view_issues.mustache

{{=<% %>=}}

   <ion-list>
       <%#issues%>
           <ion-item>

{{ <%timecreated%> | coreToLocaleString }}

<%grade%>

           </ion-item>
       <%/issues%>
   </ion-list>

As we did in the previous template, in the first line of the template we switch delimiters to avoid conflicting with Ionic delimiters (that are curly brackets like mustache).

Here we are creating an ionic list that will display a new item in the list per each issued certificated.

For the issued certificated we’ll display the time when it was created (using the app filter coreToLocaleString). We are also displaying the grade displayed in the certificate (if any).

Step 5. Plugin webservices, if included

If your plugin uses its own web services, they will also need to be enabled for mobile access in your db/services.php file.

The following line 'services' => [MOODLE_OFFICIAL_MOBILE_SERVICE, 'local_mobile'], should be included in each webservice definition.

File contents: mod/certificate/db/services.php

$functions = [

   'mod_certificate_get_certificates_by_courses' => [
       'classname'     => 'mod_certificate_external',
       'methodname'    => 'get_certificates_by_courses',
       'description'   => 'Returns a list of certificate instances...',
       'type'          => 'read',
       'capabilities'  => 'mod/certificate:view',
       'services'      => [MOODLE_OFFICIAL_MOBILE_SERVICE, 'local_mobile'],
   ],

];

This extra services definition is the reason why you will need to have the local_mobile plugin installed for Moodle versions 3.4 and lower, so that your Moodle site will have all the additional webservices included to deal with all these mobile access calls. This is explained further in the Moodle version requirements section below.

Getting started

The first and most important thing to know is that you don’t need a local mobile environment, you can just use the Chrome or Chromium browser to add mobile support to your plugins!

Open this URL (with Chrome or Chromium browser): https://mobileapp.moodledemo.net/ and you will see a web version of the mobile app completely functional (except for some native features). This URL is updated with the latest integration version of the app.

Alternatively, you can use the Moodle Desktop App that is based in the master (latest stable) version of the app, it is based on Chromium so you can enable the "Developer Tools" and inspect the HTML, inject javascript, debug, etc...

To enable "Developer Tools" in Moodle Desktop (and the Chrome or Chromium browser);

  • In MacOS: Cmd + Option + I
  • In Windows or Linux: Ctrl + Shift + I

Please test that your site works correctly in the web version before starting any development.

Moodle version requirements

If your Moodle version is lower than 3.5 you will need to install the Moodle Mobile additional features plugin.

Please use this development version for now: https://github.com/moodlehq/moodle-local_mobile/commits/MOODLE_31_STABLE (if your Moodle version is 3.2, 3.3 or 3.4) you will have to use the specific branch for your version but applying manually the last commit from the 3.1 branch (the one with number MOBILE-2362).

Also, when installing the Moodle Mobile Additional features plugin you must follow the installation instructions so the service is set up properly.

Remember to update your plugin documentation to reflect that this plugin is mandatory for Mobile support. We don’t recommend to indicate in your plugin version.php a dependency to local_mobile though.

Development workflow

First of all, we recommend creating a simple mobile.php for displaying a new main menu option (even if your plugin won’t be in the main menu, just to verify that you are able to extend the app plugins). Then open the webapp (https://mobileapp.moodledemo.net/) or refresh the browser if it was already open. Alternatively, you can use the Moodle Desktop app, it is based on Chromium so you can enable the "Developer Tools" and inspect the HTML, inject javascript, debug, etc...

Check that you can correctly see the new menu option you included.

Then, develop the main function of the app returning a “Hello world” or basic code (without using templates) to see that everything works together. After adding the classes/output/mobile.php file it is very important to “Purge all caches” to avoid problems with the auto-loading cache.

It is important to remember that:

  • Any change in the mobile.php file will require you to refresh the web app page in the browser (remember to disable the cache in the Chrome developer options).
  • Any change in an existing template or function won’t require to refresh the browser page. In most cases you should just do a PTR (Pull down To Refresh) in the page that displays the view returned by the function. Be aware that PTR will work only when using the “device” emulation in the browser (see following section).

Testing and debugging

To learn how to debug with the web version of the app, please read the following documents:

For plugins using the Javascript API you may develop making use of the console.log function to add trace messages in your code that will be displayed in the browser console.

Within the app, make sure to turn on the option: App settings / General / Display debug messages. This means popup errors from the app will show more information.

Mobile.php supported options

In the Step by Step section we learned about some of the existing options for handlers configuration. This is the full list of supported options:

Common options

  • delegate (mandatory): Name of the delegate to register the handler in.
  • method (mandatory): The function to call to retrieve the main page content.
  • init (optional): A function to call to retrieve the initialization JS and the "restrict" to apply to the whole handler. It can also return templates that can be used from the Javascript of the init method or the Javascript of the handler’s method.
  • restricttocurrentuser (optional) Only used if the delegate has a isEnabledForUser function. If true, the handler will only be shown for current user. For more info about displaying the plugin only for certain users, please see Display the plugin only if certain conditions are met.
  • restricttoenrolledcourses (optional): Only used if the delegate has a isEnabledForCourse function. If true or not defined, the handler will only be shown for courses the user is enrolled in. For more info about displaying the plugin only for certain courses, please see Display the plugin only if certain conditions are met.
  • styles (optional): An array with two properties: url and version. The URL should point to a CSS file, either using an absolute URL or a relative URL. This file will be downloaded and applied by the app. It's recommended to include styles that will only affect your plugin templates. The version number is used to determine if the file needs to be downloaded again, you should change the version number everytime you change the CSS file.
  • moodlecomponent (optional): If your plugin supports a component in the app different than the one defined by your plugin, you can use this property to specify it. For example, you can create a local plugin to support a certain course format, activity, etc. The component of your plugin in Moodle would be local_whatever, but in "moodlecomponent" you can specify that this handler will implement format_whatever or mod_whatever. This property was introduced in the version 3.6.1 of the app.

Options only for CoreCourseOptionsDelegate

  • displaydata (mandatory): title, class.
  • priority (optional): Priority of the handler. Higher priority is displayed first.
  • ismenuhandler: (optional) Supported from the 3.7.1 version of the app. Set it to true if you want your plugin to be displayed in the contextual menu of the course instead of in the top tabs. The contextual menu is displayed when you click in the 3-dots button at the top right of the course.

Options only for CoreMainMenuDelegate

  • displaydata (mandatory):
    • title: a language string identifier that was included in the 'lang' section
    • icon: the name of an ionic icon. Valid strings are found here: https://infinitered.github.io/ionicons-version-3-search/ and search for ion-md. Do not include the 'md-' in the string. (eg 'md-information-circle' should be 'information-circle')
    • class
  • priority (optional): Priority of the handler. Higher priority is displayed first. Main Menu plugins are always displayed in the "More" tab, they cannot be displayed as tabs in the bottom bar.

Options only for CoreCourseModuleDelegate

  • displaydata (mandatory): icon, class.
  • method (optional): The function to call to retrieve the main page content. In this delegate the method is optional. If the method is not set, the module won't be clickable.
  • offlinefunctions: (optional) List of functions to call when prefetching the module. It can be a get_content method or a WS. You can filter the params received by the WS. By default, WS will receive these params: courseid, cmid, userid. Other valid values that will be added if they are present in the list of params: courseids (it will receive a list with the courses the user is enrolled in), component + 'id' (e.g. certificateid).
  • downloadbutton: (optional) Whether to display download button in the module. If not defined, the button will be shown if there is any offlinefunction.
  • isresource: (optional) Whether the module is a resource or an activity. Only used if there is any offlinefunction. If your module relies on the "contents" field, then it should be true.
  • updatesnames: (optional) Only used if there is any offlinefunction. A Regular Expression to check if there's any update in the module. It will be compared to the result of core_course_check_updates.
  • displayopeninbrowser: (optional) Supported from the 3.6 version of the app. Whether the module should display the "Open in browser" option in the top-right menu. This can be done in JavaScript too: this.displayOpenInBrowser = false;
  • displaydescription: (optional) Supported from the 3.6 version of the app. Whether the module should display the "Description" option in the top-right menu. This can be done in JavaScript too: this.displayDescription = false;
  • displayrefresh: (optional) Supported from the 3.6 version of the app. Whether the module should display the "Refresh" option in the top-right menu. This can be done in JavaScript too: this.displayRefresh = false;
  • displayprefetch: (optional) Supported from the 3.6 version of the app. Whether the module should display the download option in the top-right menu. This can be done in JavaScript too: this.displayPrefetch = false;
  • displaysize: (optional) Supported from the 3.6 version of the app. Whether the module should display the downloaded size in the top-right menu. This can be done in JavaScript too: this.displaySize = false;
  • coursepagemethod: (optional) Supported from the 3.8 version of the app. If set, this method will be called when the course is rendered and the HTML returned will be displayed in the course page for the module. Please notice the HTML returned should not contain directives or components, only default HTML.

Options only for CoreCourseFormatDelegate

  • canviewallsections: (optional) Whether the course format allows seeing all sections in a single page. Defaults to true.
  • displayenabledownload: (optional) Whether the option to enable section/module download should be displayed. Defaults to true.
  • displaysectionselector: (optional) Whether the default section selector should be displayed. Defaults to true.

Options only for CoreUserDelegate

  • displaydata (mandatory): title, icon, class.
  • type: The type of the addon. Values accepted: 'newpage' (default) or 'communication'.
  • priority (optional): Priority of the handler. Higher priority is displayed first.

Options only for CoreSettingsDelegate

  • displaydata (mandatory): title, icon, class.
  • priority (optional): Priority of the handler. Higher priority is displayed first.

Options only for AddonMessageOutputDelegate

  • displaydata (mandatory): title, icon.
  • priority (optional): Priority of the handler. Higher priority is displayed first.

Options only for CoreBlockDelegate

  • displaydata (optional): title, class, type. If title is not supplied, it will default to "plugins.block_blockname.pluginname", where blockname is the name of the block. If class is not supplied, it will default to "block_blockname", where blockname is the name of the block. Possible values of type:
    • "title": Your block will only display the block title, and when it's clicked it will open a new page to display the block contents (the template returned by the block's method).
    • "prerendered": Your block will display the content and footer returned by the WebService to get the blocks (e.g. core_block_get_course_blocks), so your block's method will never be called.
    • any other value: Your block will immediately call the method specified in mobile.php and it will use the template to render the block.
  • fallback: (optional) Supported from the 3.9.0 version of the app. This option allows you to specify a block to use in the app instead of your block. E.g. you can make the app display the "My overview" block instead of your block in the app by setting: 'fallback' => 'myoverview'. The fallback will only be used if you don't specify a method and the type is different than title or prerendered..

Delegates

The delegates can be classified by type of plugin. For more info about type of plugins, please see the See Types of plugins section.

Templates generated and downloaded when the user opens the plugins

CoreMainMenuDelegate

You must use this delegate when you want to add new items to the main menu (currently displayed at the bottom of the app).

CoreCourseOptionsDelegate

You must use this delegate when you want to add new options in a course (Participants or Grades are examples of this type of delegate).

CoreCourseModuleDelegate

You must use this delegate for supporting activity modules or resources.

CoreUserDelegate

You must use this delegate when you want to add additional options in the user profile page in the app.

CoreCourseFormatDelegate

You must use this delegate for supporting course formats. When you open a course from the course list in the mobile app, it will check if there is a CoreCourseFormatDelegate handler for the format that site uses. If so, it will display the course using that handler. Otherwise, it will use the default app course format. More information is available on Creating mobile course formats.

CoreSettingsDelegate

You must use this delegate to add a new option in the settings page.

AddonMessageOutputDelegate

You must use this delegate to support a message output plugin.

CoreBlockDelegate

You must use this delegate to support a block. As of Moodle App 3.7.0, blocks are only displayed in Site Home and Dashboard, but they'll be supported in other places of the app soon (e.g. in the course page).

Templates downloaded on login and rendered using JS data

CoreQuestionDelegate

You must use this delegate for supporting question types. https://docs.moodle.org/dev/Creating_mobile_question_types

CoreQuestionBehaviourDelegate

You must use this delegate for supporting question behaviours.

CoreUserProfileFieldDelegate

You must use this delegate for supporting user profile fields.

AddonModQuizAccessRuleDelegate

You must use this delegate to support a quiz access rule.

AddonModAssignSubmissionDelegate and AddonModAssignFeedbackDelegate

You must use these delegates to support assign submission or feedback plugins.

AddonWorkshopAssessmentStrategyDelegate

You must use this delegate to support a workshop assessment strategy plugin.

Pure Javascript plugins

These delegates require JavaScript to be supported. See Initialization for more information.

  • CoreContentLinksDelegate
  • CoreCourseModulePrefetchDelegate
  • CoreFileUploaderDelegate
  • CorePluginFileDelegate
  • CoreFilterDelegate

Available components and directives

Difference between component and directives

A component (represented as an HTML tag) is used to add custom elements to the app. Example of components are: ion-list, ion-item, core-search-box

A directive (represented as an HTML attribute) allows you to extend a piece of HTML with additional information or functionality. Example of directives are: core-auto-focus, *ngIf, ng-repeat

The Mobile app uses Angular, Ionic and custom components and directives, for a full reference of:

Custom core components and directives

These are some useful custom components and directives (only available in the mobile app). Please note that this isn’t the full list of components and directives of the app, it’s just an extract of the most common ones.

For a full list of components, go to https://github.com/moodlehq/moodlemobile2/tree/master/src/components

For a full list of directives, go to https://github.com/moodlehq/moodlemobile2/tree/master/src/directives

core-format-text

This directive formats the text and adds some directives needed for the app to work as it should. For example, it treats all links and all the embedded media so they work fine in the app. If some content in your template includes links or embedded media, please use this directive.

This directive automatically applies core-external-content and core-link to all the links and embedded media.

Data that can be passed to the directive:

  • text (string): The text to format.
  • siteId (string): Optional. Site ID to use. If not defined, current site.
  • component (string): Optional. Component to use when downloading embedded files.
  • componentId (string|number): Optional. ID to use in conjunction with the component.
  • adaptImg (boolean): Optional. Whether to adapt images to screen width. Defaults to true.
  • clean (boolean): Optional. Whether all the HTML tags should be removed. Defaults to false.
  • singleLine (boolean): Optional. Whether new lines should be removed (all text in single line). Only if clean=true. Defaults to false.
  • maxHeight (number): Optional. Max height in pixels to render the content box. It should be 50 at least to make sense. Using this parameter will force display: block to calculate height better. If you want to avoid this use class="inline" at the same time to use display: inline-block.
  • fullOnClick (boolean): Optional. Whether it should open a new page with the full contents on click. Only if maxHeight is set and the content has been collapsed. Defaults to false.
  • fullTitle (string): Optional. Title to use in full view. Defaults to "Description".

Example usage:

<core-format-text text="<% cm.description %>" component="mod_certificate" componentId="<% cm.id %>"></core-format-text>

core-link

Directive to handle a link. It performs several checks, like checking if the link needs to be opened in the app, and opens the link as it should (without overriding the app).

This directive is automatically applied to all the links and media inside core-format-text.

Data that can be passed to the directive:

  • capture (boolean): Optional, default false. Whether the link needs to be captured by the app (check if the link can be handled by the app instead of opening it in a browser).
  • inApp (boolean): Optional, default false. True to open in embedded browser, false to open in system browser.
  • autoLogin (string): Optional, default "check". If the link should be open with auto-login. Accepts the following values:
    • "yes" -> Always auto-login.
    • "no" -> Never auto-login.
    • "check" -> Auto-login only if it points to the current site. Default value.

Example usage: <a href="<% cm.url %>" core-link>

core-external-content

Directive to handle links to files and embedded files. This directive should be used in any link to a file or any embedded file that you want to have available when the app is offline.

If a file is downloaded, its URL will be replaced by the local file URL.

This directive is automatically applied to all the links and media inside core-format-text.

Data that can be passed to the directive:

  • siteId (string): Optional. Site ID to use. If not defined, current site.
  • component (string): Optional. Component to use when downloading embedded files.
  • componentId (string|number): Optional. ID to use in conjunction with the component.

Example usage: <img src="<% event.iconurl %>" core-external-content component="mod_certificate" componentId="<% event.id %>">

core-user-link

Directive to go to user profile on click. When the user clicks the element where this directive is attached, the right user profile will be opened.

Data that can be passed to the directive:

  • userId (number): User id to open the profile.
  • courseId (number): Optional. Course id to show the user info related to that course.

Example usage: <a ion-item core-user-link userId="<% userid %>">

core-file

Component to handle a remote file. It shows the file name, icon (depending on mimetype) and a button to download/refresh it. The user can identify if the file is downloaded or not based on the button.

Data that can be passed to the directive:

  • file (object): The file. Must have a property 'filename' and a 'fileurl' or 'url'
  • component (string): Optional. Component the file belongs to.
  • componentId (string|number): Optional. ID to use in conjunction with the component.
  • canDelete (boolean): Optional. Whether file can be deleted.
  • alwaysDownload (boolean): Optional. Whether it should always display the refresh button when the file is downloaded. Use it for files that you cannot determine if they're outdated or not.
  • canDownload (boolean): Optional. Whether file can be downloaded. Defaults to true.

Example usage: <core-file [file]="{fileurl: '<% issue.url %>', filename: '<% issue.name %>', timemodified: '<% issue.timemodified %>', filesize: '<% issue.size %>'}" component="mod_certificate" componentId="<% cm.id %>"></core-file>

core-download-file

Directive to allow downloading and open a file. When the item with this directive is clicked, the file will be downloaded (if needed) and opened.

It is usually recommended to use the core-file component since it also displays the state of the file.

Data that can be passed to the directive:

  • core-download-file (object): The file to download.
  • component (string): Optional. Component to link the file to.
  • componentId (string|number): Optional. Component ID to use in conjunction with the component.

Example usage: a button to download a file. <button ion-button [core-download-file]="{fileurl: <% issue.url %>, timemodified: <% issue.timemodified %>, filesize: <% issue.size %>}" component="mod_certificate" componentId="<% cm.id %>">

    Template:'plugin.mod certificate.download

</button>

core-course-download-module-main-file

Directive to allow downloading and opening the main file of a module.

When the item with this directive is clicked, the whole module will be downloaded (if needed) and its main file opened. This is meant for modules like mod_resource.

This directive must receive either a module or a moduleId. If no files are provided, it will use module.contents.

Data that can be passed to the directive:

  • module (object): Optional. The module object. Required if module is not supplied.
  • moduleId (number): Optional. The module ID. Required if module is not supplied.
  • courseId (number): The course ID the module belongs to.
  • component (string): Optional. Component to link the file to.
  • componentId (string|number): Optional. Component ID to use in conjunction with the component. If not defined, moduleId.
  • files (object[]): Optional. List of files of the module. If not provided, use module.contents.

Example usage: <button ion-button block core-course-download-module-main-file moduleId="<% cmid %>" courseId="<% certificate.course %>" component="mod_certificate" [files]="[{fileurl: '<% issue.fileurl %>', filename: '<% issue.filename %>', timemodified: '<% issue.timemodified %>', mimetype: '<% issue.mimetype %>'}]">

   Template:'plugin.mod certificate.getcertificate'

</button>

core-navbar-buttons

Component to add buttons to the app's header without having to place them inside the header itself. Using this component in a site plugin will allow adding buttons to the header of the current page.

If this component indicates a position (start/end), the buttons will only be added if the header has some buttons in that position. If no start/end is specified, then the buttons will be added to the first <ion-buttons> found in the header.

You can use the [hidden] input to hide all the inner buttons if a certain condition is met.

Example usage: <core-navbar-buttons end>

   <button ion-button icon-only (click)="action()">
       <ion-icon name="funnel"></ion-icon>
   </button>

</core-navbar-buttons>

You can also use this to add options to the context menu. Example usage:

<core-navbar-buttons>

   <core-context-menu>
       <core-context-menu-item [priority]="500" [content]="'Nice boat'" (action)="boatFunction()" [iconAction]="'boat'"></core-context-menu-item>
   </core-context-menu>

</core-navbar-buttons>

Note that it is not currently possible to remove or modify options from the context menu without using a nasty hack.

Specific component and directives for plugins

These are component and directives created specifically for supporting Moodle plugins.

core-site-plugins-new-content

Directive to display a new content when clicked. This new content can be displayed in a new page or in the current page (only if the current page is already displaying a site plugin content).

Data that can be passed to the directive:

  • component (string): The component of the new content.
  • method (string): The method to get the new content.
  • args (object): The params to get the new content.
  • preSets (object): Extra options for the WS call of the new content: whether to use cache or not, etc. This field was added in v3.6.0.
  • title (string): The title to display with the new content. Only if samePage=false.
  • samePage (boolean): Whether to display the content in same page or open a new one. Defaults to new page.
  • useOtherData (any): Whether to include otherdata (from the get_content WS call) in the args for the new get_content call. If not supplied, no other data will be added. If supplied but empty (null, false or empty string) all the otherdata will be added. If it’s an array, it will only copy the properties whose names are in the array. Please notice that [useOtherData]="" is the same as not supplying it, so nothing will be copied. Also, objects or arrays in otherdata will be converted to a JSON encoded string.
  • form (string): ID or name to identify a form in the template. The form will be obtained from document.forms. If supplied and form is found, the form data will be retrieved and sent to the new get_content WS call. If your form contains an ion-radio, ion-checkbox or ion-select, please see Values of ion-radio, ion-checkbox or ion-select aren't sent to my WS.

Example usages:

A button to go to a new content page: <button ion-button core-site-plugins-new-content title="<% certificate.name %>" component="mod_certificate" method="mobile_issues_view" [args]="{cmid: <% cmid %>, courseid: <% courseid %>}">

    Template:'plugin.mod certificate.viewissued'

</button>

A button to load new content in current page using userid from otherdata: <button ion-button core-site-plugins-new-content component="mod_certificate" method="mobile_issues_view" [args]="{cmid: <% cmid %>, courseid: <% courseid %>}" samePage="true" [useOtherData]="['userid']">

   Template:'plugin.mod certificate.viewissued'

</button>

core-site-plugins-call-ws

Directive to call a WS when the element is clicked. The action to do when the WS call is successful depends on the provided data: display a message, go back or refresh current view.

If you want to load a new content when the WS call is done, please see core-site-plugins-call-ws-new-content.

Data that can be passed to the directive:

  • name (string): The name of the WS to call.
  • params (object): The params for the WS call.
  • preSets (object): Extra options for the WS call: whether to use cache or not, etc.
  • useOtherDataForWS (any): Whether to include otherdata (from the get_content WS call) in the params for the WS call. If not supplied, no other data will be added. If supplied but empty (null, false or empty string) all the otherdata will be added. If it’s an array, it will only copy the properties whose names are in the array. Please notice that [useOtherDataForWS]="" is the same as not supplying it, so nothing will be copied. Also, objects or arrays in otherdata will be converted to a JSON encoded string.
  • form (string): ID or name to identify a form in the template. The form will be obtained from document.forms. If supplied and form is found, the form data will be retrieved and sent to the WS. If your form contains an ion-radio, ion-checkbox or ion-select, please see Values of ion-radio, ion-checkbox or ion-select aren't sent to my WS.
  • confirmMessage (string): Message to confirm the action when the user clicks the element. If not supplied, no confirmation. If supplied but empty, default message ("Are you sure?").
  • showError (boolean): Whether to show an error message if the WS call fails. Defaults to true. This field was added in v3.5.2.
  • successMessage (string): Message to show on success. If not supplied, no message. If supplied but empty, default message (“Success”).
  • goBackOnSuccess (boolean): Whether to go back if the WS call is successful.
  • refreshOnSuccess (boolean): Whether to refresh the current view if the WS call is successful.
  • onSuccess (Function): A function to call when the WS call is successful (HTTP call successful and no exception returned). This field was added in v3.5.2.
  • onError (Function): A function to call when the WS call fails (HTTP call fails or an exception is returned). This field was added in v3.5.2.
  • onDone (Function): A function to call when the WS call finishes (either success or fail). This field was added in v3.5.2.

Example usages:

A button to send some data to the server without using cache, displaying default messages and refreshing on success: <button ion-button core-site-plugins-call-ws name="mod_certificate_view_certificate" [params]="{certificateid: <% certificate.id %>}" [preSets]="{getFromCache: 0, saveToCache: 0}" confirmMessage successMessage refreshOnSuccess="true">

   Template:'plugin.mod certificate.senddata'

</button>

A button to send some data to the server using cache without confirming, going back on success and using userid from otherdata: <button ion-button core-site-plugins-call-ws name="mod_certificate_view_certificate" [params]="{certificateid: <% certificate.id %>}" goBackOnSuccess="true" [useOtherData]="['userid']">

    Template:'plugin.mod certificate.senddata'

</button>

Same example as the previous one but implementing a custom JS code to run on success:

<button ion-button core-site-plugins-call-ws name="mod_certificate_view_certificate" [params]="{certificateid: <% certificate.id %>}" [useOtherData]="['userid']" (onSuccess)="certificateViewed($event)">

    Template:'plugin.mod certificate.senddata'

</button> this.certificateViewed = function(result) {

   // Code to run when the WS call is successful.

};

core-site-plugins-call-ws-new-content

Directive to call a WS when the element is clicked and load a new content passing the WS result as args. This new content can be displayed in a new page or in the same page (only if current page is already displaying a site plugin content).

If you don't need to load some new content when done, please see core-site-plugins-call-ws.

Data that can be passed to the directive:

  • name (string): The name of the WS to call.
  • params (object): The params for the WS call.
  • preSets (object): Extra options for the WS call: whether to use cache or not, etc.
  • useOtherDataForWS (any): Whether to include otherdata (from the get_content WS call) in the params for the WS call. If not supplied, no other data will be added. If supplied but empty (null, false or empty string) all the otherdata will be added. If it’s an array, it will only copy the properties whose names are in the array. Please notice that [useOtherDataForWS]="" is the same as not supplying it, so nothing will be copied. Also, objects or arrays in otherdata will be converted to a JSON encoded string.
  • form (string): ID or name to identify a form in the template. The form will be obtained from document.forms. If supplied and form is found, the form data will be retrieved and sent to the WS. If your form contains an ion-radio, ion-checkbox or ion-select, please see Values of ion-radio, ion-checkbox or ion-select aren't sent to my WS.
  • confirmMessage (string): Message to confirm the action when the user clicks the element. If not supplied, no confirmation. If supplied but empty, default message ("Are you sure?").
  • showError (boolean): Whether to show an error message if the WS call fails. Defaults to true. This field was added in v3.5.2.
  • component (string): The component of the new content.
  • method (string): The method to get the new content.
  • args (object): The params to get the new content.
  • title (string): The title to display with the new content. Only if samePage=false.
  • samePage (boolean): Whether to display the content in same page or open a new one. Defaults to new page.
  • useOtherData (any): Whether to include otherdata (from the get_content WS call) in the args for the new get_content call. The format is the same as in useOtherDataForWS.
  • jsData (any): JS variables to pass to the new page so they can be used in the template or JS. If true is supplied instead of an object, all initial variables from current page will be copied. This field was added in v3.5.2.
  • newContentPreSets (object): Extra options for the WS call of the new content: whether to use cache or not, etc. This field was added in v3.6.0.
  • onSuccess (Function): A function to call when the WS call is successful (HTTP call successful and no exception returned). This field was added in v3.5.2.
  • onError (Function): A function to call when the WS call fails (HTTP call fails or an exception is returned). This field was added in v3.5.2.
  • onDone (Function): A function to call when the WS call finishes (either success or fail). This field was added in v3.5.2.

Example usages:

A button to get some data from the server without using cache, showing default confirm and displaying a new page: <button ion-button core-site-plugins-call-ws-new-content name="mod_certificate_get_issued_certificates" [params]="{certificateid: <% certificate.id %>}" [preSets]="{getFromCache: 0, saveToCache: 0}" confirmMessage title="<% certificate.name %>" component="mod_certificate" method="mobile_issues_view" [args]="{cmid: <% cmid %>, courseid: <% courseid %>}">

   Template:'plugin.mod certificate.getissued'

</button>

A button to get some data from the server using cache, without confirm, displaying new content in same page and using userid from otherdata: <button ion-button core-site-plugins-call-ws-new-content name="mod_certificate_get_issued_certificates" [params]="{certificateid: <% certificate.id %>}" component="mod_certificate" method="mobile_issues_view" [args]="{cmid: <% cmid %>, courseid: <% courseid %>}" samePage="true" [useOtherData]="['userid']">

   Template:'plugin.mod certificate.getissued'

</button>

Same example as the previous one but implementing a custom JS code to run on success:

<button ion-button core-site-plugins-call-ws-new-content name="mod_certificate_get_issued_certificates" [params]="{certificateid: <% certificate.id %>}" component="mod_certificate" method="mobile_issues_view" [args]="{cmid: <% cmid %>, courseid: <% courseid %>}" samePage="true" [useOtherData]="['userid']" (onSuccess)="callDone($event)">

   Template:'plugin.mod certificate.getissued'

</button> this.callDone = function(result) {

   // Code to run when the WS call is successful.

};

core-site-plugins-call-ws-on-load

Directive to call a WS as soon as the template is loaded. This directive is meant for actions to do in the background, like calling logging Web Services.

If you want to call a WS when the user clicks on a certain element, please see core-site-plugins-call-ws.

Note that this will cause an error to appear on each page load if the user is offline in v3.5.1 and older, the bug was fixed in v3.5.2.

  • name (string): The name of the WS to call.
  • params (object): The params for the WS call.
  • preSets (object): Extra options for the WS call: whether to use cache or not, etc.
  • useOtherDataForWS (any): Whether to include otherdata (from the get_content WS call) in the params for the WS call. If not supplied, no other data will be added. If supplied but empty (null, false or empty string) all the otherdata will be added. If it’s an array, it will only copy the properties whose names are in the array. Please notice that [useOtherDataForWS]="" is the same as not supplying it, so nothing will be copied. Also, objects or arrays in otherdata will be converted to a JSON encoded string.
  • form (string): ID or name to identify a form in the template. The form will be obtained from document.forms. If supplied and form is found, the form data will be retrieved and sent to the WS. If your form contains an ion-radio, ion-checkbox or ion-select, please see Values of ion-radio, ion-checkbox or ion-select aren't sent to my WS.
  • onSuccess (Function): A function to call when the WS call is successful (HTTP call successful and no exception returned). This field was added in v3.5.2.
  • onError (Function): A function to call when the WS call fails (HTTP call fails or an exception is returned). This field was added in v3.5.2.
  • onDone (Function): A function to call when the WS call finishes (either success or fail). This field was added in v3.5.2.

Example usage: <span core-site-plugins-call-ws-on-load name="mod_certificate_view_certificate" [params]="{certificateid: <% certificate.id %>}" [preSets]="{getFromCache: 0, saveToCache: 0}" (onSuccess)="callDone($event)"> this.callDone = function(result) {

   // Code to run when the WS call is successful.

};

Advanced features

Display the plugin only if certain conditions are met

You might want to display your plugin in the mobile app only if certain dynamic conditions are met, so the plugin would be displayed only for some users. This can be achieved using the "init" method (for more info, please see the Initialization section ahead).

All the init methods are called as soon as your plugin is retrieved. If you don't want your plugin to be displayed for the current user, then you should return this in the init method (only for Moodle 3.8 and onwards).

return [

   'disabled' => true

];

If the Moodle version is older than 3.8, then the init method should return this:

return [

   'javascript' => 'this.HANDLER_DISABLED'

];

On the other hand, you might want to display a plugin only for certain courses (CoreCourseOptionsDelegate) or only if the user is viewing certain users' profiles (CoreUserDelegate). This can be achieved with the init method too.

In the init method you can return a "restrict" property with two fields in it: courses and users. If you return a list of courses IDs in this restrict property, then your plugin will only be displayed when the user views any of those courses. In the same way, if you return a list of user IDs then your plugin will only be displayed when the user views any of those users' profiles.

Using “otherdata”

The values returned by the functions in otherdata are added to a variable so they can be used both in Javascript and in templates. The otherdata returned by a init call is added to a variable named INIT_OTHERDATA, while the otherdata returned by a get_content WS call is added to a variable named CONTENT_OTHERDATA.

The otherdata returned by a init call will be passed to the JS and template of all the get_content calls in that handler. The otherdata returned by a get_content call will only be passed to the JS and template returned by that get_content call.

This means that, in your Javascript, you can access and use these data like this: this.CONTENT_OTHERDATA.myVar And in the template you could use it like this: Template:CONTENT OTHERDATA.myVar myVar is the name we put to one of our variables, it can be the name you want. In the example above, this is the otherdata returned by the PHP method:

array('myVar' => 'Initial value')

Example

In our plugin we want to display an input text with a certain initial value. When the user clicks a button, we want the value in the input to be sent to a certain WebService. This can be done using otherdata.

We will return the initial value of the input in the otherdata of our PHP method: 'otherdata' => array('myVar' => 'My initial value'), Then in the template we will use it like this: <ion-item text-wrap>

   <ion-label stacked>Template:'plugin.mod certificate.textlabel</ion-label>
   <ion-input type="text" [(ngModel)]="CONTENT_OTHERDATA.myVar"></ion-input>

</ion-item> <ion-item>

   <button ion-button block color="light" core-site-plugins-call-ws name="mod_certificate_my_webservice" [useOtherDataForWS]="['myVar']">
       Template:'plugin.mod certificate.send
   </button>

</ion-item>

In the example above, we are creating an input text and we use [(ngModel)] to use the value in myVar as the initial value and to store the changes in the same myVar variable. This means that the initial value of the input will be “My initial value”, and if the user changes the value of the input these changes will be applied to the myVar variable. This is called 2-way data binding in Angular.

Then we add a button to send this data to a WS, and for that we use the directive core-site-plugins-call-ws. We use the useOtherDataForWS attribute to specify which variable from otherdata we want to send to our WebService. So if the user enters “A new value” in the input and then clicks the button, it will call the WebService mod_certificate_my_webservice and will send as a param: myVar -> “A new value”.

We can achieve the same result using the params attribute of the core-site-plugins-call-ws directive instead of using useOtherDataForWS: <button ion-button block color="light" core-site-plugins-call-ws name="mod_certificate_my_webservice" [params]="{myVar: CONTENT_OTHERDATA.myVar}">

   Template:'plugin.mod certificate.send

</button> The WebService call will be exactly the same with both buttons.

Please notice that this example could be done without using otherdata too, using the “form” input of the core-site-plugins-call-ws directive.

Running JS code after a content template has loaded

When you return JavaScript code from a handler function using the 'javascript' array key, this code is executed immediately after the web service call returns, which may be before the returned template has been rendered into the DOM.

If your code needs to run after the DOM has been updated, you can use setTimeout to call it. For example:

return [

   'template' => [ ... ],
   'javascript' => 'setTimeout(function() { console.log("DOM is available now"); });',
   'otherdata' => ,
   'files' => []

];

Note: If you wanted to write a lot of code here, you might be better off putting it in a function defined in the response from an init template, so that it does not get loaded again with each page of content.

JS functions visible in the templates

The app provides some Javascript functions that can be used from the templates to update, refresh or view content. These are the functions:

  • openContent(title: string, args: any, component?: string, method?: string): Open a new page to display some new content. You need to specify the title of the new page and the args to send to the method. If component and method aren't provided, it will use the same as in the current page.
  • refreshContent(showSpinner = true): Refresh the current content. By default it will display a spinner while refreshing, if you don't want it to be displayed you should pass false as a parameter.
  • updateContent(args: any, component?: string, method?: string): Refresh the current content using different params. You need to specify the args to send to the method. If component and method aren't provided, it will use the same as in the current page.

Examples

Group selector

Imagine we have an activity that uses groups and we want to let the user select which group he wants to see. A possible solution would be to return all the groups in the same template (hidden), and then show the group user selects. However, we can make it more dynamic and return only the group the user is requesting.

To do so, we'll use a drop down to select the group. When the user selects a group using this drop down we'll update the page content to display the new group.

The main difficulty in this is to tell the view which group needs to be selected when the view is loaded. There are 2 ways to do it: using plain HTML or using Angular's ngModel.

Using plain HTML

We need to add a "selected" attribute to the option that needs to be selected. To do so, we need to pre-caclulate the selected option in the PHP code:

       $groupid = empty($args->group) ? 0 : $args->group; // By default, group 0.
       $groups = groups_get_activity_allowed_groups($cm, $user->id);
       // Detect which group is selected.
       foreach ($groups as $gid=>$group) {
           $group->selected = $gid === $groupid;
       }
       $data = array(
           'cmid' => $cm->id,
           'courseid' => $args->courseid,
           'groups' => $groups
       );
       return array(
           'templates' => array(
               array(
                   'id' => 'main',
                   'html' => $OUTPUT->render_from_template('mod_certificate/mobile_view_page', $data),
               ),
           ),
       );

In the code above, we're retrieving the groups the user can see and then we're adding a "selected" bool to each one to determine which one needs to be selected in the drop down. Finally, we pass the list of groups to the template.

In the template, we display the drop down like this:

<ion-select (ionChange)="updateContent({cmid: <% cmid %>, courseid: <% courseid %>, group: $event})" interface="popover">

   <%#groups%>
       <ion-option value="<% id %>" <%#selected%>selected<%/selected%> ><% name %></ion-option>
   <%/groups%>

</ion-select>

The ionChange function will be called everytime the user selects a different group with the drop down. We're using the function updateContent to update the current view using the new group. $event is an Angular variable that will have the selected value (in our case, the group ID that was just selected). This is enough to make the group selector work.

Using ngModel

ngModel is an Angular directive that allows storing the value of a certain input/select in a Javascript variable, and also the opposite way: tell the input/select which value to set. The main problem is that we cannot initialize a Javascript variable from the template (Angular doesn't have ng-init like in AngularJS), so we'll use "otherdata".

In the PHP function we'll return the group that needs to be selected in the otherdata array:

       $groupid = empty($args->group) ? 0 : $args->group; // By default, group 0.
       $groups = groups_get_activity_allowed_groups($cm, $user->id);
        ...
        return array(
           'templates' => array(
               array(
                   'id' => 'main',
                   'html' => $OUTPUT->render_from_template('mod_certificate/mobile_view_page', $data),
               ),
           ),
           'otherdata' => array(
               'group' => $groupid
           ),
       );

In the example above we don't need to iterate over the groups array like in the plain HTML example. However, now we're returning the groupid in the "otherdata" array. As it's explained in the Using "otherdata" section, this "otherdata" is visible in the templates inside a variable named CONTENT_OTHERDATA. So in the template we'll use this variable like this:

<ion-select [(ngModel)]="CONTENT_OTHERDATA.group" (ionChange)="updateContent({cmid: <% cmid %>, courseid: <% courseid %>, group: CONTENT_OTHERDATA.group})" interface="popover">

   <%#groups%>
       <ion-option value="<% id %>"><% name %></ion-option>
   <%/groups%>

</ion-select>

Use the rich text editor

The rich text editor included in the app requires a FormControl to work. You can use the library FormBuilder to create this control (or to create a whole FormGroup if you prefer).

With the following Javascript you'll be able to create a FormControl:

this.control = this.FormBuilder.control(this.CONTENT_OTHERDATA.rte);

In the example above we're using a value returned in OTHERDATA as the initial value of the rich text editor, but you can use whatever you want.

Then you need to pass this control to the rich text editor in your template:

<ion-item>

   <core-rich-text-editor item-content [control]="control" placeholder="Enter your text here" name="rte_answer"></core-rich-text-editor>

</ion-item>

Finally, there are several ways to send the value in the rich text editor to a WebService to save it. This is one of the simplest options:

<button ion-button block type="submit" core-site-plugins-call-ws name="my_webservice" [params]="{rte: control.value}" ....

As you can see, we're passing the value of the rich text editor as a parameter to our WebService.

Initialization

All handlers can specify a “init” method in the mobile.php file. This method is meant to return some JavaScript code that needs to be executed as soon as the plugin is retrieved.

When the app retrieves all the handlers, the first thing it will do is call the tool_mobile_get_content WebService with the init method. This WS call will only receive the default args.

The app will immediately execute the JavaScript code returned by this WS call. This JavaScript can be used to manually register your handlers in the delegates you want, without having to rely on the default handlers built based on the mobile.php data.

The templates returned by this init method will be added to a INIT_TEMPLATES variable that will be passed to all the Javascript code of that handler. This means that the Javascript returned by the init method or the “main” method can access any of the templates HTML like this: this.INIT_TEMPLATES[‘main’]; In this case, “main” is the ID of the template we want to use.

The same happens with the otherdata returned by this init method, it is added to a INIT_OTHERDATA variable.

The restrict field returned by this init call will be used to determine if your handler is enabled or not. For example, if your handler is for the delegate CoreCourseOptionsDelegate and you return a list of courseids in restrict->courses, then your handler will only be enabled in the courses you returned. This only applies to the “default” handlers, if you register your own handler using the Javascript code then you should check yourself if the handler is enabled.

Finally, if you return an object in this init Javascript code, all the properties of that object will be passed to all the Javascript code of that handler so you can use them when the code is run. For example, if your init Javascript code does something like this: var result = {

   MyAddonClass: new MyAddonClass()

}; result; Then, for the rest of Javascript code of your handler (e.g. for the “main” method) you can use this variable like this: this.MyAddonClass

Examples

Module link handler

A link handler allows you to decide what to do when a link with a certain URL is clicked. This is useful, for example, to open your module when a link to the module is clicked. In this example we’ll create a link handler to detect links to a certificate module using a init JavaScript: var that = this;

function AddonModCertificateModuleLinkHandler() {

   that.CoreContentLinksModuleIndexHandler.call(this, that.CoreCourseHelperProvider, 'mmaModCertificate', 'certificate');
   this.name = "AddonModCertificateLinkHandler";

}

AddonModCertificateModuleLinkHandler.prototype = Object.create(this.CoreContentLinksModuleIndexHandler.prototype); AddonModCertificateModuleLinkHandler.prototype.constructor = AddonModCertificateModuleLinkHandler;

this.CoreContentLinksDelegate.registerHandler(new AddonModCertificateModuleLinkHandler());

Advanced link handler

Link handlers have some advanced features that allow you to change how links behave under different conditions.

Patterns

You can define a Regular Expression pattern to match certain links. This will apply the handler only to links that match the pattern. function AddonModFooLinkHandler() {

   ....
   this.pattern = RegExp('\/mod\/foo\/specialpage.php');
   ....

}

Priority

Multiple link handlers may apply to a given link. You can define the order of precedence by setting the priority - the handler with the highest priority will be used. All default handlers have a priority of 0, so 1 or higher will override the default. function AddonModFooLinkHandler() {

   ....
   this.priority = 1;
   ....

}

Multiple actions

Once a link has been matched, the handler's getActions() method determines what the link should do. This method has access to the URL and its parameters. Different actions can be returned depending on different conditions. AddonModFooLinkHandler.prototype.getActions = function(siteIds, url, params) {

   return [{
       action: function(siteId, navCtrl) {
           // The actual behaviour of the link goes here.
       },
       sites: [...]
   }, {
       ...
   }];

} Once handlers have been matched for a link, the actions will be fetched for all the matching handlers, in priorty order. The first "valid" action will be used to open the link. If your handler is matched with a link, but a condition assessed in the getActions() function means you want to revert to the next highest priorty handler, you can "invalidate" your action by settings its sites propety to an empty array.

Complex example

This will match all URLs containing /mod/foo/, and force those with an id parameter that's not in the "supportedModFoos" array to open in the user's browser, rather than the app.

var that = this; var supportedModFoos = [...]; function AddonModFooLinkHandler() {

   this.pattern = new RegExp('\/mod\/foo\/');
   this.name = "AddonModFooLinkHandler";
   this.priority = 1;

} AddonModFooLinkHandler.prototype = Object.create(that.CoreContentLinksHandlerBase.prototype); AddonModFooLinkHandler.prototype.constructor = AddonModFooLinkHandler; AddonModFooLinkHandler.prototype.getActions = function(siteIds, url, params) {

   var action = {
       action: function() {
           that.CoreUtilsProvider.openInBrowser(url);
       }
   };
   if (supportedModFoos.indexOf(parseInt(params.id)) !== -1) {
       action.sites = [];
   }
   return [action];

}; that.CoreContentLinksDelegate.registerHandler(new AddonModFooLinkHandler());

Module prefetch handler

The CoreCourseModuleDelegate handler allows you to define a list of offlinefunctions to prefetch a module. However, you might want to create your own prefetch handler to determine what needs to be downloaded. For example, you might need to chain WS calls (pass the result of a WS call to the next one), and this cannot be done using offlinefunctions.

Here’s an example on how to create a prefetch handler using init JS: var that = this;

// Create a class that "inherits" from CoreCourseActivityPrefetchHandlerBase. function AddonModCertificateModulePrefetchHandler() {

   that.CoreCourseActivityPrefetchHandlerBase.call(this, that.TranslateService, that.CoreAppProvider, that.CoreUtilsProvider,
           that.CoreCourseProvider, that.CoreFilepoolProvider, that.CoreSitesProvider, that.CoreDomUtilsProvider);
   this.name = "AddonModCertificateModulePrefetchHandler";
   this.modName = "certificate";
   this.component = "mod_certificate"; // This must match the plugin identifier from db/mobile.php, otherwise the download link in the context menu will not update correctly.
   this.updatesNames = /^configuration$|^.*files$/;

}

AddonModCertificateModulePrefetchHandler.prototype = Object.create(this.CoreCourseActivityPrefetchHandlerBase.prototype); AddonModCertificateModulePrefetchHandler.prototype.constructor = AddonModCertificateModulePrefetchHandler;

// Override the prefetch call. AddonModCertificateModulePrefetchHandler.prototype.prefetch = function(module, courseId, single, dirPath) {

   return this.prefetchPackage(module, courseId, single, prefetchCertificate);

};

function prefetchCertificate(module, courseId, single, siteId) {

   // Perform all the WS calls.
   // You can access most of the app providers using that.ClassName. E.g. that.CoreWSProvider.call().

}

this.CoreCourseModulePrefetchDelegate.registerHandler(new AddonModCertificateModulePrefetchHandler());

One relatively simple full example is where you have a function that needs to work offline, but it has an additional argument other than the standard ones. You can imagine for this an activity like the book module, where it has multiple pages for the same cmid. The app will not automatically work with this situation - it will call the offline function with the standard arguments only, so you won't be able to prefetch all the possible parameters.

To deal with this, you need to implement a web service in your Moodle component that returns the list of possible extra arguments, and then you can call this web service and loop around doing the same thing the app does when it prefetches the offline functions. Here is an example from a third-party module (showing only the actual prefetch function - the rest of the code is as above) where there are multiple values of a custom 'section' parameter for the mobile function 'mobile_document_view':

function prefetchOucontent(module, courseId, single, siteId) {

   var component = 'mod_oucontent';
   // Get the site, first.
   return that.CoreSitesProvider.getSite(siteId).then(function(site) {
       // Read the list of pages in this document using a web service.
       return site.read('mod_oucontent_get_page_list', {'cmid': module.id}).then(function(response) {
           var promises = [];
           // For each page, read and process the page - this is a copy of logic in the app at
           // siteplugins.ts (prefetchFunctions), but modified to add the custom argument.
           for(var i = 0; i < response.length; i++) {
               var args = {
                   courseid: courseId,
                   cmid: module.id,
                   userid: site.getUserId()
               };
               if (response[i] !== ) {
                   args.section = response[i];
               }
               promises.push(that.CoreSitePluginsProvider.getContent(
                       component, 'mobile_document_view', args).then(
                       function(result) {
                           var subPromises = [];
                           if (result.files && result.files.length) {
                               subPromises.push(that.CoreFilepoolProvider.downloadOrPrefetchFiles(
                                       site.id, result.files, true, false, component, module.id));
                           }
                           return Promise.all(subPromises);
                       }));
           }
           return Promise.all(promises);
       });
   });

}

Single activity course format

In the following example, the value of INIT_TEMPLATES["main"] is:

<core-dynamic-component [component]="componentClass" [data]="data"></core-dynamic-component>

This template is returned by the init method. And this is the JavaScript code returned by the init method: var that = this;

function getAddonSingleActivityFormatComponent() {

   function AddonSingleActivityFormatComponent() {
       this.data = {};
   };
   AddonSingleActivityFormatComponent.prototype.constructor = AddonSingleActivityFormatComponent;
   AddonSingleActivityFormatComponent.prototype.ngOnChanges = function(changes) {
       var self = this;
       if (this.course && this.sections && this.sections.length) {
           var module = this.sections[0] && this.sections[0].modules && this.sections[0].modules[0];
           if (module && !this.componentClass) {
               that.CoreCourseModuleDelegate.getMainComponent(that.Injector, this.course, module).then((component) => {
                   self.componentClass = component || that.CoreCourseUnsupportedModuleComponent;
               });
           }
           this.data.courseId = this.course.id;
           this.data.module = module;
       }
   };
   AddonSingleActivityFormatComponent.prototype.doRefresh = function(refresher, done) {
       return Promise.resolve(this.dynamicComponent.callComponentFunction("doRefresh", [refresher, done]));
   };

return AddonSingleActivityFormatComponent; };

function AddonSingleActivityFormatHandler() {

   this.name = "singleactivity";

};

AddonSingleActivityFormatHandler.prototype.constructor = AddonSingleActivityFormatHandler;

AddonSingleActivityFormatHandler.prototype.isEnabled = function() {

   return true;

};

AddonSingleActivityFormatHandler.prototype.canViewAllSections = function(course) {

   return false;

};

AddonSingleActivityFormatHandler.prototype.getCourseTitle = function(course, sections) {

   if (sections && sections[0] && sections[0].modules && sections[0].modules[0]) {
       return sections[0].modules[0].name;
   }
   return course.fullname || "";

};

AddonSingleActivityFormatHandler.prototype.displayEnableDownload = function(course) {

   return false;

};

AddonSingleActivityFormatHandler.prototype.displaySectionSelector = function(course) {

   return false;

};

AddonSingleActivityFormatHandler.prototype.getCourseFormatComponent = function(injector, course) {

   that.Injector = injector || that.Injector;
   return that.CoreCompileProvider.instantiateDynamicComponent(that.INIT_TEMPLATES["main"], getAddonSingleActivityFormatComponent(), injector);

};

this.CoreCourseFormatDelegate.registerHandler(new AddonSingleActivityFormatHandler());

Using the JavaScript API

The Javascript API is partly supported right now, only the delegates specified in the section Templates downloaded on login and rendered using JS data supports it now. This API allows you to override any of the functions of the default handler.

The “method” specified in a handler registered in the CoreUserProfileFieldDelegate will be called immediately after the init method, and the Javascript returned by this method will be run. If this Javascript code returns an object with certain functions, these function will override the ones in the default handler.

For example, if the Javascript returned by the method returns something like this:

var result = {

   getData: function(field, signup, registerAuth, formValues) {
   }

}; result;

The the getData function of the default handler will be overridden by the returned getData function.

The default handler for CoreUserProfileFieldDelegate only has 2 functions: getComponent and getData. In addition, the JavaScript code can return an extra function named componentInit that will be executed when the component returned by getComponent is initialized.

Here’s an example on how to support the text user profile field using this API:

var that = this;

var result = {

   componentInit: function() {
       if (this.field && this.edit && this.form) {
           this.field.modelName = "profile_field_" + this.field.shortname;
           if (this.field.param2) {
               this.field.maxlength = parseInt(this.field.param2, 10) || "";
           }
           this.field.inputType = that.CoreUtilsProvider.isTrueOrOne(this.field.param3) ? "password" : "text";
           var formData = {
               value: this.field.defaultdata,
               disabled: this.disabled
           };
           this.form.addControl(this.field.modelName, that.FormBuilder.control(formData, this.field.required && !this.field.locked ? that.Validators.required : null));
       }
   },
   getData: function(field, signup, registerAuth, formValues) {
       var name = "profile_field_" + field.shortname;
       return {
           type: "text",
           name: name,
           value: that.CoreTextUtilsProvider.cleanTags(formValues[name])
       };
   }

};

result;

Translate dynamic strings

If you wish to have an element that displays a localised string based on value from your template you can doing something like:

<ion-card>

   <ion-card-content translate>
       plugin.mod_myactivity.<% status %>
   </ion-card-content>

</ion-card>

This could save you from having to write something like when only one value should be displayed:

<ion-card>

   <ion-card-content>
       <%#isedting%>Template:'plugin.mod myactivity.editing'<%/isediting%>
       <%#isopen%>Template:'plugin.mod myactivity.open'<%/isopen%>
       <%#isclosed%>Template:'plugin.mod myactivity.closed'<%/isclosed%>
   </ion-card-content>

</ion-card>

Using strings with dates

If you have a string that you wish to pass a formatted date for example in the Moodle language file you have:

$string['strwithdate'] = 'This string includes a date of {$a->date} in the middle of it.';

You can localise the string correctly in your template using something like the following:

Template:'plugin.mod myactivity.strwithdate'

A Unix timestamp must be multiplied by 1000 as the Mobile App expects millisecond timestamps, where as Unix timestamps are in seconds.

Support push notification clicks

If your plugin sends push notifications to the app, you might want to open a certain page in the app when the notification is clicked. There are several ways to achieve this.

The easiest way is to include a contexturl in your notification. When the notification is clicked, the app will try to open the contexturl.

Please notice that the contexturl will also be displayed in web. If you want to use a specific URL for the app, different than the one displayed in web, you can do so by returning a customdata array that contains an appurl property:

$notification->customdata = [

   'appurl' => $myurl->out(),

];

In both cases you will have to create a link handler to treat the URL. For more info on how to create the link handler, please see how to create an advanced link handler.

If you want to do something that only happens when the notification is clicked, not when the link is clicked, you'll have to implement a push click handler yourself. The way to create it is similar to creating an advanced link handler, but you'll have to use CorePushNotificationsDelegate and your handler will have to implement the properties and functions defined in the interface CorePushNotificationsClickHandler.

Implement a module similar to mod_label

In Moodle 3.8 or higher, if your plugin doesn't support FEATURE_NO_VIEW_LINK and you don't specify a coursepagemethod then the module will only display the module description in the course page and it won't be clickable in the app, just like mod_label. You can decide if you want the module icon to be displayed or not (if you don't want it to be displayed, then don't define it in displaydata).

However, if your plugin needs to work in previous versions of Moodle or you want to display something different than the description then you need a different approach.

If your plugin wants to render something in the course page instead of just the module name and description you should specify the property coursepagemethod in the mobile.php. The template returned by this method will be rendered in the course page. Please notice the HTML returned should not contain directives or components, only default HTML.

If you don't want your module to be clickable then you just need to remove the method from mobile.php. With these 2 changes you can have a module that behaves like mod_label in the app.

Use Ionic navigation lifecycle functions

Ionic let pages define some functions that will be called when certain navigation lifecycle events happen. For more info about these functions, see this page.

You can define these functions in your plugin javascript:

this.ionViewCanLeave = function() {

   ...

};

So for example you can make your plugin ask for confirmation if the user tries to leave the page when he has some unsaved data.

Troubleshooting

Invalid response received

You might receive this error when using the "core-site-plugins-call-ws" directive or similar. By default, the app expects all WebService calls to return an object, if your WebService returns another type (string, bool, ...) then you need to specify it using the preSets attribute of the directive. For example, if your WS returns a boolean value, then you should specify it like this:

[preSets]="{typeExpected: 'boolean'}"

In a similar way, if your WebService returns null you need to tell the app not to expect any result using the preSets:

[preSets]="{responseExpected: false}"

Values of ion-radio, ion-checkbox or ion-select aren't sent to my WS

Some directives allow you to specify a form id or name to send the data from the form to a certain WS. These directives look for HTML inputs to retrieve the data to send. However, ion-radio, ion-checkbox and ion-select don't use HTML inputs, they simulate them, so the directive isn't going to find their data and so it won't be sent to the WebService.

There are 2 workarounds to fix this problem. It seems that the next major release of Ionic framework does use HTML inputs, so these are temporary solutions.

Sending the data manually

The first solution is to send the missing params manually using the "params" property. We will use ngModel to store the input value in a variable, and this variable will be passed to the params. Please notice that ngModel requires the element to have a name, so if you add ngModel to a certain element you need to add a name too.

For example, if you have a template like this:

<ion-list radio-group name="responses">

   <ion-item>
       <ion-label>First value</ion-label>
       <ion-radio value="1"></ion-radio>
   </ion-item>

</ion-list>

<button ion-button block type="submit" core-site-plugins-call-ws name="myws" [params]="{id: <% id %>}" form="myform">

   Template:'plugin.mycomponent.save'

</button>

Then you should modify it like this:

<ion-list radio-group [(ngModel)]="responses">

   <ion-item>
       <ion-label>First value</ion-label>
       <ion-radio value="1"></ion-radio>
   </ion-item>

</ion-list>

<button ion-button block type="submit" core-site-plugins-call-ws name="myws" [params]="{id: <% id %>, responses: responses}" form="myform">

   Template:'plugin.mycomponent.save'

</button>

Basically, you need to add ngModel to the affected element (in this case, the radio-group). You can put whatever name you want as the value, we used "responses". With this, everytime the user selects a radio button the value will be stored in a variable named "responses". Then, in the button we are passing this variable to the params of the WebService.

Please notice that the "form" attribute has priority over "params", so if you have an input with name="responses" it will override what you're manually passing to params.

Using a hidden input

Since the directive is looking for HTML inputs, you need to add one with the value to send to the server. You can use ngModel to synchronize your ion-radio/ion-checkbox/ion-select with the new hidden input. Please notice that ngModel requires the element to have a name, so if you add ngModel to a certain element you need to add a name too.

For example, if you have a radio button like this:

   <ion-item>
       <ion-label>First value</ion-label>
       <ion-radio value="1"></ion-radio>
   </ion-item>

Then you should modify it like this:

   <ion-item>
       <ion-label>First value</ion-label>
       <ion-radio value="1"></ion-radio>
   </ion-item>
   <ion-input type="hidden" [ngModel]="responses" name="responses"></ion-input>

In the example above, we're using a variable named "responses" to synchronize the data between the radio-group and the hidden input. You can use whatever name you want.

I can't return an object or array in otherdata

If you try to return an object or an array in any field inside otherdata, the WebService call will fail with the following error:

Scalar type expected, array or object received

Each field in otherdata must be a string, number or boolean, it cannot be an object or array. To make it work, you need to encode your object or array into a JSON string:

'otherdata' => array('data' => json_encode($data))

The app will automatically parse this JSON and convert it back into an array or object.

Examples

Accepting dynamic names in a WebService

We want to display a form where the names of the fields are dynamic, like it happens in quiz. This data will be sent to a new WebService that we have created.

The first issue we find is that the WebService needs to define the names of the parameters received, but in this case they're dynamic. The solution is to accept an array of objects with name and value. So in the _parameters() function of our new WebService, we will add this parameter:

'data' => new external_multiple_structure(

    new external_single_structure(
       array(
           'name' => new external_value(PARAM_RAW, 'data name'),
           'value' => new external_value(PARAM_RAW, 'data value'),
       )
   ),
   'The data to be saved', VALUE_DEFAULT, array()

)

Now we need to adapt our form to send the data as the WebService requires it. In our template, we have a button with the directive core-site-plugins-call-ws that will send the form data to our WebService. To make this work we will have to pass the parameters manually, without using the "form" attribute, because we need to format the data before it is sent.

Since we will send the params manually and we want it all to be sent in the same array, we will use ngModel to store the input data into a variable that we'll call "data", but you can use the name you want. This "data" will be an object that will hold the input data with the format "name->value". For example, if I have an input with name "a1" and value "My answer", the data object will be:

{a1: "My answer"}

So we need to add ngModel to all the inputs whose values need to be sent to the "data" WS param. Please notice that ngModel requires the element to have a name, so if you add ngModel to a certain element you need to add a name too. For example:

<ion-input name="<% name %>" [(ngModel)]="CONTENT_OTHERDATA.data['<% name %>']">

As you can see, we're using CONTENT_OTHERDATA to store the data. We do it like this because we'll use otherdata to initialize the form, setting the values the user has already stored. If you don't need to initialize the form, then you can use the variable "dataObject", an empty object that the Mobile app creates for you: [(ngModel)]="dataObject['<% name %>']"

The Mobile app has a function that allows you to convert this data object into an array like the one the WS expects: objectToArrayOfObjects. So in our button we'll use this function to format the data before it's sent:

<button ion-button block type="submit" core-site-plugins-call-ws name="my_ws_name"

   [params]="{id: <% id %>, data: CoreUtilsProvider.objectToArrayOfObjects(CONTENT_OTHERDATA.data, 'name', 'value')}"
   successMessage
   refreshOnSuccess="true">

As you can see in the example above, we're specifying that the keys of the "data" object need to be stored in a property named "name", and the values need to be stored in a property named "value". If your WebService expects different names you need to change the parameters of the function objectToArrayOfObjects.

If you open your plugin now in the Mobile app it will display an error in the Javascript console. The reason is that the variable "data" doesn't exist inside CONTENT_OTHERDATA. As it is explained in previous sections, CONTENT_OTHERDATA holds the data that you return in otherdata for your method. We'll use otherdata to initialize the values to be displayed in the form.

If the user hasn't answered the form yet, we can initialize the "data" object as an empty object. Please remember that we cannot return arrays or objects in otherdata, so we'll return a JSON string.

'otherdata' => array('data' => '{}')

With the code above, the form will always be empty when the user opens it. But now we want to check if the user has already answered the form and fill the form with the previous values. We will do it like this:

$userdata = get_user_responses(); // It will held the data in a format name->value. Example: array('a1' => 'My value'). ... 'otherdata' => array('data' => json_encode($userdata))

Now the user will be able to see previous values when the form is opened, and clicking the button will send the data to our WebService in array format.

Moodle plugins with mobile support

See the complete list in the plugins database here (it may contain some outdated plugins)

Mobile app support award

If you want your plugin to be awarded in the plugins directory and marked as supporting the mobile app, please feel encouraged to contact us via email mobile@moodle.com.

Don't forget to include a link to your plugin page and the location of its code repository.

See the list of awarded plugins in the plugins directory