### Install and Start Development Environment Source: https://moodledev.io/general/documentation/contributing Use these commands to set up your local development environment for Moodle documentation. After cloning the repository, ensure NVM is installed, then install dependencies and start the development server. ```bash nvm install npm i -g yarn yarn yarn start ``` -------------------------------- ### Install Dependencies and Start Development Server Source: https://moodledev.io/general/app/development/setup Navigate to the cloned directory, install project dependencies, and launch the application in a browser for development. This compilation can take a while. ```bash cd moodleapp ``` ```bash npm install ``` ```bash npm start ``` -------------------------------- ### Install Dependencies and Start Moodle App Source: https://moodledev.io/general/app/development/development-guide Install project dependencies using npm and start the Moodle App. This command launches the application in a browser, compatible with chromium-based browsers. ```bash npm install npm start ``` -------------------------------- ### Example xmldb_block_example_install() function Source: https://moodledev.io/docs/5.3/guides/upgrade This is an example of an install.php script for a Moodle block plugin, demonstrating the use of the `xmldb_block_example_install()` function. This function is called when the plugin is first installed. ```php blocks('side-pre'); $hasblocks = strpos($blockshtml, 'data-block=') !== false; ... $templatecontext = [ ... 'sidepreblocks' => $blockshtml, 'hasblocks' => $hasblocks, ... ]; echo $OUTPUT->render_from_template('theme_boost/columns2', $templatecontext); ``` -------------------------------- ### TinyMCE Plugin Setup Example Source: https://moodledev.io/docs/5.3/apis/plugintypes/tiny This JavaScript code demonstrates how to set up a TinyMCE plugin in Moodle. It registers a custom icon, a toolbar button, and a menu item, all of which trigger a handleAction function when clicked. It uses asynchronous operations to fetch necessary data like strings and icon HTML before returning the synchronous setup function required by TinyMCE. ```javascript import {getButtonImage} from 'editor_tiny/utils'; import {get_string as getString} from 'core/str'; import { component, startdemoButtonName, startdemoMenuItemName, icon, } from './common'; /** * Handle the action for your plugin. * @param {TinyMCE.editor} editor The tinyMCE editor instance. */ const handleAction = (editor) => { // TODO Handle the action. window.console.log(editor); }; export const getSetup = async() => { const [ startdemoButtonNameTitle, startdemoMenuItemNameTitle, buttonImage, ] = await Promise.all([ getString('button_startdemo', component), getString('menuitem_startdemo', component), getButtonImage('icon', component), ]); return (editor) => { // Register the Moodle SVG as an icon suitable for use as a TinyMCE toolbar button. editor.ui.registry.addIcon(icon, buttonImage.html); // Register the startdemo Toolbar Button. editor.ui.registry.addButton(startdemoButtonName, { icon, tooltip: startdemoButtonNameTitle, onAction: () => handleAction(editor), }); // Add the startdemo Menu Item. // This allows it to be added to a standard menu, or a context menu. editor.ui.registry.addMenuItem(startdemoMenuItemName, { icon, text: startdemoMenuItemNameTitle, onAction: () => handleAction(editor), }); }; }; ``` -------------------------------- ### Start Development Server Source: https://moodledev.io/general/documentation/installation Starts the development server for live previewing of documentation changes. Edits to markdown files will automatically reload in the browser. ```bash yarn start ``` -------------------------------- ### File Structure Example Source: https://moodledev.io/docs/5.3/apis/plugintypes/assign/feedback Example directory layout for the 'assignfeedback_file' plugin. ```text mod/assign/feedback/file ├── backup │   └── moodle2 │   ├── backup_assignfeedback_file_subplugin.class.php │   └── restore_assignfeedback_file_subplugin.class.php ├── classes │   └── privacy │   └── provider.php ├── db │   ├── access.php │   ├── install.php │   ├── install.xml │   └── upgrade.php ├── importzipform.php ├── importziplib.php ├── lang │   └── en │   └── assignfeedback_file.php ├── lib.php ├── locallib.php ├── settings.php ├── uploadzipform.php └── version.php ``` -------------------------------- ### Example: lti_get_course_content_items Source: https://moodledev.io/docs/5.3/apis/plugintypes/mod/activitymodule An example implementation of the `_get_course_content_items()` callback for the LTI plugin, demonstrating how to add LTI activities to the activity chooser. ```php function lti_get_course_content_items(string $courseid): array { $items = []; $ltiplugins = lti_get_available_plugins(true); foreach ($ltiplugins as $plugin) { $items[] = new content_item( 'lti_plugin_' . $plugin->id, $plugin->name, $plugin->description, new moodle_url('/mod/lti/intro.php', ['id' => $plugin->id]), 'mod/lti:launch' ); } return $items; } ``` -------------------------------- ### Specify Example for a Path Parameter Source: https://moodledev.io/docs/5.3/apis/subsystems/routing/parameters This snippet demonstrates how to define a path parameter with an example. It uses the `path_parameter` class and includes an instance of `\core\router\schema\example` to provide a named example for the parameter. ```php new path_parameter( name: 'themename', type: param::ALPHANUMEXT, examples: [ new \core\router\schema\example( name: 'The Boost theme', value: 'boost', ), ], ) ``` -------------------------------- ### Install Build Tools on Ubuntu Source: https://moodledev.io/general/app/development/setup/troubleshooting Run this command on Ubuntu to install necessary build tools if you encounter a 'make: not found' error. ```bash sudo apt-get install build-essential ``` -------------------------------- ### Example cURL Client Source: https://moodledev.io/general/community/plugincontribution/pluginsdirectory/api An example cURL command to fetch the list of maintained plugins from the Moodle API. ```APIDOC ## Example cURL Client ### Description This example demonstrates how to use cURL to call the `local_plugins_get_maintained_plugins` external function. ### Method POST (via cURL) ### Endpoint https://moodle.org/webservice/rest/server.php ### Parameters #### Query Parameters - **wstoken** (string) - Required - Your service access token. - **wsfunction** (string) - Required - The name of the function to call (`local_plugins_get_maintained_plugins`). - **moodlewsrestformat** (string) - Required - The desired output format (`json`). ### Request Example ```bash #!/bin/bash # Replace this with your own service access token. TOKEN="d41d8cd98f00b204e9800998ecf8427e" CURL="curl -s" ENDPOINT=https://moodle.org/webservice/rest/server.php FUNCTION=local_plugins_get_maintained_plugins ${CURL} ${ENDPOINT} --data-urlencode "wstoken=${TOKEN}" --data-urlencode "wsfunction=${FUNCTION}" \ --data-urlencode "moodlewsrestformat=json" | jq ``` ``` -------------------------------- ### Change Header Toolbar Background to Red Source: https://moodledev.io/general/app/customisation/remote-themes This CSS snippet demonstrates how to change the background color of the Moodle App's header toolbar to red using a CSS variable. This is a basic example to get started with remote theming. ```css :root { --core-header-toolbar-background: red; } ``` -------------------------------- ### Get Help Creating an Upgrade Note Source: https://moodledev.io/general/development/upgradenotes Access the full help documentation for the `create` command to understand all available options and their usage. ```bash .grunt/upgradenotes.mjs create -h ``` -------------------------------- ### Example db/upgrade.php Structure Source: https://moodledev.io/docs/5.3/guides/upgrade This example demonstrates the basic structure of the db/upgrade.php file, showing how to define upgrade functions based on the old plugin version. It includes placeholders for upgrade logic and a return statement indicating success. ```php get_manager(); // Loads ddl manager and xmldb classes. if ($oldversion < 2019031200) { // Perform the upgrade from version 2019031200 to the next version. } if ($oldversion < 2019031201) { // Perform the upgrade from version 2019031201 to the next version. } // Everything has succeeded to here. Return true. return true; } ``` -------------------------------- ### Repository Plugin lib.php Example Source: https://moodledev.io/docs/5.3/apis/plugintypes/repository This example demonstrates the structure of a lib.php file for a repository plugin. It includes defining instance-specific settings, a configuration form for those settings, global type settings, a configuration form for type settings, and a plugin initialization method. ```php . /** * Plugin functions for the repository_pluginname plugin. * * @package repository_pluginname * @copyright Year, You Name * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); require_once($CFG->dirroot . '/repository/lib.php'); class repository_flickr_public extends repository { // User specific settings. /** * Options names. * * Tell the API that the repositories have specific settings: "email address" * * @return string[] of options. */ public static function get_instance_option_names() { return ['email_address']; } /** * Repository configuration form. * * Add an "email address" text box to the create/edit repository instance Moodle form * * @param moodleform $mform Moodle form */ public static function instance_config_form($mform) { $mform->addElement( 'text', 'email_address', get_string('emailaddress', 'repository_flickr_public') ); $mform->addRule( 'email_address', get_string('required'), 'required', null, 'client' ); } // Global repository plugin settings. /** * Repository global settings names. * * We tell the API that the repositories have general settings: "api_key" * * @return string[] of options. */ public static function get_type_option_names() { return array('api_key'); } /** * Repository global settings form. * * We add an "api key" text box to the create/edit repository plugin Moodle form (also called a Repository type Moodle form) * * @param moodleform $mform Moodle form */ public function type_config_form($mform) { //the following line is needed in order to retrieve the API key value from the database when Moodle displays the edit form $api_key = get_config('flickrpublic', 'api_key'); $mform->addElement( 'text', 'api_key', get_string('apikey', 'repository_flickr_public'), ['value' => $api_key, 'size' => '40'] ); $mform->addRule( 'api_key', get_string('required'), 'required', null, 'client' ); } // Method called when the repostiroy plugin is installed. /** * Plugin init method. * * this function is only called one time, when the Moodle administrator add the Flickr Public Plugin into the Moodle site. */ public static function plugin_init() { //here we create a default repository instance. The last parameter is 1 in order to set the instance as readonly. repository::static_function( 'flickrpublic', 'create', 'flickrpublic', 0, context_system::instance(), ['name' => 'default instance', 'email_address' => null], 1 ); } } ``` -------------------------------- ### PHP Inline Comment Style - Incorrect Examples Source: https://moodledev.io/general/development/policies/codingstyle Examples of incorrect inline commenting styles, including block comments and comments not starting with a capital letter or ending with proper punctuation. ```php /* Comment explaining this piece of code. */ # Comment explaining this piece of code. // comment explaining this piece of code (without capital letter and punctuation) ``` -------------------------------- ### Get Course Custom Field Metadata Example Source: https://moodledev.io/docs/5.3/apis/core/customfields Example function to retrieve all custom fields for a given course ID and format them into a metadata array. It filters out fields with empty values. ```php function get_course_metadata($courseid) { $handler = \core_customfield\handler::get_handler('core_course', 'course'); // This is equivalent to the line above. //$handler = \core_course\customfield\course_handler::create(); $datas = $handler->get_instance_data($courseid); $metadata = []; foreach ($datas as $data) { if (empty($data->get_value())) { continue; } $cat = $data->get_field()->get_category()->get('name'); $metadata[$data->get_field()->get('shortname')] = $cat . ': ' . $data->get_value(); } return $metadata; } ``` -------------------------------- ### Create Moodle Instance with PostgreSQL Source: https://moodledev.io/general/development/tools/mdk Use this command to create a new Moodle instance with PostgreSQL, set it up for development, and create user accounts. ```bash mdk create -i -v 24 -e pgsql -r dev users ``` ```bash mdk create --install --version 24 --engine pgsql --run dev users ``` -------------------------------- ### Dispatching a Hook During Plugin Installation Source: https://moodledev.io/docs/5.3/apis/core/hooks Dispatch a custom hook after the plugin's XMLDB installation process is complete. This example shows how to instantiate the `installation_finished` hook and dispatch it using the core hook manager. ```php dispatch($hook); } ``` -------------------------------- ### Frontend Source Structure Example Source: https://moodledev.io/docs/5.3/guides/frontend This illustrates the recommended directory structure for frontend source code within a Moodle component. ```bash ├── component │ └── js │ └── esm │ └── src ``` -------------------------------- ### Get Specific Package Status Source: https://moodledev.io/general/development/tools/composer Check the installation and version status of a specific Composer package using its name. ```php $package = $composer->get_package_status('composer/installers'); if (!$package->installed) { echo 'Package is not installed.'; } if (!$package->current) { echo 'Package is not up to date.'; } echo "Required version: {$package->requiredversion}"; echo "Installed version: {$package->installedversion}"; ``` -------------------------------- ### Atto Plugin Directory Layout Example Source: https://moodledev.io/docs/5.3/apis/plugintypes/atto Illustrates the typical file and directory structure for an Atto plugin, such as `atto_media`. This helps in understanding where different plugin components should be placed. ```text lib/editor/atto/plugins/media |-- db | └-- upgrade.php |-- lang | └-- en | └-- atto_media.php |-- yui | └-- src | └-- button | └-- atto_media.php | ├── build.json | ├── js | │   └-- button.js | └── meta | └-- button.json |-- settings.php └-- version.php ``` -------------------------------- ### PHP Example: Enrol a user using a manual enrolment plugin Source: https://moodledev.io/docs/5.3/apis/subsystems/enrol Shows how to retrieve a specific enrolment plugin instance (e.g., manual) and then use its enrol_user method to enrol a user. Requires fetching the enrolment instance record first. ```php $instance = $DB->get_record('enrol', ['courseid' => $course->id, 'enrol' => 'manual']); $enrolplugin = enrol_get_plugin($instance->enrol); $enrolplugin->enrol_user($instance, $user->id, $role->id, $timestart, $timeend); ``` -------------------------------- ### Render a Widget in a Page Context Source: https://moodledev.io/docs/5.3/guides/templates Example of how to get a renderer for a specific plugin and use it to render a widget within a Moodle page. ```php $output = $PAGE->get_renderer('tool_myplugin'); echo $output->render($widget); ``` -------------------------------- ### Retrieve Overall Composer Status Source: https://moodledev.io/general/development/tools/composer Get the overall Composer runtime status, including whether dependencies are installed and if all packages are up to date. ```php $status = $composer->get_status(); if (!$status->installed) { echo 'Composer dependencies are not installed.'; } else if (!$status->current) { echo 'One or more Composer packages require attention.'; } ``` -------------------------------- ### Create a New Moodle Development Site Source: https://moodledev.io/docs/5.3/guides/composer Use this command to quickly set up a new Moodle site with Composer, ideal for reproducible development environments. ```bash composer create-project moodle/seed [yourlocation] ``` -------------------------------- ### Example Behat Test Scenario Source: https://moodledev.io/general/development/tools/behat/writing Demonstrates a typical Behat test scenario using Given, When, Then, And, and But steps with data tables for setup. ```gherkin Given the following user exists: | username | ccolon | | First name | Colin | | Last name | Colon | | email | ccolon@example.com | And the following course exists: | Name | Jump Judging (Level 1) | | Shortname | sjea1 | When I log in as "ccolon" And I navigate to "Site home > Jump Judging (Level 1)" Then I should see "You are not enrolled in this course" But I should see "Enrol now" ``` -------------------------------- ### Install Windows Build Tools Source: https://moodledev.io/general/app/development/setup On Windows, run this command as administrator to install native build tools required by `node-gyp`. This process can take a significant amount of time. ```bash npm install --global --production windows-build-tools ``` -------------------------------- ### Install Watchman from Source Source: https://moodledev.io/general/development/tools/nodejs Steps to clone, build, and install Watchman from its source code. This is useful if you encounter errors with 'grunt watch' due to missing Watchman. ```bash $ git clone https://github.com/facebook/watchman.git -b v4.9.0 --depth 1 $ cd watchman $ ./autogen.sh $ ./configure $ make $ sudo make install ``` -------------------------------- ### Get Default Condition Values Source: https://moodledev.io/docs/5.3/apis/core/reportbuilder Optionally defines the initial values for default conditions. This method overrides the default setup for specific conditions. ```php /** * Return the condition values that will be set for the report upon creation * * @return array */ public function get_default_condition_values(): array { return [ 'task_log:type_operator' => select::EQUAL_TO, 'task_log:type_value' => \core\task\database_logger::TYPE_SCHEDULED, ]; } ``` -------------------------------- ### Mustache Template for Mobile View Source: https://moodledev.io/general/app/development/plugins-development-guide/examples/course-modules A basic Mustache template structure for rendering the mobile view of the course module. This example shows the start of a div element. ```mustache {{=<% %>=}}
``` -------------------------------- ### Create a repository instance Source: https://moodledev.io/docs/5.3/guides/testing Create a repository instance using the provided type, record, and options. ```php $this->getDataGenerator()->create_repository($type, $record, $options); ``` -------------------------------- ### Example Hook Callback Method Source: https://moodledev.io/docs/5.3/apis/core/hooks Defines a static method within a class that will be registered as a hook callback. Includes checks for initial installation and plugin configuration. ```php id = $id; $test = new condition_info($cm, CONDITION_MISSING_EVERYTHING); $fullcm = $test->get_full_course_module(); ``` -------------------------------- ### Get Record with Multiple Conditions Source: https://moodledev.io/docs/5.3/apis/core/dml Example of retrieving a user record based on multiple conditions (firstname and lastname) using an associative array. Conditions are combined with AND. ```php $user = $DB->get_record('user', ['firstname' => 'Martin', 'lastname' => 'Dougiamas']); ``` -------------------------------- ### PHP Example: Get users able to submit an assignment Source: https://moodledev.io/docs/5.3/apis/subsystems/enrol Demonstrates using get_enrolled_users to find all users within a context who possess the 'mod/assign:submit' capability. ```php $submissioncandidates = get_enrolled_users($modcontext, 'mod/assign:submit'); ``` -------------------------------- ### Theme Language File Example (theme_boost) Source: https://moodledev.io/docs/5.3/apis/plugintypes/theme This is an example of a language file for the Boost theme, demonstrating how to define plugin name, readme text, and configuration titles. ```php . /** * Languages configuration for the theme_boost plugin. * * @package theme_boost * @copyright Year, You Name * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ $string['pluginname'] = 'Boost'; $string['choosereadme'] = 'Boost is a modern, highly-customisable theme. This theme is intended to be used directly, or as a parent theme when creating new themes utilising Bootstrap 4.'; $string['configtitle'] = 'Boost'; ``` -------------------------------- ### Node-Sass Installation Error Source: https://moodledev.io/general/development/tools/nodejs This is a typical error message when the node-sass module fails to compile on macOS due to incomplete or outdated Xcode build system setup. ```bash npm ERR! code 1 npm ERR! path /Users/jun/Work/moodles/integration_master/moodle/node_modules/node-sass npm ERR! command failed npm ERR! command sh /var/folders/87/fnlrch612m5d40trk64lrd480000gn/T/postinstall-a2316f45.sh npm ERR! Building: /Users/jun/.nvm/versions/node/v16.17.0/bin/node /Users/jun/Work/moodles/integration_master/moodle/node_modules/node-gyp/bin/node-gyp.js rebuild --verbose --libsass_ext= --libsass_cflags= --libsass_ldflags= --libsass_library= npm ERR! make: Entering directory '/Users/jun/Work/moodles/integration_master/moodle/node_modules/node-sass/build' ``` -------------------------------- ### Create Upgrade Note with Pre-filled Options Source: https://moodledev.io/general/development/upgradenotes Provide options to the `create` command to pre-fill information such as the issue ID, component, type, and a short description. ```bash .grunt/upgradenotes.mjs create \ -i MDL-99999 \ -c core_communication \ -t improved \ -m "Added a new option to call the speaking clock" ``` -------------------------------- ### Example Language File for format_pluginname Source: https://moodledev.io/docs/5.3/apis/plugintypes/format Provides a complete example of a language file for a Moodle format plugin, including standard Moodle header, copyright, license, and various language strings. ```php . /** * Languages configuration for the format_pluginname plugin. * * @package format_pluginname * @copyright Year, You Name * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ $string['addsections'] = 'Add section'; $string['currentsection'] = 'This section'; $string['deletesection'] = 'Delete section'; $string['editsection'] = 'Edit section'; $string['editsectionname'] = 'Edit section name'; $string['hidefromothers'] = 'Hide section'; $string['newsectionname'] = 'New name for section {$a}'; $string['pluginname'] = 'pluginname format'; $string['privacy:metadata'] = 'The Sample format plugin does not store any personal data.'; $string['sectionname'] = 'Section'; $string['showfromothers'] = 'Show section'; ``` -------------------------------- ### Define Placement Admin Settings Source: https://moodledev.io/docs/5.3/apis/plugintypes/ai/placement Create a new admin settings page for a placement plugin using the admin_settingspage_provider class. This example shows the setup for 'aiplacement_courseassist'. ```php use core_ai\admin\admin_settingspage_provider; if ($hassiteconfig) { // Placement specific settings heading. $settings = new admin_settingspage_provider( 'aiplacement_courseassist', new lang_string('pluginname', 'aiplacement_courseassist'), 'moodle/site:config', true, ); ... ``` -------------------------------- ### Example Service Module Structure Source: https://moodledev.io/docs/5.3/guides/frontend Illustrates the recommended directory structure for service modules, separating API logic from UI components. ```directory services/ └── courses.ts ``` -------------------------------- ### Get Record with Named Placeholders Source: https://moodledev.io/docs/5.3/apis/core/dml Example of using named placeholders (:firstname, :lastname) in SQL queries for secure parameter binding. Parameters are provided in an associative array. ```php $DB->get_record_sql( 'SELECT * FROM {user} WHERE firstname = :firstname AND lastname = :lastname', [ 'firstname' => 'Martin', 'lastname' => 'Dougiamas', ] ); ``` -------------------------------- ### Get Record with Question Mark Placeholders Source: https://moodledev.io/docs/5.3/apis/core/dml Example of using question mark placeholders (?) in SQL queries for secure parameter binding. The parameters are provided in an indexed array. ```php $DB->get_record_sql( 'SELECT * FROM {user} WHERE firstname = ? AND lastname = ?', [ 'Martin', 'Dougiamas', ] ); ``` -------------------------------- ### Manual Moodle Instance Upgrade Source: https://moodledev.io/general/development/tools/mdk This demonstrates the manual steps equivalent to 'mdk upgrade', involving checking out the stable branch, fetching, resetting, and running the upgrade script. ```bash # For each instance of Moodle... cd /dir/to/stable_24/moodle git checkout MOODLE_24_STABLE git fetch origin git reset --hard origin/MOODLE_24_STABLE php admin/cli/upgrade.php --non-interactive --allow-unstable ``` -------------------------------- ### Get Record Without Table Prefix Source: https://moodledev.io/docs/5.3/apis/core/dml Example of retrieving a record from the 'user' table without explicitly using the table prefix. The API handles prefixing automatically. ```php $user = $DB->get_record('user', ['id' => '1']); ``` -------------------------------- ### Example: Using Delegated Transactions Source: https://moodledev.io/docs/5.3/apis/core/dml Demonstrates a typical use case for delegated transactions, including starting, performing operations, allowing commit on success, and rolling back on exception. ```php global $DB; try { $transaction = $DB->start_delegated_transaction(); $DB->insert_record('foo', $object); $DB->insert_record('bar', $otherobject); // Assuming the both inserts work, we get to the following line. $transaction->allow_commit(); } catch (Exception $e) { $transaction->rollback($e); } ``` -------------------------------- ### Get Record Using Custom SQL with Table Prefix Source: https://moodledev.io/docs/5.3/apis/core/dml Example of using custom SQL with table names enclosed in curly braces, which are automatically converted to prefixed table names. ```php $user = $DB->get_record_sql('SELECT COUNT(*) FROM {user} WHERE deleted = 1 OR suspended = 1;'); ``` -------------------------------- ### Build and Serve Docs Locally Source: https://moodledev.io/general/documentation/installation Builds the documentation and serves it locally. This is typically used for developing or testing the build process. ```bash yarn build yarn serve ``` -------------------------------- ### Get Tag Cloud for Collection Source: https://moodledev.io/docs/5.3/apis/subsystems/tag Retrieves all tags within a specific tag collection to display them, for example, as a tag cloud. This method is used to access tags managed by a custom tag area. ```php tag_collection::get_tag_cloud() ``` -------------------------------- ### Initialize Behat for Moodle Source: https://moodledev.io/general/development/tools/behat/running Run this command from your Moodle root directory to initialize Behat. It installs dependencies, sets up a new Moodle site, and configures Behat. ```bash php admin/tool/behat/cli/init.php ``` -------------------------------- ### Get Table Alias Example Source: https://moodledev.io/docs/5.3/apis/core/reportbuilder Demonstrates how to retrieve table aliases for use in SQL queries within entities. This ensures compatibility with report configurations that may alter default table aliases. ```php $logalias = $this->get_table_alias('logstore_standard_log'); $useralias = $this->get_table_alias('user'); $fildname = "{$useralias}.lastname"; $join = "JOIN {user} {$useralias} ON {$useralias}.id = {$logalias}.relateduser" ``` -------------------------------- ### Get Help for Migration Assistant Source: https://moodledev.io/general/documentation/contributing Run this command to view the help documentation for the Moodle documentation migration assistant. This tool helps automate the migration of legacy documentation to the new Markdown format. ```bash yarn migrate --help ``` -------------------------------- ### Initialize Behat for All Themes Source: https://moodledev.io/general/development/tools/behat/running Run this command to prepare Behat for testing across all installed themes. This is a prerequisite for running Behat with a specified theme. ```php php admin/tool/behat/cli/init.php --add-core-features-to-theme ``` -------------------------------- ### Behat Scenario Example Source: https://moodledev.io/general/development/tools/behat A single scenario demonstrating the Given, When, and Then steps for logging in as an existing user. ```gherkin Scenario: Login as an existing user Given I am on "login/index.php" When I fill in "username" with "admin" And I fill in "password" with "admin" And I press "loginbtn" Then I should see "Moodle 101: Course Name" ``` -------------------------------- ### Get Moodle Plugin Types Source: https://moodledev.io/docs/5.3/apis/plugintypes This script retrieves and displays a list of all plugin types known to your Moodle installation, along with their plural names and directory paths. It requires Moodle's configuration to be loaded. ```php get_plugin_types() as $type => $dir) { $dir = substr($dir, strlen($CFG->dirroot)); printf( "%-20s %-50s %s" . PHP_EOL, $type, $pluginman->plugintype_name_plural($type), $dir) ; } ``` -------------------------------- ### Example State Action Implementation (Topics Format) Source: https://moodledev.io/docs/5.3/apis/plugintypes/format Illustrates how the topics format plugin extends the core state actions class to add custom actions like section highlighting. ```php class format_topics\courseformat\stateactions extends \core_courseformat\stateactions { // ... implementation for section_highlight and section_unhighlight ... } ``` -------------------------------- ### Get File Listing Example Source: https://moodledev.io/docs/5.3/apis/plugintypes/repository Implement this method to return a list of files and directories for display in the file picker. It must return an array containing file details like title, date, size, and source, as well as directory information. ```php /** * Get file listing. * * This is a mandatory method for any repository. * * See repository::get_listing() for details. * * @param string $encodedpath * @param string $page * @return array the list of files, including meta information */ public function get_listing($encodedpath = '', $page = '') { // This methods return [ //this will be used to build navigation bar. 'path'=>[ [ 'name'=>'root' 'path'=>'/' ], [ 'name'=>'subfolder', 'path'=>'/subfolder' ], ], 'manage'=>'http://webmgr.moodle.com', 'list'=> [ [ 'title'=>'filename1', 'date'=>'1340002147', 'size'=>'10451213', 'source'=>'http://www.moodle.com/dl.rar', ], [ 'title'=>'folder', 'date'=>'1340002147', 'size'=>'0', 'children'=>[], ], ], ]; } ``` -------------------------------- ### Test Default Datasource Functionality Source: https://moodledev.io/docs/5.3/apis/core/reportbuilder Tests the default setup of a datasource, ensuring it returns the expected number of rows and that the data is ordered and formatted correctly. This example demonstrates adding a category and course to Moodle to test course count functionality. ```php /** * Test default datasource */ public function test_datasource_default(): void { $this->resetAfterTest(); $category = $this->getDataGenerator()->create_category(['name' => 'Zoo', 'idnumber' => 'Z01']); $course = $this->getDataGenerator()->create_course(['category' => $category->id]); /** @var core_reportbuilder_generator $generator */ $generator = $this->getDataGenerator()->get_plugin_generator('core_reportbuilder'); $report = $generator->create_report(['name' => 'My report', 'source' => categories::class, 'default' => 1]); $content = $this->get_custom_report_content($report->get('id')); $this->assertCount(2, $content); // Default columns are name, idnumber, coursecount. Sorted by name ascending. $this->assertEquals([ [get_string('defaultcategoryname'), '', 0], [$category->get_formatted_name(), $category->idnumber, 1], ], array_map('array_values', $content)); } ``` -------------------------------- ### Complete Feature File Example Source: https://moodledev.io/general/app/development/testing/acceptance-testing A full Behat feature file demonstrating how to load the app, log in, navigate to a course, and assert the course page is displayed. Requires the app and JavaScript to be enabled. ```gherkin @app @javascript Feature: Test app (demo) In order to test something in the app As a developer I need for this test script to run the app Background: Given the following "courses" exist: | fullname | shortname | | Course 1 | C1 | And the following "users" exist: | username | | student | And the following "course enrolments" exist: | user | course | role | | student | C1 | student | Scenario: Try going into the course When I enter the app And I log in as "student" And I press "Course 1" near "Course overview" in the app Then the header should be "Course 1" in the app ```