Client-Side Configuration and Moodle Context

SA
StudyAI Editorial
Reviewed by StudyAI tutors
· Published Updated

From the 123 curriculum

Client-Side Configuration and Moodle Context

TL;DR

You'll learn how Moodle uses client-side configuration, especially through M.cfg, to pass important settings from the server to your browser. This data defines what your JavaScript can do and how it interacts with the Moodle environment, specifically within different "contexts." Understanding Moodle's context system helps you write secure and efficient client-side code that adapts to where it's being used.

1. The Mental Model

Think of Moodle as a busy office building. Client-side configuration is like the building manager giving you a clipboard with instructions as you walk in: "You're in Department A (context ID 123), so you can use Printer X but not Printer Y." Moodle context is simply knowing where you are in that building – a course, an activity, the site front page – which dictates what resources and permissions are available to you.

2. The Core Material

When Moodle renders a page, it often needs to tell your browser's JavaScript about certain things. This is where M.cfg comes in. M.cfg is a global JavaScript object available on almost every Moodle page. The server fills it with useful information like the current user ID, session key, AJAX URLs, and most importantly, details about the current context.

How M.cfg Gets Populated

Close-up of two people exchanging a note, hinting at secretive communication.
Photo by RDNE Stock project on Pexels

Moodle's PHP code builds the M.cfg object. It then injects this as a <script> tag into the HTML head of the page before it's sent to your browser. You can inspect M.cfg in your browser's developer console by typing M.cfg.

Here's a simplified example of what you might see:

// This is what Moodle's PHP outputs to your HTML,
// making M.cfg available globally.
var M = M || {};
M.cfg = {
    "wwwroot": "http:\/\/localhost\/moodle",
    "sesskey": "aBcDeFgH123",
    "theme": "boost",
    "lang": "en",
    "amd": {"loadon": "body"},
    "contextid": 123, // The current context ID
    "courseid": 456,  // If we're in a course
    "cmid": 789,      // If we're in a course module
    "component": "mod_forum",
    "module": "forum",
    "userhash": "...",
    "pageid": 100,
    // ... many more properties
};

Understanding Moodle Context

Reading glasses resting on an open textbook, symbolizing study and knowledge.
Photo by Pixabay on Pexels

A context in Moodle represents a specific hierarchical level or "place" within the system. Every item in Moodle – a user, a course, an activity, a block – exists within a context. This context system is fundamental for permissions, file storage, and data isolation.

The hierarchy flows like this:

graph TD
    A["System Context (ID 1)"] --> B["Category Contexts (e.g., Cat ID 2)"]
    B --> C["Course Contexts (e.g., Course ID 123)"]
    C --> D["Module Contexts (e.g., Forum ID 456)"]
    D --> E["Block Contexts (e.g., Block ID 789)"]
    D --> F["User Contexts (e.g., User ID 10)"]

When you're writing client-side JavaScript, M.cfg.contextid tells you the most specific context ID for the current page. For example, if you're on a forum activity page, M.cfg.contextid will be the context ID of that specific forum module, not just the course. Knowing this ID is crucial when making AJAX calls that require a context, or when determining what features should be available.

Why Context Matters for Client-Side Code

A close-up of a hand holding a humorous programming sticker perfect for tech enthusiasts.
Photo by RealToughCandy.com on Pexels

  1. Permissions: Your JavaScript code might need to know if the current user has permission to perform an action (e.g., edit a post). While server-side checks are primary, M.cfg might expose basic permissions or allow you to pass the contextid to an AJAX endpoint that performs a permission check.
  2. AJAX Calls: Many Moodle AJAX endpoints require a contextid to correctly validate permissions and process data. You'll often include M.cfg.contextid in your AJAX payload.
  3. Data Scoping: Knowing the courseid or cmid (course module ID) from M.cfg helps you fetch data relevant to just that course or activity.
  4. Theming/Layout: Sometimes, you might want to apply specific client-side CSS classes or JavaScript behaviors based on the current context (e.g., "if in a quiz, hide this element").

3. Worked Example

Let's say you're developing a custom block that displays a "Mark as Complete" button for the current course module. This button should only appear if the user hasn't completed it and has permission to do so. You need to send the correct cmid and contextid to your server-side AJAX handler.

Here's how you might use M.cfg to get this information:

// Assume this script is loaded on a course module page (e.g., a Forum).

require(['jquery', 'core/ajax'], function($, Ajax) {
    $(document).ready(function() {
        // M.cfg is already available globally from Moodle's server-side output.
        var currentContextId = M.cfg.contextid;
        var currentCourseModuleId = M.cfg.cmid; // Specific to a course module page

        // Only proceed if we actually have a context and course module ID
        if (currentContextId && currentCourseModuleId) {
            // Let's say your block adds a button with ID 'mark-complete-button'
            $('#mark-complete-button').on('click', function() {
                $(this).text('Marking...').prop('disabled', true);

                Ajax.call([{
                    method: 'core_create_completion_record', // A hypothetical AJAX function
                    args: {
                        contextid: currentContextId, // IMPORTANT: Pass the context ID
                        cmid: currentCourseModuleId, // The specific activity to mark
                        state: 1 // 1 for complete
                    },
                    done: function(response) {
                        if (response.success) {
                            $('#mark-complete-button').text('Completed!').off('click').addClass('btn-success');
                            console.log('Activity marked as complete.');
                        } else {
                            $('#mark-complete-button').text('Error!').prop('disabled', false).addClass('btn-danger');
                            console.error('Failed to mark activity complete:', response.error);
                        }
                    },
                    fail: function(error) {
                        $('#mark-complete-button').text('Network Error!').prop('disabled', false).addClass('btn-danger');
                        console.error('AJAX request failed:', error);
                    }
                }]);
            });
        } else {
            console.warn('M.cfg.contextid or M.cfg.cmid not found. Cannot enable completion button.');
            // Optionally hide the button if context isn't right
            $('#mark-complete-button').hide();
        }
    });
});

In this example, M.cfg.contextid and M.cfg.cmid are directly used to form the AJAX request, ensuring that the server receives the necessary information to process the completion record correctly and securely within the proper context.

4. Key Takeaways

  • M.cfg is a global JavaScript object Moodle's server populates with vital configuration details for your client-side code.
  • Always check M.cfg for environment-specific data like wwwroot, sesskey, theme, and language.
  • M.cfg.contextid provides the ID of the current Moodle context, which is crucial for understanding permissions and data scope.
  • Moodle's context system is a hierarchy (System > Category > Course > Module/Block/User) that defines where an item sits and what resources it can access.
  • You'll frequently use M.cfg.contextid and other M.cfg properties when making AJAX calls to Moodle's server-side endpoints.
  • Client-side configuration helps your JavaScript adapt to different parts of Moodle without needing to re-fetch basic environmental data.

Common Mistakes to Avoid

Flat lay of a spiral notebook and eraser on a pastel pink background with crossed out words.
Photo by KATRIN BOLOVTSOVA on Pexels

  • Hardcoding IDs: Never hardcode context, course, or module IDs; always retrieve them from M.cfg or similar Moodle-provided data.
  • Ignoring Context: Making AJAX calls without including the relevant contextid often leads to permission errors or incorrect data processing.
  • Over-reliance on M.cfg for dynamic data: M.cfg is for initial page load configuration; for real-time dynamic data, use AJAX.
  • Assuming all M.cfg properties are always present: Properties like cmid are only available on specific page types (e.g., course module pages). Always check if a property exists before using it.

5. Now Try It

Open any Moodle course page in your browser where you have editing rights. Open your browser's developer console (usually F12). Type M.cfg and press Enter to inspect its contents. Identify the contextid, courseid, and if you navigate to a specific activity (like a Forum), find cmid. Then, make a small change to a block or activity description, and observe if any new M.cfg values appear or if existing ones update during the page refresh or AJAX call (hint: look at network requests for M.cfg data or similar data payloads).

Frequently asked about Client-Side Configuration and Moodle Context

You'll learn how Moodle uses client-side configuration, especially through M.cfg, to pass important settings from the server to your browser. Read the full notes above for the details.

Client-Side Configuration and Moodle Context is a core topic in 123. Most exam papers test it via a mix of definitions, worked examples, and applied problems. The notes above cover the high-yield sub-topics, common pitfalls, and the kind of questions examiners typically set.

Yes — every note in the StudyAI Campus Hub is free to read in full, right here on this page, with no account needed. If you clone the plan into your own dashboard, the free plan shows a preview of each note there; Basic and above unlock the full notes in your dashboard, along with practice quizzes, flashcards and offline study. You can always come back here to read the complete note for free.
Continue with
Moodle-Specific Components and Best Practices

Study this next


Get the full 123 curriculum

Clone the complete plan to your dashboard for unlimited AI-generated notes, practice quizzes, and a personalised revision schedule.

Create Free Account