Note:

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

Fragment

From MoodleDocs
Revision as of 07:46, 3 May 2016 by Adrian Greeve (talk | contribs) (Further awesome detail about fragments)

Introduction

fragment.js is an Asynchronous Module Definition (AMD) to allow the inclusion of rendered HTML code and associated JavaScript to be inserted through AJAX onto a page.

History

The issue for this was created to allow Moodle mforms to be changed and submitted via AJAX. Mforms currently do a lot of validation, and include accessibility code and tags. Most of Moodle uses these forms and there seemed no clear way to borrow or create another system that would satisfy all requirements.

fragment.js details

This JavaScript module is located at lib/amd/src/fragment.js

loadFragment is the exposed function to use. It takes four parameters.

  • component: The component for the callback that you will also supply. e.g. "mod_assign"
  • callback: The callback that you are calling.
  • contextid: The context ID for the component.
  • params: Parameters for the callback function.

This function returns a promise that is resolved with HTML and JavaScript.

This module will handle:

  • mforms
  • text editors
  • filters
  • fancy YUI modules such as editpdf.

Callback

The callback function needs to be located in {component}/lib.php

The function name should be in the following format - {component}_output_fragment_{callback}()

The callback function should return a string (HTML from a renderer).

example

function mod_assign_output_fragment_gradingpanel($args) {

   global $CFG;
   $context = $args['context'];
   if ($context->contextlevel != CONTEXT_MODULE) {
       return null;
   }
   require_once($CFG->dirroot . '/mod/assign/locallib.php');
   $assign = new assign($context, null, null);
   $userid = clean_param($args['userid'], PARAM_INT);
   $attemptnumber = clean_param($args['attemptnumber'], PARAM_INT);
   $formdata = array();
   if (!empty($args['jsonformdata'])) {
       $serialiseddata = json_decode($args['jsonformdata']);
       parse_str($serialiseddata, $formdata);
   }
   $viewargs = array(
       'userid' => $userid,
       'attemptnumber' => $attemptnumber,
       'formdata' => $formdata
   );
   return $assign->view('gradingpanel', $viewargs);

}