Note:

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

Blocks: Difference between revisions

From MoodleDocs
(Added after_install and before_delete methods to appendix. Noted when methods were first introduced.)
m (Protected "Blocks": Developer Docs Migration ([Edit=Allow only administrators] (indefinite)))
 
(208 intermediate revisions by 55 users not shown)
Line 1: Line 1:
{{Template:Migrated|newDocId=/docs/apis/plugintypes/blocks}}
''' A Step-by-step Guide To Creating Blocks '''
''' A Step-by-step Guide To Creating Blocks '''


Original Author: Jon Papaioannou (pj@moodle.org)
Original Author: Jon Papaioannou ([mailto:pj@moodle.org pj@moodle.org])


The present document serves as a guide to developers who want to create their own blocks for use in Moodle. It applies to the 1.5 development version of Moodle (and any newer) '''only''', as the blocks subsystem was rewritten and expanded for the 1.5 release. However, you can also find it useful if you want to modify blocks written for Moodle 1.3 and 1.4 to work with the latest versions (look at [[Blocks_Howto#appendix_b| Appendix B]]).
Updated to Moodle 2.0 and above by: Greg J Preece ([mailto:greg.preece@blackboard.com greg.preece@blackboard.com])
The guide is written as an interactive course which aims to develop a configurable, multi-purpose block that displays arbitrary HTML. It's targeted mainly at people with little experience with Moodle or programming in general and aims to show how easy it is to create new blocks for Moodle. A certain small amount of PHP programming knowledge is still required, though. Experienced developers and those who just want a reference text should refer to [[Blocks_Howto#appendix_a| Appendix A]] because the main guide has a rather low concentration of pure information in the text.
 
{{Moodle 2.0}}
 
The present document serves as a guide to developers who want to create their own blocks for use in Moodle. It applies to the 2.0 development version of Moodle (and any newer) '''only''', as the blocks API changed significantly enough to warrant new documentation. Those wishing to read the old tutorial for Moodles 1.5 to 1.9 can find it under [[Blocks/Blocks for 1.5 to 1.9| Blocks for 1.5 to 1.9]].
 
The guide is written as an interactive course which aims to develop a configurable, multi-purpose block that displays arbitrary HTML. It's targeted mainly at people with little experience with Moodle or programming in general and aims to show how easy it is to create new blocks for Moodle. A certain small amount of PHP programming knowledge is still required, though.  
 
Experienced developers and those who just want a '''programmer's reference''' text should refer to [[Blocks/Appendix_A| Appendix A]] because the main guide has a rather low concentration of pure information in the text.


== Basic Concepts ==
== Basic Concepts ==
Through this guide, we will be following the creation of an "HTML" block from scratch in order to demonstrate most of the block features at our disposal. Our block will be named "SimpleHTML". This does not constrain us regarding the name of the actual directory on the server where the files for our block will be stored, but for consistency we will follow the practice of using the lowercased form "simplehtml" in any case where such a name is required. Whenever we refer to a file or directory name which contains "simplehtml", it's important to remember that ''only'' the "simplehtml" part is up to us to change; the rest is standardized and essential for Moodle to work correctly.
 
Through this guide, we will be following the creation of an "HTML" block from scratch in order to demonstrate most of the block features at our disposal. Our block will be named "SimpleHTML". This does not constrain us regarding the name of the actual directory on the server where the files for our block will be stored, but for consistency we will follow the practice of using the lowercased form "simplehtml" in any case where such a name is required.  
 
Whenever we refer to a file or directory name which contains "simplehtml", it's important to remember that ''only'' the "simplehtml" part is up to us to change; the rest is standardised and essential for Moodle to work correctly.
 
Whenever a file's path is mentioned in this guide, it will always start with a slash. This refers to the Moodle home directory; all files and directories will be referred to with respect to that directory.
Whenever a file's path is mentioned in this guide, it will always start with a slash. This refers to the Moodle home directory; all files and directories will be referred to with respect to that directory.


== Ready, Set, Go! ==
== Ready, Set, Go! ==
To define a "block" in Moodle, in the most basic case we need to provide just one source code file. We start by creating the directory <span class="filename">/blocks/simplehtml/</span> and creating a file named <span class="filename">/blocks/simplehtml/block_simplehtml.php</span> which will hold our code. We then begin coding the block:
    <?php
    class block_simplehtml extends block_base {
    function init() {
        $this->title = get_string('simplehtml', 'block_simplehtml');
        $this->version = 2004111200;
    }


The first line is our block class definition; it must be named exactly in the manner shown. Again, only the "simplehtml" part can (and indeed must) change; everything else is standardized.
To define a "block" in Moodle, in the most basic case we need to provide just four PHP files. Remember, in this example we are creating a block called 'simplehtml', replace 'simplehtml' with the name of your custom block. The four files should be located in blocks/simplehtml and are:
Our class is then given a small method: [[Blocks_Howto#method_init| init]]. This is essential for all blocks, and its purpose is to set the two class member variables listed inside it. But what do these values actually mean? Here's a more detailed description.
 
[[Blocks_Howto#variable_title| $this->title]] is the title displayed in the header of our block. We can set it to whatever we like; in this case it's set to read the actual title from a language file we are presumably distributing together with the block. I 'll skip ahead a bit here and say that if you want your block to display '''no''' title at all, then you should set this to any descriptive value you want (but '''not''' make it an empty string). We will later see [[Blocks_Howto#section_eye_candy| how to disable the title's display]].
=== block_simplehtml.php ===
[[Blocks_Howto#variable_version| $this->version]] is the version of our block. This actually would only make a difference if your block wanted to keep its own data in special tables in the database (i.e. for very complex blocks). In that case the version number is used exactly as it's used in activities; an upgrade script uses it to incrementally upgrade an "old" version of the block's data to the latest. We will outline this process further ahead, since blocks tend to be relatively simple and not hold their own private data. In our example,
 
this is certainly the case so we just set [[Blocks_Howto#variable_version| $this->version]] to '''YYYYMMDD00''' and forget about it.
This file will hold the class definition for the block, and is used both to manage it as a plugin and to render it onscreen.
'''UPDATING:''' Prior to version 1.5, the basic structure of each block class was slightly different. Refer to [[Blocks_Howto#appendix_b| Appendix B]] for more information on the changes that old blocks have to make to conform to the new standard.
 
We start by creating the main object file, 'block_simplehtml.php'. We then begin coding the block:
 
<syntaxhighlight lang="php">
<?php
class block_simplehtml extends block_base {
    public function init() {
        $this->title = get_string('simplehtml', 'block_simplehtml');
    }
    // The PHP tag and the curly bracket for the class definition
    // will only be closed after there is another function added in the next section.
}
</syntaxhighlight>
 
The first line is our block class definition; it must be named exactly in the manner shown. Again, only the "simplehtml" part can (and indeed must) change; everything else is standardised.
 
Our class is then given a small method: [[Blocks/Appendix_A#init.28.29| init()]]. This is essential for all blocks, and its purpose is to give values to any class member variables that need instantiating.  
 
In this very basic example, we only want to set [[Blocks/Appendix_A#.24this-.3Etitle| $this->title]], which is the title displayed in the header of our block. We can set it to whatever we like; in this case it's set to read the actual title from the language file mentioned below, which is then distributed along with the block. I'll skip ahead a bit here and say that if you want your block to display '''no''' title at all, then you should set this to any descriptive value you want (but '''not''' make it an empty string). We will later see [[Blocks#Eye_Candy|how to disable the title's display]].
 
=== db/access.php ===
 
This file will hold the new capabilities created by the block.
 
Moodle 2.4 onwards introduced the capabilities addinstance and myaddinstance for core blocks. They were introduced so that it was possible to control the use of individual blocks. These capabilities should also be added to your custom block, so in this case to the file blocks/simplehtml/db/access.php. If your block is not going to be used in the 'My Moodle page' (ie, your applicable_formats function (discussed later) has 'my' set to false.) then the myaddinstance capability does not need to be given to any user, but it must still be defined here otherwise you will get errors on certain pages. The following is the capabilities array and how it should look for any new blocks.
 
<syntaxhighlight lang="php">
<?php
    $capabilities = array(
 
    'block/simplehtml:myaddinstance' => array(
        'captype' => 'write',
        'contextlevel' => CONTEXT_SYSTEM,
        'archetypes' => array(
            'user' => CAP_ALLOW
        ),
 
        'clonepermissionsfrom' => 'moodle/my:manageblocks'
    ),
 
    'block/simplehtml:addinstance' => array(
        'riskbitmask' => RISK_SPAM | RISK_XSS,
 
        'captype' => 'write',
        'contextlevel' => CONTEXT_BLOCK,
        'archetypes' => array(
            'editingteacher' => CAP_ALLOW,
            'manager' => CAP_ALLOW
        ),
 
        'clonepermissionsfrom' => 'moodle/site:manageblocks'
    ),
);
</syntaxhighlight>
 
=== lang/en/block_simplehtml.php ===
 
This is the English language file for your block. If you are not an English speaker, you can replace 'en' with your appropriate language code (but even then you will need english folder !). All language files for blocks go under the /lang subfolder of the block's installation folder.
 
Moodle 2.0 and above require a name for our plugin to show in the upgrading page. We set this value, along with the capabilities we created and any other language strings we wish to use within the block, in a language package as previously mentioned (the same file where we put our string for the plugin title).
 
The capabilities added above need descriptions for pages that allow setting of capabilities. These should also be added to the language file.
 
<syntaxhighlight lang="php">
<?php
$string['pluginname'] = 'Simple HTML block';
$string['simplehtml'] = 'Simple HTML';
$string['simplehtml:addinstance'] = 'Add a new simple HTML block';
$string['simplehtml:myaddinstance'] = 'Add a new simple HTML block to the My Moodle page';
</syntaxhighlight>
 
=== version.php ===
 
This file will hold version information for the plugin, along '''with other advanced parameters''' (not covered here - see [[version.php]] if you want '''more details''').
 
Prior to Moodle 2.0, version details for blocks were stored as class fields; as of Moodle 2.0 these are stored in a file called version.php, stored under ''/blocks/simplehtml/'''version.php'''''. The version file is very simple indeed, containing only a few field definitions, depending on your needs. Here is an example:
<syntaxhighlight lang="php">
<?php
$plugin->component = 'block_simplehtml';  // Recommended since 2.0.2 (MDL-26035). Required since 3.0 (MDL-48494)
$plugin->version = 2011062800;  // YYYYMMDDHH (year, month, day, 24-hr time)
$plugin->requires = 2010112400; // YYYYMMDDHH (This is the release version for Moodle 2.0)
</syntaxhighlight>
 
This file contains object field definitions that denote the full [[Frankenstyle|frankenstyle]] component name in the form of ''plugintype_pluginname'' and the version number of the block, along with the minimum version of Moodle that must be installed in order to use it. Please note that the object being used here is ''always'' called '''$plugin''', and that you do not need to create this object yourself within the version file. Note also we don't include a closing "?>" tag. This is intentional, and a [[Coding_style#PHP_tags | workaround for whitespace issues]].
 
The exact Moodle version of a release can be found in [[Releases]].
 
 
{{Top}}


== I Just Hear Static ==
== I Just Hear Static ==
In order to get our block to actually display something on screen, we need to add one more method to our class (before the final closing brace in our file). The new code is:
In order to get our block to actually display something on screen, we need to add one more method to our class (before the final closing brace in our file) inside of the block_simplehtml.php script. The new code is:
  function get_content() {
 
    if ($this->content !== NULL) {
<syntaxhighlight lang="php">  
        return $this->content;
  public function get_content() {
    }
    if ($this->content !== null) {
      return $this->content;
    }
 
    $this->content        =  new stdClass;
    $this->content->text  = 'The content of our SimpleHTML block!';
    $this->content->footer = 'Footer here...';
   
   
    $this->content = new stdClass;
    return $this->content;
    $this->content->text = 'The content of our SimpleHTML block!';
}
    $this->content->footer = 'Footer here...';
 
</syntaxhighlight>
    return $this->content;
 
}
'''Add your block to the front page!'''
}
Don't forget (especially if you're a new Moodle user) to add your block to the front page. Turn Editing On, and add your block to the page.
?>
 
It can't get any simpler than that, can it? Let's dissect this method to see what's going on...
It can't get any simpler than that, can it? Let's dissect this method to see what's going on...
First of all, there is a check that returns the current value of [[Blocks_Howto#variable_content| $this->content]] if it's not NULL; otherwise we proceed with "computing" it. Since the computation is potentially a time-consuming operation and it '''will''' be called several times for each block (Moodle works that way internally), we take a precaution and include this time-saver.
 
First of all, there is a check that returns the current value of [[Blocks/Appendix_A#.24this-.3Econtent| $this->content]] if it's not NULL; otherwise we proceed with "computing" it. Since the computation is potentially a time-consuming operation and it '''will''' be called several times for each block (Moodle works that way internally), we take a precaution and include this time-saver.
Supposing the content had not been computed before (it was NULL), we then define it from scratch. The code speaks for itself there, so there isn't much to say. Just keep in mind that we can use HTML both in the text '''and''' in the footer, if we want to.
Supposing the content had not been computed before (it was NULL), we then define it from scratch. The code speaks for itself there, so there isn't much to say. Just keep in mind that we can use HTML both in the text '''and''' in the footer, if we want to.
At this point our block should be capable of being automatically installed in Moodle and added to courses; visit your administration page to install it and after seeing it in action come back to continue our tutorial.
 
It's worth mentioning that this is not the only type of content a block can output. You can also create lists and hierarchical trees, which are better suited for certain types of output, such as menus. These different content types have an impact on the content object and how it is constructed. For more information, see [[Blocks/Appendix A#.24this-.3Econtent_type|Appendix A]]
 
At this point our block should be capable of being automatically installed in Moodle and added to courses; visit your administration page to install it (Click "Notifications" under the Site Administration Block) and after seeing it in action come back to continue our tutorial.


== Configure That Out ==
== Configure That Out ==
The current version of our block doesn't really do much; it just displays a fixed message, which is not very useful. What we 'd really like to do is allow the teachers to customize what goes into the block. This, in block-speak, is called "instance configuration". So let's give our block some instance configuration...
 
First of all, we need to tell Moodle that we want it to provide instance-specific configuration amenities to our block. That's as simple as adding one more method to our block class:
The current version of our block doesn't really do much; it just displays a fixed message, which is not very useful. What we'd really like to do is allow the teachers to customize what goes into the block. This, in block-speak, is called "instance configuration". Basic instance configuration is automatic in Moodle 2.0; if you put any page with blocks on it into "editing mode", you will notice that each block has an edit button in its title bar. Clicking on this will take you to the block configuration form. The settings that Moodle adds to this form by default relate to the block's appearance and position on Moodle pages.  
function instance_allow_config() {
 
    return true;
We can extend this configuration form, and add custom preferences fields, so that users can better tailor our block to a given task or page. To extend the configuration form, create the file <span class="filename">/blocks/simplehtml/'''edit_form.php'''</span>, and fill it with the following code:
}
 
This small change is enough to make Moodle display an "Edit..." icon in our block's header when we turn editing mode on in any course. However, if you try to click on that icon you will be presented with a notice that complains about the block's configuration not being implemented correctly. Try it, it's harmless.
<syntaxhighlight lang="php">
Moodle's complaints do make sense. We told it that we want to have configuration, but we didn't say ''what'' kind of configuration we want, or how it should be displayed. To do that, we need to create one more file: <span class="filename">/blocks/simplehtml/config_instance.html</span> (which has to be named exactly like that). For the moment, copy paste the following into it and save:
<?php
<nowiki>
 
<table cellpadding="9" cellspacing="0">
class block_simplehtml_edit_form extends block_edit_form {
<tr valign="top">
       
    <td align="right">
    protected function specific_definition($mform) {
        <?php print_string('configcontent', 'block_simplehtml'); ?>:
       
    </td>
        // Section header title according to language file.
    <td>
        $mform->addElement('header', 'config_header', get_string('blocksettings', 'block'));
        <?php print_textarea(true, 10, 50, 0, 0, 'text', $this->config->text); ?>
 
    </td>
        // A sample string variable with a default value.
</tr>
        $mform->addElement('text', 'config_text', get_string('blockstring', 'block_simplehtml'));
<tr>
        $mform->setDefault('config_text', 'default value');
    <td colspan="2" align="center">
        $mform->setType('config_text', PARAM_RAW);       
        <input type="submit" value="<?php print_string('savechanges') ?>" />
 
    </td>
    }
</tr>
}
</table>
</syntaxhighlight>
<?php use_html_editor(); ?>
The first line declares a class that inherits '''from block_edit_form''', and this allows Moodle to identify the code to execute in the configuration page. The '''specific_definition()''' method is where your form elements are defined, and these take the same format as with the standard [[lib/formslib.php_Form_Definition|Moodle form library]]. Within our specific_definition method, we have created a header, and an input field which will accept text to be used within the block.  
</nowiki>
 
It isn't difficult to see that the above code just provides us with a wysiwyg-editor-enabled textarea to write our block's desired content in and a submit button to save. But... what's $this->config->text? Well...
'''NOTE:''' You might want extend language file for your block (lang/en/block_simplehtml.php) and add a value for "blockstring" defined in a code above.
Moodle goes a long way to make things easier for block developers. Did you notice that the textarea is actually named "text"? When the submit button is pressed, Moodle saves each and every field it can find in our <span class="filename">config_instance.html</span> file as instance configuration data. We can then access that data as '''$this->config->''variablename''''', where ''variablename'' is the actual name we used for our field; in this case, "text". So in essence, the above form just pre-populates the textarea with the current content of the block (as indeed it should) and then allows us to change it.
 
You also might be surprised by the presence of a submit button and the absence of any <form> element at the same time. But the truth is, we don't need to worry about that at all; Moodle goes a really long way to make things easier for developers! We just print the configuration options we want, in any format we want; include a submit button, and Moodle will handle all the rest itself. The instance configuration variables are automatically at our disposal to access from any of the class methods ''except'' [[Blocks_Howto#method_init| init]].
'''IMPORTANT:''' All your field names need to start with "config_", otherwise they will not be saved and will not be available within the block via [[Blocks/Appendix_A#.24this-.3Econfig| $this->config]].
In the event where the default behavior is not satisfactory, we can still override it. However, this requires advanced modifications to our block class and will not be covered here; refer to [[Blocks_Howto#appendix_a| Appendix A]] for more details.
 
Having now the ability to refer to this instance configuration data through [[Blocks_Howto#variable_config| $this->config]], the final twist is to tell our block to actually ''display'' what is saved in is configuration data. To do that, find this snippet in <span class="filename">/blocks/simplehtml/block_simplehtml.php</span><nowiki>:</nowiki>
So once our instance configuration form has been saved, we can use the inputted text within the block like so:
 
$this->content = new stdClass;
<syntaxhighlight lang="php">
$this->content->text = 'The content of our SimpleHTML block!';
if (! empty($this->config->text)) {
$this->content->footer = 'Footer here...';
    $this->content->text = $this->config->text;
and change it to:
}
</syntaxhighlight>
$this->content = new stdClass;
 
$this->content->text = $this->config->text;
Note that [[Blocks/Appendix_A#.24this-.3Econfig| $this->config]] is available in all block methods ''except'' [[Blocks/Appendix_A#init.28.29|init()]]. This is because [[Blocks/Appendix_A#init.28.29|init()]] is called immediately as the block is being created, with the purpose of setting things up, so [[Blocks/Appendix_A#.24this-.3Econfig| $this->config]] has not yet been instantiated.
$this->content->footer = 'Footer here...';
 
Oh, and since the footer isn't really exciting at this point, we remove it from our block because it doesn't contribute anything. We could just as easily have decided to make the footer configurable in the above way, too. So for our latest code, the snippet becomes:
'''Note about Checkbox:''' You cannot use the 'checkbox' element in the form (once set it will stay set). You must use advcheckbox instead.  
<nowiki>
 
$this->content = new stdClass;
{{Top}}
$this->content->text = $this->config->text;
$this->content->footer = '';</nowiki>
After this discussion, our block is ready for prime time! Indeed, if you now visit any course with a SimpleHTML block, you will see that modifying its contents is now a snap.


== The Specialists ==
== The Specialists ==
Implementing instance configuration for the block's contents was good enough to whet our appetite, but who wants to stop there? Why not customize the block's title, too?
Implementing instance configuration for the block's contents was good enough to whet our appetite, but who wants to stop there? Why not customize the block's title, too?
Why not, indeed. Well, our first attempt to achieve this is natural enough: let's add another field to <span class="filename">/blocks/simplehtml/config_instance.html</span>. Here goes:
 
<nowiki>
Why not, indeed. Well, our first attempt to achieve this is natural enough: let's add another field to ''/blocks/simplehtml/'''edit_form.php'''''. Here goes:
<tr valign="top">
 
    <td align="right"><p><?php print_string('configtitle', 'block_simplehtml'); ?>:</p></td>
<syntaxhighlight lang="php">
    <td><input type="text" name="title" size="30" value="<?php echo $this->config->title; ?>" /></td>
    // A sample string variable with a default value.
</tr>
    $mform->addElement('text', 'config_title', get_string('blocktitle', 'block_simplehtml'));
</nowiki>
    $mform->setDefault('config_title', 'default value');
    $mform->setType('config_title', PARAM_TEXT);      
</syntaxhighlight>
 
We save the edited file, go to a course, edit the title of the block and... nothing happens! The instance configuration is saved correctly, all right (editing it once more proves that) but it's not being displayed. All we get is just the simple "SimpleHTML" title.
We save the edited file, go to a course, edit the title of the block and... nothing happens! The instance configuration is saved correctly, all right (editing it once more proves that) but it's not being displayed. All we get is just the simple "SimpleHTML" title.
That's not too wierd, if we think back a bit. Do you remember that [[Blocks_Howto#method_init| init]] method, where we set [[Blocks_Howto#variable_title| $this->title]]? We didn't actually change its value from then, and [[Blocks_Howto#variable_title| $this->title]] is definitely not the same as $this->config->title (to Moodle, at least). What we need is a way to update [[Blocks_Howto#variable_title| $this->title]] with the value in the instance configuration. But as we said a bit earlier, we can use [[Blocks_Howto#variable_config| $this->config]] in all methods ''except'' [[Blocks_Howto#method_init| init]]<nowiki>! So what can we do?</nowiki>
 
That's not too weird, if we think back a bit. Do you remember that [[Blocks/Appendix_A#init.28.29|init()]] method, where we set [[Blocks/Appendix_A#.24this-.3Etitle|$this->title]]? We didn't actually change its value from then, and [[Blocks/Appendix_A#.24this-.3Etitle|$this->title]] is definitely not the same as '''$this->config->title''' (to Moodle, at least). What we need is a way to update [[Blocks/Appendix_A#.24this-.3Etitle|$this->title]] with the value in the instance configuration. But as we said a bit earlier, we can use [[Blocks/Appendix_A#.24this-.3Econfig| $this->config]] in all methods ''except'' [[Blocks/Appendix_A#init.28.29|init()]]! So what can we do?
 
Let's pull out another ace from our sleeve, and add this small method to our block class:
Let's pull out another ace from our sleeve, and add this small method to our block class:
 
function specialization() {
<syntaxhighlight lang="php">
    if(!empty($this->config->title)){
public function specialization() {
        $this->title = $this->config->title;
    if (isset($this->config)) {
    }
        if (empty($this->config->title)) {
    else{
            $this->title = get_string('defaulttitle', 'block_simplehtml');          
        $this->config->title = ''''''';
        } else {
    }
            $this->title = $this->config->title;
    if(empty($this->config->text)){
        }
        $this->config->text = ''''''';
 
    }     
        if (empty($this->config->text)) {
}
            $this->config->text = get_string('defaulttext', 'block_simplehtml');
Aha, here's what we wanted to do all along! But what's going on with the [[Blocks_Howto#method_specialization| specialization]] method?
        }     
This "magic" method has actually a very nice property: it's ''guaranteed'' to be automatically called by Moodle as soon as our instance configuration is loaded and available (that is, immediately after [[Blocks_Howto#method_init| init]] is called). That means before the block's content is computed for the first time, and indeed before ''anything'' else is done with the block. Thus, providing a [[Blocks_Howto#method_specialization| specialization]] method is the natural choice for any configuration data that needs to be acted upon "as soon as possible", as in this case.
    }
}
</syntaxhighlight>
 
Aha, here's what we wanted to do all along! But what's going on with the [[Blocks/Appendix_A#specialization.28.29| specialization()]] method?
 
This "magic" method has actually a very nice property: it's ''guaranteed'' to be automatically called by Moodle as soon as our instance configuration is loaded and available (that is, immediately after [[Blocks/Appendix_A#init.28.29|init()]] is called). That means before the block's content is computed for the first time, and indeed before ''anything'' else is done with the block. Thus, providing a [[Blocks/Appendix_A#specialization.28.29| specialization()]] method is the natural choice for any configuration data that needs to be acted upon or made available "as soon as possible", as in this case.
 
{{Top}}


== Now You See Me, Now You Don't ==
== Now You See Me, Now You Don't ==
Now would be a good time to mention another nifty technique that can be used in blocks, and which comes in handy quite often. Specifically, it may be the case that our block will have something interesting to display some of the time; but in some other cases, it won't have anything useful to say. (An example here would be the "Recent Activity" block, in the case where no recent activity in fact exists. However in that case the block chooses to explicitly inform you of the lack of said activity, which is arguably useful). It would be nice, then, to be able to have our block "disappear" if it's not needed to display it.
 
This is indeed possible, and the way to do it is to make sure that after the [[Blocks_Howto#method_get_content| get_content]]<nowiki> method is called, the block is completely void of content. Specifically, "void of content" means that both $this->content->text and $this->content->footer are each equal to the empty string (''). Moodle performs this check by calling the block's </nowiki>[[Blocks_Howto#method_is_empty| is_empty()]] method, and if the block is indeed empty then it is not displayed at all.
Now would be a good time to mention another nifty technique that can be used in blocks, and which comes in handy quite often. Specifically, it may be the case that our block will have something interesting to display some of the time; but in some other cases, it won't have anything useful to say. An example here would be the "Recent Activity" block, in the case where no recent activity in fact exists.  
Note that the exact value of the block's title and the presence or absence of a [[Blocks_Howto#method_hide_header| hide_header]] method do ''not'' affect this behavior. A block is considered empty if it has no content, irrespective of anything else.
 
However in that case the block chooses to explicitly inform you of the lack of said activity, which is arguably useful. It would be nice, then, to be able to have our block "disappear" if it's not needed to display it.
 
This is indeed possible, and the way to do it is to make sure that after the [[Blocks/Appendix_A#get_content.28.29| get_content()]] method is called, the block has no content to display. This means that all fields in $this->content should be equal to the empty string (<nowiki>''</nowiki>). In the case of our HTML-based block, these fields are $this->content->text and $this->content->footer. Moodle performs this check by calling the block's [[Blocks/Appendix_A#is_empty.28.29| is_empty()]] method, and if the block is indeed empty then it is not displayed at all.
 
Note that the exact value of the block's title and the presence or absence of a [[Blocks/Appendix_A#hide_header.28.29| hide_header()]] method do ''not'' affect this behavior. A block is considered empty if it has no content, irrespective of anything else.
 
{{Top}}
 
== We Are Legion ==
== We Are Legion ==
Right now our block is fully configurable, both in title and content. It's so versatile, in fact, that we could make pretty much anything out of it. It would be really nice to be able to add multiple blocks of this type to a single course. And, as you might have guessed, doing that is as simple as adding another small method to our block class:
Right now our block is fully configurable, both in title and content. It's so versatile, in fact, that we could make pretty much anything out of it. It would be really nice to be able to add multiple blocks of this type to a single course. And, as you might have guessed, doing that is as simple as adding another small method to our block class:
 
function instance_allow_multiple() {
<syntaxhighlight lang="php">
    return true;
public function instance_allow_multiple() {
}
  return true;
}
</syntaxhighlight>
 
This tells Moodle that it should allow any number of instances of the SimpleHTML block in any course. After saving the changes to our file, Moodle immediately allows us to add multiple copies of the block without further ado!
This tells Moodle that it should allow any number of instances of the SimpleHTML block in any course. After saving the changes to our file, Moodle immediately allows us to add multiple copies of the block without further ado!
There are a couple more of interesting points to note here. First of all, even if a block itself allows multiple instances in the same page, the administrator still has the option of disallowing such behavior. This setting can be set separately for each block from the Administration / Configuration / Blocks page.
 
And finally, a nice detail is that as soon as we defined an [[Blocks_Howto#method_instance_allow_multiple| instance_allow_multiple]] method, the method [[Blocks_Howto#method_instance_allow_config| instance_allow_config]] that was already defined became obsolete. Moodle assumes that if a block allows multiple instances of itself, those instances will want to be configured (what is the point of same multiple instances in the same page if they are identical?) and thus automatically provides an "Edit" icon. So, we can also remove the whole [[Blocks_Howto#method_instance_allow_config| instance_allow_config]] method now without harm. We had only needed it when multiple instances of the block were not allowed.
Please note that even if a block itself allows multiple instances in the same page, the administrator still has the option of disallowing such behavior. This setting can be set separately for each block from the Administration / Configuration / Blocks page.
 
{{Top}}
 
== The Effects of Globalization ==
== The Effects of Globalization ==
Configuring each block instance with its own personal data is cool enough, but sometimes administrators need some way to "touch" all instances of a specific block at the same time. In the case of our SimpleHTML block, a few settings that would make sense to apply to all instances aren't that hard to come up with. For example, we might want to limit the contents of each block to only so many characters, or we might have a setting that filters HTML out of the block's contents, only allowing pure text in. Granted, such a feature wouldn't win us any awards for naming our block "SimpleHTML" but some tormented administrator somewhere might actually find it useful.
This kind of configuration is called "global configuration" and applies only to a specific block type (all instances of that block type are affected, however). Implementing such configuration for our block is quite similar to implementing the instance configuration. We will now see how to implement the second example, having a setting that only allows text and not HTML in the block's contents.
First of all, we need to tell Moodle that we want our block to provide global configuration by, what a surprise, adding a small method to our block class:
function has_config() {
    return true;
}
Then, we need to create a HTML file that actually prints out the configuration screen. In our case, we 'll just print out a checkbox saying "Do not allow HTML in the content" and a "submit" button. Let's create the file <span class="filename">/blocks/simplehtml/config_global.html</span> which again must be named just so, and copy paste the following into it:


<pre>
Configuring each block instance with its own personal data is cool enough, but sometimes administrators need some way to "touch" all instances of a specific block at the same time. In the case of our SimpleHTML block, a few settings that would make sense to apply to all instances aren't that hard to come up with.
<div style="text-align: center;">
 
<input type="hidden" name="block_simplehtml_strict" value="0" />
For example, we might want to limit the contents of each block to only so many characters, or we might have a setting that filters HTML out of the block's contents, only allowing pure text in. Granted, such a feature wouldn't win us any awards for naming our block "SimpleHTML" but some tormented administrator somewhere might actually find it useful.
<input type="checkbox" name="block_simplehtml_strict" value="1"
 
  <?php if(!empty($CFG->block_simplehtml_strict)) echo 'checked="checked"'; ?> />
This kind of configuration is called "global configuration" and applies only to a specific block type (all instances of that block type are affected, however).  Implementing such configuration for our block is quite similar to implementing the instance configuration. We will now see how to implement the second example, having a setting that only allows text and not HTML in the block's contents. To enable global configuration for the block, we create a new file, ''/blocks/simplehtml/'''settings.php''''', and populate it with form field definitions for each setting, which Moodle will use to generate and handle a global settings form. This is quite similar in concept to how we generated the instance configuration form earlier, but the actual code used to generate the form and fields is somewhat different.
<?php print_string('donotallowhtml', 'block_simplehtml'); ?>
<p><input type="submit" value="<?php print_string('savechanges'); ?>" /></p>
  </div>
</pre>


True to our block's name, this looks simple enough. What it does is that it displays a checkbox named "block_simplehtml_strict" and if the Moodle configuration variable with the same name (i.e., $CFG->block_simplehtml_strict) is set and not empty (that means it's not equal to an empty string, to zero, or to boolean false) it displays the box as pre-checked (reflecting the current status). Why does it check the configuration setting with the same name? Because the default implementation of the global configuration saving code takes all the variables we have in our form and saves them as Moodle configuration options with the same name. Thus, it's good practice to use a descriptive name and also one that won't possibly conflict with the name of another setting. "block_simplehtml_strict" clearly satisfies both requirements.
Place the following in your settings.php file:
The astute reader may have noticed that we actually have ''two'' input fields named "block_simplehtml_strict" in our configuration file. One is hidden and its value is always 0; the other is the checkbox and its value is 1. What gives? Why have them both there?
Actually, this is a small trick we use to make our job as simple as possible. HTML forms work this way: if a checkbox in a form is not checked, its name does not appear at all in the variables passed to PHP when the form is submitted. That effectively means that, when we uncheck the box and click submit, the variable is not passed to PHP at all. Thus, PHP does not know to update its value to "0", and our "strict" setting cannot be turned off at all once we turn it on for the first time. Not the behavior we want, surely.
However, when PHP handles received variables from a form, the variables are processed in the order in which they appear in the form. If a variable comes up having the same name with an already-processed variable, the new value overwrites the old one. Taking advantage of this, our logic runs as follows: the variable "block_simplehtml_strict" is first unconditionally set to "0". Then, ''if'' the box is checked, it is set to "1", overwriting the previous value as discussed. The net result is that our configuration setting behaves as it should.
To round our bag of tricks up, notice that the use of if(!empty($CFG->block_simplehtml_strict)) in the test for "should the box be checked by default?" is quite deliberate. The first time this script runs, the variable $CFG->block_simplehtml_strict will not exist at all. After it's set for the first time, its value can be either "0" or "1". Given that both "not set" and the string "0" evaluate as empty while the sting "1" does not, we manage to avoid any warnings from PHP regarding the variable not being set at all, ''and'' have a nice human-readable representation for its two possible values ("0" and "1").
Now that we have managed to cram a respectable amount of tricks into a few lines of HTML, we might as well discuss the alternative in case that tricks are not enough for a specific configuration setup we have in mind. Saving the data is done in the method [[Blocks_Howto#method_config_save| config_save]], the default implementation of which is as follows:
function config_save($data) {
    // Default behavior: save all variables as $CFG properties
    foreach ($data as $name => $value) {
        set_config($name, $value);
    }
    return true;
}
As can be clearly seen, Moodle passes this method an associative array $data which contains all the variables coming in from our configuration screen. If we wanted to do the job without the "hidden variable with the same name" trick we used above, one way to do it would be by overriding this method with the following:
function config_save($data) {
    if(isset($data['block_simplehtml_strict'])) {
        set_config('block_simplehtml_strict', '1');
    }
    else {
        set_config('block_simplehtml_strict', '0');
    }
    return true;
}
Quite straightfoward: if the variable "block_simplehtml_strict" is passed to us, then it can only mean that the user has checked it, so set the configuration variable with the same name to "1". Otherwise, set it to "0". Of course, this version would need to be updated if we add more configuration options because it doesn't respond to them as the default implementation does. Still, it's useful to know how we can override the default implementation if it does not fit our needs (for example, we might not want to save the variable as part of the Moodle configuration but do something else with it).
So, we are now at the point where we know if the block should allow HTML tags in its content or not. How do we get the block to actually respect that setting?
We could decide to do one of two things: either have the block "clean" HTML out from the input before saving it in the instance configuration and then display it as-is (the "eager" approach); or have it save the data "as is" and then clean it up each time just before displaying it (the "lazy" approach). The eager approach involves doing work once when saving the configuration; the lazy approach means doing work each time the block is displayed and thus it promises to be worse performance-wise. We shall hence go with the eager approach.
Much as we did just before with overriding [[Blocks_Howto#method_config_save| config_save]], what is needed here is overriding the method [[Blocks_Howto#method_instance_config_save| instance_config_save]] which handles the instance configuration. The default implementation is as follows:
function instance_config_save($data) {
    $data = stripslashes_recursive($data);
    $this->config = $data;
    return set_field('block_instance', 'configdata', base64_encode(serialize($data)),
                      'id', $this->instance->id);
}
This may look intimidating at first (what's all this stripslashes_recursive() and base64_encode() and serialize() stuff?) but do not despair; we won't have to touch any of it. We will only add some extra validation code in the beginning and then instruct Moodle to additionally call this default implementation to do the actual storing of the data. Specifically, we will add a method to our class which goes like this:
function instance_config_save($data) {
    // Clean the data if we have to
    global $CFG;
    if(!empty($CFG->block_simplehtml_strict)) {
        $data->text = strip_tags($data->text);
    }
    // And now forward to the default implementation defined in the parent class
    return parent::instance_config_save($data);
}
At last! Now the administrator has absolute power of life and death over what type of content is allowed in our "SimpleHTML" block! Absolute? Well... not exactly. In fact, if we think about it for a while, it will become apparent that if at some point in time HTML is allowed and some blocks have saved their content with HTML included, and afterwards the administrator changes the setting to "off", this will only prevent subsequent content changes from including HTML. Blocks which already had HTML in their content would continue to display it!
Following that train of thought, the next stop is realizing that we wouldn't have this problem if we had chosen the lazy approach a while back, because in that case we would "sanitize" each block's content just before it was displayed. The only thing we can do with the eager approach is strip all the tags from the content of all SimpleHTML instances as soon as the admin setting is changed to "HTML off"; but even then, turning the setting back to "HTML on" won't bring back the tags we stripped away. On the other hand, the lazy approach might be slower, but it's more versatile; we can choose whether to strip or keep the HTML before displaying the content, and we won't lose it at all if the admin toggles the setting off and on again. Isn't the life of a developer simple and wonderful?
We will let this part of the tutorial come to a close with the obligatory excercise for the reader: in order to have the SimpleHTML block work "correctly", find out how to strengthen the eager approach to strip out all tags from the existing configuration of all instances of our block, '''or''' go back and implement the lazy approach instead. (Hint: do that in the [[Blocks_Howto#method_get_content| get_content]] method)
'''UPDATING'''<nowiki>: Prior to version 1.5, the file </nowiki><span class="filename">config_global.html</span> was named simply <span class="filename">config.html</span>. Also, the methods [[Blocks_Howto#method_config_save| config_save]] and [[Blocks_Howto#method_config_print| config_print]] were named '''handle_config''' and '''print_config''' respectively. Upgrading a block to work with Moodle 1.5 involves updating these aspects; refer to [[Blocks_Howto#appendix_b| Appendix B]] for more information.


== Eye Candy ==
<syntaxhighlight lang="php">
Our block is just about complete functionally, so now let's take a look at some of the tricks we can use to make its behavior customized in a few more useful ways.
<?php
First of all, there are a couple of ways we can adjust the visual aspects of our block. For starters, it might be useful to create a block that doesn't display a header (title) at all. You can see this effect in action in the Course Description block that comes with Moodle. This behavior is achieved by, you guessed it, adding one more method to our block class:
$settings->add(new admin_setting_heading(
            'headerconfig',
function hide_header() {
            get_string('headerconfig', 'block_simplehtml'),
    return true;
            get_string('descconfig', 'block_simplehtml')
}
        ));
One more note here: we cannot just set an empty title inside the block's [[Blocks_Howto#method_init| init]] method; it's necessary for each block to have a unique, non-empty title after [[Blocks_Howto#method_init| init]] is called so that Moodle can use those titles to differentiate between all of the installed blocks.
Another adjustment we might want to do is instruct our block to take up a certain amount of width on screen. Moodle handles this as a two-part process: first, it queries each block about its preferred width and takes the maximum number as the desired value. Then, the page that's being displayed can choose to use this value or, more probably, bring it within some specific range of values if it isn't already. That means that the width setting is a best-effort settlement; your block can ''request'' a certain width and Moodle will ''try'' to provide it, but there's no guarantee whatsoever about the end result. As a concrete example, all standard Moodle course formats will deliver any requested width between 180 and 210 pixels, inclusive.
To instruct Moodle about our block's preferred width, we add one more method to the block class:
function preferred_width() {
    // The preferred value is in pixels
    return 200;
}
This will make our block (and all the other blocks displayed at the same side of the page) a bit wider than standard.
Finally, we can also affect some properties of the actual HTML that will be used to print our block. Each block is fully contained within a &lt;table&gt; element, inside which all the HTML for that block is printed. We can instruct Moodle to add HTML attributes with specific values to that container. This would be done to either a) directly affect the end result (if we say, assign bgcolor="black"), or b) give us freedom to customize the end result using CSS (this is in fact done by default as we 'll see below).
The default behavior of this feature in our case will assign to our block's container the class HTML attribute with the value "sideblock block_simplehtml" (the prefix "block_" followed by the name of our block, lowercased). We can then use that class to make CSS selectors in our theme to alter this block's visual style (for example, ".sideblock.block_simplehtml { border: 1px black solid}").
To change the default behavior, we will need to define a method which returns an associative array of attribute names and values. For example, the version
function html_attributes() {
    return array(
        'class'      => 'sideblock block_'. $this->name(),
        'onmouseover' => "alert('Mouseover on our block!');"
    );
}
will result in a mouseover event being added to our block using JavaScript, just as if we had written the onmouseover="alert(...)" part ourselves in HTML. Note that we actually duplicate the part which sets the class attribute (we want to keep that, and since we override the default behavior it's our responsibility to emulate it if required). And the final elegant touch is that we don't set the class to the hard-coded value "block_simplehtml" but instead use the [[Blocks_Howto#method_name| name]] method to make it dynamically match our block's name.


== Authorized Personnel Only ==
$settings->add(new admin_setting_configcheckbox(
It's not difficult to imagine a block which is very useful in some circumstances but it simply cannot be made meaningful in others. An example of this would be the "Social Activities" block which is indeed useful in a course with the social format, but doesn't do anything useful in a course with the weeks format. There should be some way of allowing the use of such blocks only where they are indeed meaningful, and not letting them confuse users if they are not.
            'simplehtml/Allow_HTML',
Moodle allows us to declare which course formats each block is allowed to be displayed in, and enforces these restrictions as set by the block developers at all times. The information is given to Moodle as a standard associative array, with each key corresponding to a page format and defining a boolean value (true/false) that declares whether the block should be allowed to appear in that page format.
            get_string('labelallowhtml', 'block_simplehtml'),
Notice the deliberate use of the term ''page'' instead of ''course'' in the above paragraph. This is because in Moodle 1.5 and onwards, blocks can be displayed in any page that supports them. The best example of such pages are the course pages, but we are not restricted to them. For instance, the quiz view page (the first one we see when we click on the name of the quiz) also supports blocks.
            get_string('descallowhtml', 'block_simplehtml'),
The format names we can use for the pages derive from the name of the script which is actually used to display that page. For example, when we are looking at a course, the script is <span class="filename">/course/view.php</span> (this is evident from the browser's address line). Thus, the format name of that page is '''course-view'''. It follows easily that the format name for a quiz view page is '''mod-quiz-view'''. This rule of thumb does have a few exceptions, however:
            '0'
#* The format name for the front page of Moodle is '''site-index'''.
        ));  
#* The format name for courses is actually not just '''course-view'''<nowiki>; it is </nowiki>'''course-view-weeks''', '''course-view-topics''', etc.
</syntaxhighlight>
#* Even though there is no such page, the format name '''all''' can be used as a catch-all option.
We can include as many format names as we want in our definition of the applicable formats. Each format can be allowed or disallowed, and there are also three more rules that help resolve the question "is this block allowed into this page or not?":
#* Prefixes of a format name will match that format name; for example, '''mod''' will match all the activity modules. '''course-view''' will match any course, regardless of the course format. And finally, '''site''' will also match the front page (remember that its full format name is '''site-index''').
#* The more specialized a format name that matches our page is, the higher precedence it has when deciding if the block will be allowed. For example, '''mod''', '''mod-quiz''' and '''mod-quiz-view''' all match the quiz view page. But if all three are present, '''mod-quiz-view''' will take precedence over the other two because it is a better match.
#* The character '''<nowiki>*</nowiki>''' can be used in place of any word. For example, '''mod''' and '''mod-*''' are equivalent. At the time of this document's writing, there is no actual reason to utilize this "wildcard matching" feature, but it exists for future usage.
#* The order that the format names appear does not make any difference.
All of the above are enough to make the situation sound complex, so let's look at some specific examples. First of all, to have our block appear '''only''' in the site front page, we would use:
function applicable_formats() {
    return array('site' => true);
}
Since '''all''' is missing, the block is disallowed from appearing in ''any'' course format; but then '''site''' is set to true, so it's explicitly allowed to appear in the site front page (remember that '''site''' matches '''site-index''' because it's a prefix).
For another example, if we wanted to allow the block to appear in all course formats ''except'' social, and also to ''not'' be allowed anywhere but in courses, we would use:
function applicable_formats() {
    return array('course-view' => true, 'course-view-social' => false);
}
This time, we first allow the block to appear in all courses and then we explicitly disallow the social format.
For our final, most complicated example, suppose that a block can be displayed in the site front page, in courses (but not social courses) and also when we are viewing any activity module, ''except'' quiz. This would be:
function applicable_formats() {
    return array('site-index' => true,
                  'course-view' => true, 'course-view-social' => false,
                  'mod' => true, 'mod-quiz' => false);
}
It is not difficult to realize that the above accomplishes the objective if we remember that there is a "best match" policy to determine the end result.
'''UPDATING:''' Prior to version 1.5, blocks were only allowed in courses (and in Moodle 1.4, in the site front page). Also, the keywords used to describe the valid course formats at the time were slightly different and had to be changed in order to allow for a more open architecture. Refer to [[Blocks_Howto#appendix_b| Appendix B]] for more information on the changes that old blocks have to make to conform to the new standard.
== Lists and Icons ==
In this final part of the guide we will briefly discuss an additional capability of Moodle's block system, namely the ability to very easily create blocks that display a list of choices to the user. This list is displayed with one item per line, and an optional image (icon) next to the item. An example of such a ''list block'' is the standard Moodle "admin" block, which illustrates all the points discussed in this section.
As we have seen so far, blocks use two properties of [[Blocks_Howto#variable_content| $this->content]]<nowiki>: "text" and "footer". The text is displayed as-is as the block content, and the footer is displayed below the content in a smaller font size. List blocks use $this->content->footer in the exact same way, but they ignore $this->content->text.</nowiki>
Instead, Moodle expects such blocks to set two other properties when the [[Blocks_Howto#method_get_content| get_content]] method is called: $this->content->items and $this->content->icons. $this->content->items should be a numerically indexed array containing elements that represent the HTML for each item in the list that is going to be displayed. Usually these items will be HTML anchor tags which provide links to some page. $this->content->icons should also be a numerically indexed array, with exactly as many items as $this->content->items has. Each of these items should be a fully qualified HTML <img> tag, with "src", "height", "width" and "alt" attributes. Obviously, it makes sense to keep the images small and of a uniform size.
In order to tell Moodle that we want to have a list block instead of the standard text block, we need to make a small change to our block class declaration. Instead of extending class '''block_base''', our block will extend class '''block_list'''. For example:
class block_my_menu extends block_list {
    // The init() method does not need to change at all
}
In addition to making this change, we must of course also modify the [[Blocks_Howto#method_get_content| get_content]] method to construct the [[Blocks_Howto#variable_content| $this->content]] variable as discussed above:
function get_content() {
    if ($this->content !== NULL) {
        return $this->content;
    }
    $this->content = new stdClass;
    $this->content->items = array();
    $this->content->icons = array();
    $this->content->footer = 'Footer here...';
    $this->content->items[] = '<a href="some_file.php">Menu Option 1</a>';
    $this->content->icons[] = '<img src="images/icons/1.gif" class="icon" alt="" />';
    // Add more list items here
    return $this->content;
}
To summarize, if we want to create a list block instead of a text block, we just need to change the block class declaration and the [[Blocks_Howto#method_get_content| get_content]] method. Adding the mandatory [[Blocks_Howto#method_init| init]] method as discussed earlier will then give us our first list block in no time!


== Appendix A: Reference ==
As you can see, to generate a global configuration form, we simply create admin setting objects and add them to an array. This array is then stepped over to create the settings form, and the inputted data is automatically saved to the database. Full details of the setting types available and how to add them can be found under [[Admin_settings#Individual_settings]].


This Appendix will discuss the base class '''block_base''' from which all other block classes derive, and present each and every method that can be overridden by block developers in detail. Methods that should '''not''' be overridden are explicitly referred to as such. After reading this Appendix, you will have a clear understanding of every method which you should or could override to implement functionality for your block.
We've now created a header and checkbox form element to accept configuration details from the site admin. You should pay extra attention to the name of our checkbox element, ''' 'simplehtml/Allow_HTML' ''', as it specifies not only the name of the configuration option, but also how it should be stored. If you simply specify a name for the config option, it will be stored in the global $CFG object, and in the ''<prefix>_config'' database table. This will make your config variable available immediately via $CFG without requiring an additional database call, but will also increase the size of the $CFG object. In addition, we must prefix the variable with the name of our block, otherwise we run the risk of our config variable sharing its name with a similar variable in another plugin, or within Moodle itself.


The methods are divided into three categories: those you may use and override in your block, those that you may '''not''' override but might want to use, and those internal methods that should '''neither''' be used '''nor''' overridden. In each category, methods are presented in alphabetical order.
The preferred method of storing your block's configuration data is to prefix each config variable name in your settings.php file with your block's name, followed by a slash ( / ), and the name of the configuration variable, as we have done above. If you write your settings.php file in this way, then your variables will be stored in the ''<prefix>_config_plugin'' table, under your block's name. Your config data will still be available via a '''get_config()''' call, and name collision will be impossible between plugins.


=== Methods you can freely use and override: ===
Finally, if you're wondering why there are two language tags specified for each element, the first tag is for the element's label or primary text, and the second tag is for its description. And that's it. Pretty easy, huh?
** <div class="function_title">after_install</div>
<nowiki>
function after_install() {
}
</nowiki>
Available in Moodle 1.7 and later


This method is designed to be overridden by block subclasses, and allows you to specify a set of tasks to be executed after the block is installed. For example, you may wish to store the date on which the block was installed. However, each database type has its own way of getting the current date, and when using XMLDB to install your block, these operations are also unsupported. So the best way to complete such a task while maintaining database abstraction is to use XMLDB to install the block, and then use the after_install() method to perform the insertion before the block is used.
=== Enabling Global Configuration ===
{{Moodle 2.4}}Since version 2.4, the following line must be added to the /blocks/simplehtml/block_simplehtml.php file in order to enable global configuration:
<syntaxhighlight lang="php">
    function has_config() {return true;}
</syntaxhighlight>
This line tells Moodle that the block has a settings.php file.


Please note that after_install() is called once per block, not once per instance.


** <div class="function_title">applicable_formats</div>
'''NOTE FOR UPGRADERS'''
<nowiki>
function applicable_formats() {
    // Default case: the block can be used in courses and site index, but not in activities
    return array('all' => true, 'mod' => false);
}
</nowiki>
Available in Moodle 1.5 and later


This method allows you to control which pages your block can be added to. Page formats are formulated from the full path of the script that is used to display that page. You should return an array with the keys being page format names and the values being booleans (true or false). Your block is only allowed to appear in those formats where the value is true.
You'll notice that the settings.php file and parsed element names replaces Moodle's old storage method, wherein it would send all the configuration data to your block's [[Blocks/Appendix_A#config_save.28.29|config_save()]] method, and allow you to override how the data is saved. The [[Blocks/Appendix_A#config_save.28.29|config_save()]] method is no longer used in Moodle 2.x; however the [[Blocks/Appendix_A#instance_config_save.28.29|instance_config_save()]] method is very much alive and well, as you will see shortly.
Example format names are: '''course-view''', '''site-index''' (this is an exception, referring front page of the Moodle site), '''course-format-weeks''' (referring to a specific course format), '''mod-quiz''' (referring to the quiz module) and '''all''' (this will be used for those formats you have not explicitly allowed or disallowed).
The full matching rules are:
*** Prefixes of a format name will match that format name; for example, '''mod''' will match all the activity modules. '''course-view''' will match any course, regardless of the course format. And finally, '''site''' will also match the front page (remember that its full format name is '''site-index''').
*** The more specialized a format name that matches our page is, the higher precedence it has when deciding if the block will be allowed. For example, '''mod''', '''mod-quiz''' and '''mod-quiz-view''' all match the quiz view page. But if all three are present, '''mod-quiz-view''' will take precedence over the other two because it is a better match.
*** The character '''<nowiki>*</nowiki>''' can be used in place of any word. For example, '''mod''' and '''mod-*''' are equivalent. At the time of this document's writing, there is no actual reason to utilize this "wildcard matching" feature, but it exists for future usage.
*** The order that the format names appear does not make any difference.


** <div class="function_title">before_delete</div>
{{Top}}


  <nowiki>
=== Accessing Global Config Data ===
function before_delete() {
}
</nowiki>
Available in Moodle 1.7 and later


This method is called when an administrator removes a block from the Moodle installation, immediately before the relevant database tables are deletedIt allows block authors to perform any necessary cleanup - removing temporary files and so on - before the block is deleted.
Now that we have global data defined for the plugin, we need to know how to access it within our codeIf you saved your config variables in the global namespace, you can access them from the global $CFG object, like so:


** <div class="function_title">config_print</div>
<syntaxhighlight lang="php">
<nowiki>
$allowHTML = $CFG->Allow_HTML;
function config_print() {
</syntaxhighlight>
    // Default behavior: print the config_global.html file
    // You don't need to override this if you're satisfied with the above
    if (!$this->has_config()) {
        return false;
    }
    global $CFG, $THEME;
    print_simple_box_start('center', '', $THEME->cellheading);
    include($CFG->dirroot.'/blocks/'. $this->name() .'/config_global.html');
    print_simple_box_end();
    return true;
}</nowiki>
Available in Moodle 1.5 and later


This method allows you to choose how to display the global configuration screen for your block. This is the screen that the administrator is presented with when he chooses "Settings..." for a specific block. Override it if you need something much more complex than the default implementation allows you to do. However, keep these points in mind:
If, as recommended, you saved your config variables in a custom namespace for your block, then you can access them via a call to '''get_config()''':
**# If you save your configuration options in $CFG, you will probably need to use global $CFG; before including any HTML configuration screens.
**# The HTML <input> elements that you include in your method's output will be automatically enclosed in a <form> element. You do not need to worry about where and how that form is submitted; however, you '''must''' provide a way to submit it (i.e., an <input type="submit" />.
You should return a boolean value denoting the success or failure of your method's actions.
** <div class="function_title">config_save</div>
function config_save($data) {
    // Default behavior: save all variables as $CFG properties
    // You don't need to override this if you 're satisfied with the above
    foreach ($data as $name => $value) {
        set_config($name, $value);
    }
    return true;
}
Available in Moodle 1.5 and later


This method allows you to override the storage mechanism for your global configuration data. The received argument is an associative array, with the keys being setting names and the values being setting values. The default implementation saves everything as Moodle $CFG variables.
<syntaxhighlight lang="php">
Note that $data does not hold all of the submitted POST data because Moodle adds some hidden fields to the form in order to be able to process it. However, before calling this method it strips the hidden fields from the received data and so when this method is called only the "real" configuration data remain.
$allowHTML = get_config('simplehtml', 'Allow_HTML');
You should return a boolean value denoting the success or failure of your method's actions.
</syntaxhighlight>
** <div class="function_title">get_content</div>
function get_content() {
    // This should be implemented by the derived class.
    return NULL;
}
Available in Moodle 1.5 and later


This method should, when called, populate the [[Blocks_Howto#variable_content| $this->content]] variable of your block. Populating the variable means:
{{Top}}
'''EITHER'''<br />defining $this->content->text and $this->content->footer if your block derives from '''block_base'''. Both of these should be strings, and can contain arbitrary HTML.
'''OR'''<br />defining $this->content->items, $this->content->icons and $this->content->footer if your block derives from '''block_list'''. The first two should be numerically indexed arrays having the exact same number of elements. $this->content->items is an array of strings that can contain arbitrary HTML while $this->content->icons also contains should strings, but those must be fully-qualified HTML <img> tags '''and nothing else'''. $this->content->footer is a string, as above.
If you set ''all'' of these variables to their default "empty" values (empty arrays for the arrays and empty strings for the strings), the block will '''not''' be displayed at all except to editing users. This is a good way of having your block hide itself to unclutter the screen if there is no reason to have it displayed.
Before starting to populate [[Blocks_Howto#variable_content| $this->content]], you should also include a simple caching check. If [[Blocks_Howto#variable_content| $this->content]] is exactly equal to NULL then proceed as normally, while if it is not, return the existing value instead of calculating it once more. If you fail to do this, Moodle will suffer a performance hit.
In any case, your method should return the fully constructed [[Blocks_Howto#variable_content| $this->content]] variable.
** <div class="function_title">has_config</div>
function has_config() {
    return false;
}
Available in Moodle 1.5 and later


This method should return a boolean value that denotes whether your block wants to present a configuration interface to site admins or not. The configuration that this interface offers will impact all instances of the block equally.
=== Rolling It All Together ===
To actually implement the configuration interface, you will either need to rely on the default [[Blocks_Howto#method_instance_config_print| config_print]] method or override it. The full guide contains [[Blocks_Howto#section_effects_of_globalization| more information on this]].
** <div class="function_title">hide_header</div>
function hide_header() {
    //Default, false--> the header is shown
    return false;
}
Available in Moodle 1.5 and later


This method should return a boolean value that denotes whether your block wants to hide its header (or title). Thus, if you override it to return true, your block will not display a title unless the current user is in editing mode.
OK, so we now have an instance configuration form that allows users to enter custom content text for a block, and a global configuration option that dictates whether or not that user should be allowed to enter HTML tags as part of the content. Now we just need to tie the two together. But if Moodle takes care of the form processing for our instance configuration in edit_form.php, how can we capture it and remove the HTML tags where required?
** <div class="function_title">html_attributes</div>
function html_attributes() {
    // Default case: an id with the instance and a class with our name in it
    return array('id' => 'inst'.$this->instance->id, 'class' => 'block_'. $this->name());
}
Available in Moodle 1.5 and later


This method should return an associative array of HTML attributes that will be given to your block's container element when Moodle constructs the output HTML. No sanitization will be performed in these elements at all.
Well, fortunately, there is a way this can be done. By overriding the [[Blocks/Appendix_A#instance_config_save.28.29| instance_config_save()]] method in our block class, we can modify the way in which instance configuration data is stored after input. The default implementation is as follows:
If you intend to override this method, you should return the default attributes as well as those you add yourself. The recommended way to do this is:
   
function html_attributes() {
    $attrs = parent::html_attributes();
    // Add your own attributes here, e.g.
    // $attrs['width'] = '50%';
    return $attrs;
}
** <div class="function_title">init</div>
function init() {
    $this->title = get_string('simplehtml', 'block_simplehtml');
    $this->version = 2004111200;
}
Available in Moodle 1.5 and later


This method must be implemented for all blocks. It has to assign meaningful values to the object variables [[Blocks_Howto#variable_title| $this->title]] and [[Blocks_Howto#variable_version| $this->version]] (which is used by Moodle for performing automatic updates when available).
<syntaxhighlight lang="php">
No return value is expected from this method.
public function instance_config_save($data, $nolongerused = false) {
** <div class="function_title">instance_allow_config</div>
  $data = stripslashes_recursive($data);
  $this->config = $data;
function instance_allow_config() {
  return set_field('block_instance',
    return false;
                  'configdata',
}
                    base64_encode(serialize($data)),
Available in Moodle 1.5 and later
                  'id',
                  $this->instance->id);
}
</syntaxhighlight>


This method should return a boolean value. True indicates that your block wants to have per-instance configuration, while false means it does not. If you do want to implement instance configuration, you will need to take some additional steps apart from overriding this method; refer to the full guide for [[Blocks_Howto#section_configure_that_out| more information]].
This may look intimidating at first (what's all this stripslashes_recursive() and base64_encode() and serialize() stuff?) but do not despair; we won't have to touch any of it. We will only add some extra validation code in the beginning and then instruct Moodle to additionally call this default implementation to do the actual storing of the data. Specifically, we will add a method to our class which goes like this:
This method's return value is irrelevant if [[Blocks_Howto#method_instance_allow_multiple| instance_allow_multiple]] returns true; it is assumed that if you want multiple instances then each instance needs its own configuration.
** <div class="function_title">instance_allow_multiple</div>
   
   
function instance_allow_multiple() {
<syntaxhighlight lang="php">
    // Are you going to allow multiple instances of each block?
public function instance_config_save($data,$nolongerused =false) {
    // If yes, then it is assumed that the block WILL USE per-instance configuration
  if(get_config('simplehtml', 'Allow_HTML') == '1') {
    return false;
    $data->text = strip_tags($data->text);
}
  }
Available in Moodle 1.5 and later


This method should return a boolean value, indicating whether you want to allow multiple instances of this block in the same page or not. If you do allow multiple instances, it is assumed that you will also be providing per-instance configuration for the block. Thus, you will need to take some additional steps apart from overriding this method; refer to the full guide for [[Blocks_Howto#section_configure_that_out| more information]].
  // And now forward to the default implementation defined in the parent class
** <div class="function_title">instance_config_print</div>
  return parent::instance_config_save($data,$nolongerused);
<nowiki>
}
function instance_config_print() {
</syntaxhighlight>
    // Default behavior: print the config_instance.html file
    // You don't need to override this if you're satisfied with the above
    if (!$this->instance_allow_multiple() && !$this->instance_allow_config()) {
        return false;
    }
    global $CFG, $THEME;
    if (is_file($CFG->dirroot .'/blocks/'. $this->name() .'/config_instance.html')) {
        print_simple_box_start('center', '', $THEME->cellheading);
        include($CFG->dirroot .'/blocks/'. $this->name() .'/config_instance.html');
        print_simple_box_end();
    } else {
        notice(get_string('blockconfigbad'),
                str_replace('blockaction=', 'dummy=', qualified_me()));
    }
    return true;
}</nowiki>
Available in Moodle 1.5 and later


This method allows you to choose how to display the instance configuration screen for your block. Override it if you need something much more complex than the default implementation allows you to do. Keep in mind that whatever you do output from [[Blocks_Howto#method_instance_config_print| config_print]], it will be enclosed in a HTML form automatically. You only need to provide a way to submit that form.
(This example assumes you are using a custom namespace for the block.)
You should return a boolean value denoting the success or failure of your method's actions.
** <div class="function_title">instance_config_save</div>
function instance_config_save($data) {
    $data = stripslashes_recursive($data);
    $this->config = $data;
    return set_field('block_instance', 'configdata', base64_encode(serialize($data)),
                      'id', $this->instance->id);
}
Available in Moodle 1.5 and later


This method allows you to override the storage mechanism for your instance configuration data. The received argument is an associative array, with the keys being setting names and the values being setting values.
At last! Now the administrator has absolute power of life and death over what type of content is allowed in our "SimpleHTML" block! Absolute? Well... not exactly. In fact, if we think about it for a while, it will become apparent that if at some point in time HTML is allowed and some blocks have saved their content with HTML included, and afterwards the administrator changes the setting to "off", this will only prevent subsequent content changes from including HTML. Blocks which already had HTML in their content would continue to display it!
The configuration must be stored in the "configdata" field of your instance record in the database so that Moodle can auto-load it when your block is constructed. However, you may still want to override this method if you need to take some additional action apart from saving the data. In that case, you really should do what data processing you want and then call parent::instance_config_save($data) with your new $data array. This will keep your block from becoming broken if the default implementation of instance_config_save changes in the future.
Note that $data does not hold all of the submitted POST data because Moodle adds some hidden fields to the form in order to be able to process it. However, before calling this method it strips the hidden fields from the received data and so when this method is called only the "real" configuration data remain.
If you want to update the stored copy of the configuration data at run time (for example to persist some changes you made programmatically), you should not use this method. The correct procedure for that purpose is to call [[Blocks_Howto#method_instance_config_commit| instance_config_commit]].
You should return a boolean value denoting the success or failure of your method's actions.
** <div class="function_title">preferred_width</div>
function preferred_width() {
    // Default case: the block wants to be 180 pixels wide
    return 180;
}
Available in Moodle 1.5 and later


This method should return an integer value, which is the number of pixels of width your block wants to take up when displayed. Moodle will try to honor your request, but this is actually up to the implementation of the format of the page your block is being displayed in and therefore no guarantee is given. You might get exactly what you want or any other width the format decides to give you, although obviously an effort to accomodate your block will be made.
Following that train of thought, the next stop is realizing that we wouldn't have this problem if we had chosen the lazy approach a while back, because in that case we would "sanitize" each block's content just before it was displayed.  
Most display logic at this point allocates the maximum width requested by the blocks that are going to be displayed, bounding it both downwards and upwards to avoid having a bad-behaving block break the format.
** <div class="function_title">refresh_content</div>
function refresh_content() {
    // Nothing special here, depends on content()
    $this->content = NULL;
    return $this->get_content();
}
Available in Moodle 1.5 and later


This method should cause your block to recalculate its content immediately. If you follow the guidelines for [[Blocks_Howto#get_content| get_content]], which say to respect the current content value unless it is NULL, then the default implementation will do the job just fine.
The only thing we can do with the eager approach is strip all the tags from the content of all SimpleHTML instances as soon as the admin setting is changed to "HTML off"; but even then, turning the setting back to "HTML on" won't bring back the tags we stripped away. On the other hand, the lazy approach might be slower, but it's more versatile; we can choose whether to strip or keep the HTML before displaying the content, and we won't lose it at all if the admin toggles the setting off and on again. Isn't the life of a developer simple and wonderful?
You should return the new value of [[Blocks_Howto#variable_content| $this->content]] after refreshing it.
** <div class="function_title">specialization</div>
function specialization() {
    // Just to make sure that this method exists.
}
Available in Moodle 1.5 and later


This method is automatically called by the framework immediately after your instance data (which includes the page type and id and all instance configuration data) is loaded from the database. If there is some action that you need to take as soon as this data becomes available and which cannot be taken earlier, you should override this method.
=== Exercise ===
The instance data will be available in the variables [[Blocks_Howto#variable_instance| $this->instance]] and [[Blocks_Howto#variable_config| $this->config]].
We will let this part of the tutorial come to a close with the obligatory exercise for the reader:
This method should not return anything at all.
In order to have the SimpleHTML block work "correctly", find out how to strengthen the eager approach to strip out all tags from the existing configuration of all instances of our block, '''or''' go back and implement the lazy approach instead.  
=== Methods which you should ''not'' override but may want to use: ===
(Hint: Do that in the [[Blocks/Appendix_A#get_content.28.29| get_content()]] method.)
** <div class="function_title">instance_config_commit</div>
function instance_config_commit() {
    return set_field('block_instance',
                      'configdata', base64_encode(serialize($this->config)),
                      'id', $this->instance->id);
}
Available in Moodle 1.5 and later


This method saves the current contents of [[Blocks_Howto#variable_config| $this->config]] to the database. If you need to make a change to the configuration settings of a block instance at run time (and not through the usual avenue of letting the user change it), just make the changes you want to [[Blocks_Howto#variable_config| $this->config]] and then call this method.
** <div class="function_title">get_content_type</div>
function get_content_type() {
    return $this->content_type;
}
Available in Moodle 1.5 and later


This method returns the value of [[Blocks_Howto#variable_content_type| $this->content_type]], and is the preferred way of accessing that variable. It is guaranteed to always work, now and forever. Directly accessing the variable is '''not recommended'''<nowiki>; future library changes may break compatibility with code that does so.</nowiki>
{{Top}}
** <div class="function_title">get_title</div>
function get_title() {
    return $this->title;
}
Available in Moodle 1.5 and later


This method returns the value of [[Blocks_Howto#variable_title| $this->title]], and is the preferred way of accessing that variable. It is guaranteed to always work, now and forever. Directly accessing the variable is '''not recommended'''<nowiki>; future library changes may break compatibility with code that does so.</nowiki>
== Eye Candy ==
** <div class="function_title">get_version</div>
function get_version() {
    return $this->version;
}
Available in Moodle 1.5 and later


This method returns the value of [[Blocks_Howto#variable_version| $this->version]], and is the preferred way of accessing that variable. It is guaranteed to always work, now and forever. Directly accessing the variable is '''not recommended'''<nowiki>; future library changes may break compatibility with code that does so.</nowiki>
Our block is just about complete functionally, so now let's take a look at some of the tricks we can use to make its behavior customized in a few more useful ways.
** <div class="function_title">is_empty</div>
For blocks that extend class '''block_base'''<nowiki>:</nowiki>
function is_empty() {
    $this->get_content();
    return(empty($this->content->text) && empty($this->content->footer));
}
Available in Moodle 1.5 and later


For blocks that extend class '''block_list'''<nowiki>:</nowiki>
First of all, there are a couple of ways we can adjust the visual aspects of our block. For starters, it might be useful to create a block that doesn't display a header (title) at all. You can see this effect in action in the Course Description block that comes with Moodle. This behavior is achieved by, you guessed it, adding one more method to our block class:
function is_empty() {
    $this->get_content();
    return (empty($this->content->items) && empty($this->content->footer));
}
This method returns the a boolean true/false value, depending on whether the block has any content at all to display. Blocks without content are not displayed by the framework.
** <div class="function_title">name</div>
function name() {
    static $myname;
    if ($myname === NULL) {
        $myname = strtolower(get_class($this));
        $myname = substr($myname, strpos($myname, '_') + 1);
    }
    return $myname;
}
Available in Moodle 1.5 and later


This method returns the internal name of your block inside Moodle, without the '''block_''' prefix. Obtaining the name of a block object is sometimes useful because it can be used to write code that is agnostic to the actual block's name (and thus more generic and reusable). For an example of this technique, see the [[Blocks_Howto#method_config_print| config_print]] method.
<syntaxhighlight lang="php">
=== Methods which you should ''not'' override and ''not'' use at all: ===
public function hide_header() {
** <div class="function_title">_self_test</div>
  return true;
This is a private method; no description is given.
}
** <div class="function_title">_add_edit_controls</div>
</syntaxhighlight>
This is a private method; no description is given.
** <div class="function_title">_load_instance</div>
This is a private method; no description is given.
** <div class="function_title">_print_block</div>
This is a private method; no description is given.
** <div class="function_title">_print_shadow</div>
This is a private method; no description is given.


The class '''block_base''' also has a few standard member variables which its methods manipulate. These variables, the purpose of each and the type of data they are expected to hold is explained in the next section of this Appendix.
One more note here: we cannot just set an empty title inside the block's [[Blocks/Appendix_A#init.28.29| init()]] method; it's necessary for each block to have a unique, non-empty title after [[Blocks/Appendix_A#init.28.29| init()]] is called so that Moodle can use those titles to differentiate between all of the installed blocks.


=== Class variables: ===
Next, we can affect some properties of the actual HTML that will be used to print our block. Each block is fully contained within a &lt;div&gt; or &lt;table&gt; elements, inside which all the HTML for that block is printed. We can instruct Moodle to add HTML attributes with specific values to that container. This is generally done to give us freedom to customize the end result using CSS (this is in fact done by default as we'll see below).


* <div class="variable_title">$this->config</div>
The default behavior of this feature in our case will modify our block's "class" HTML attribute by appending the value "block_simplehtml" (the prefix "block_" followed by the name of our block, lowercased). We can then use that class to make CSS selectors in our theme to alter this block's visual style (for example, ".block_simplehtml { border: 1px black solid}").
This variable holds all the specialized instance configuration data that have been provided for this specific block instance (object). It is an object of type stdClass, with member variables directly corresponding to the HTML <input> elements in the block's <span class="filename">config_instance.html</span> file.
The variable is initialized just after the block object is constructed, immediately before [[Blocks_Howto#method_specialization| specialization]] is called for the object. It is possible that the block has no instance configuration, in which case the variable will be NULL.
It is obvious that there is a direct relationship between this variable and the configdata field in the mdl_block_instance table. However, it is ''strongly'' advised that you refrain from accessing the configdata field yourself. If you absolutely must update its value at any time, it is recommended that you call the method [[Blocks_Howto#method_instance_config_commit| instance_config_commit]] to do the actual work.
* <div class="variable_title">$this->content_type</div>
This variable instructs Moodle on what type of content it should assume the block has, and is used to differentiate text blocks from list blocks. It is essential that it has a meaningful value, as Moodle depends on this for correctly displaying the block on screen. Consequently, this variable is closely tied with the variable [[Blocks_Howto#variable_content| $this->content]]. The variable is expected to have a valid value after the framework calls the [[Blocks_Howto#method_init| init]] method for each block.
The only valid values for this variable are the two named constants [[Blocks_Howto#constant_block_type_text| BLOCK_TYPE_TEXT]] and [[Blocks_Howto#constant_block_type_list| BLOCK_TYPE_LIST]].
* <div class="variable_title">$this->content</div>
This variable holds all the actual content that is displayed inside each block. Valid values for it are either NULL or an object of class stdClass, which must have specific member variables set as explained below. Normally, it begins life with a value of NULL and it becomes fully constructed (i.e., an object) when [[Blocks_Howto#method_get_content| get_content]] is called.
After it is fully constructed, this object is expected to have certain properties, depending on the value of [[Blocks_Howto#variable_content_type| $this->content_type]]. Specifically:
** If [[Blocks_Howto#variable_content_type| $this->content_type]] is [[Blocks_Howto#constant_block_type_text| BLOCK_TYPE_TEXT]], then [[Blocks_Howto#variable_content| $this->content]] is expected to have the following member variables:
*** <div>'''text'''</div>This is a string of arbitrary length and content. It is displayed inside the main area of the block, and can contain HTML.
*** <div>'''footer'''</div>This is a string of arbitrary length and contents. It is displayed below the text, using a smaller font size. It can also contain HTML.
** If [[Blocks_Howto#variable_content_type| $this->content_type]] is [[Blocks_Howto#constant_block_type_list| BLOCK_TYPE_LIST]], then [[Blocks_Howto#variable_content| $this->content]] is expected to have the following member variables:
*** <div>'''items'''</div>This is a numerically indexed array of strings which holds the title for each item in the list that will be displayed in the block's area. Since usually such lists function like menus, the title for each item is normally a fully qualified HTML <a> tag.
*** <div>'''icons'''</div>This is a numerically indexed array of strings which represent the images displayed before each item of the list. It therefore follows that it should have the exact number of elements as the items member variable. Each item in this array should be a fully qualified HTML <img> tag.
*** <div>'''footer'''</div>This is a string of arbitrary length and contents. It is displayed below the text, using a smaller font size. It can also contain HTML.
* <div class="variable_title">$this->instance</div>
This member variable holds all the specific information that differentiates one block instance (i.e., the PHP object that embodies it) from another. It is an object of type stdClass retrieved by calling get_record on the table mdl_block_instance. Its member variables, then, directly correspond to the fields of that table. It is initialized immediately after the block object itself is constructed.
* <div class="variable_title">$this->title</div>
This variable is a string that contains the human-readable name of the block. It is used to refer to blocks of that type throughout Moodle, for example in the administrator's block configuration screen and in the editing teacher's add block menu. It is also the title that is printed when the block is displayed on screen, although blocks can specifically change this title to something else if they wish (see below). The variable is expected to have a valid value after the framework calls the [[Blocks_Howto#method_init| init]] method for each object.
In the case of blocks which may want to configure their title dynamically through instance configuration, it is still essential to provide a valid title inside [[Blocks_Howto#method_init| init]]. This title may then be overridden when the [[Blocks_Howto#method_specialization| specialization]] method is called by the framework:
function specialization() {
    // At this point, $this->instance and $this->config are available
    // for use. We can now change the title to whatever we want.
    $this->title = $this->config->variable_holding_the_title;
}


A lot of blocks seem to use
To change the default behavior, we will need to define a method which returns an associative array of attribute names and values. For example:


$this->title = get_string('blockname', ... );
<syntaxhighlight lang="php">
public function html_attributes() {
    $attributes = parent::html_attributes(); // Get default values
    $attributes['class'] .= ' block_'. $this->name(); // Append our class to class attribute
    return $attributes;
}
</syntaxhighlight>


to set the title of the block (and then put a more specific title inside the language file)
This results in the block having all its normal HTML attributes, as inherited from the base block class, plus our additional class name. We can now use this class name to change the style of the block, add JavaScript events to it via YUI, and so on. And for one final elegant touch,  we have not set the class to the hard-coded value "block_simplehtml", but instead used the [[Blocks/Appendix_A#name.28.29| name()]] method to make it dynamically match our block's name.
If there is no proper language string, the title of the block will then be set to ''blockname''. If there is another block with the same generic title, then an error will show up: Naming conflict.


To avoid this error on installations with missing language strings, use a more specific name when calling the language string...
{{Top}}


$this->title = get_string('simplehtml', ... );
== Authorized Personnel Only ==


That way all blocks will show up with a unique title in the admin area, even if people have not yet succeeded in placing language files in the correct location
Some blocks are useful in some circumstances, but not in others. An example of this would be the "Social Activities" block, which is useful in courses with the "social" course format, but not courses with the "weeks" format. What we need to be able to do is limit our block's availability, so that it can only be selected on pages where its content or abilities are appropriate.


* <div class="variable_title">$this->version</div>
Moodle allows us to declare which page formats a block is available on, and enforces these restrictions as set by the block's developer at all times. The information is given to Moodle as a standard associative array, with each key corresponding to a page format and defining a boolean value (true/false) that declares whether the block should be allowed to appear in that page format.
This variable should hold each block's version number in the form '''YYYYMMDDXX''', as per the convention throughout Moodle. The version number is used by Moodle to detect when a block has been upgraded and it consequently needs to run the block's upgrade code to bring the "old" version of the block's data up to date. The variable is expected to have a valid value after the framework calls the [[Blocks_Howto#method_init| init]] method for each block.
Most blocks do not keep complex data of their own in the database the way that modules do, so in most cases nothing actually happens during a block version upgrade. However, the version number is displayed in the administration interface for blocks. It is good practice therefore to change your block's version number when it gains new functionality or receives important bug fixes, to enable site administrators to easily identify the exact version of the block they are working with.


Appearing throughout the code related to the Blocks API, there is a number of predefined constants that are utilized to avoid the use of "magic numbers" in the code. These constants are:
Notice the deliberate use of the term ''page'' instead of ''course'' in the above paragraph. This is because in Moodle 1.5 and onwards, blocks can be displayed in any page that supports them. The best example of such pages are the course pages, but we are not restricted to them. For instance, the quiz view page (the first one we see when we click on the name of the quiz) also supports blocks.


=== Named constants: ===
The format names we can use for the pages derive from the name of the script which is actually used to display that page. For example, when we are looking at a course, the script is <span class="filename">/course/view.php</span> (this is evident from the browser's address line). Thus, the format name of that page is '''course-view'''. It follows easily that the format name for a quiz view page is '''mod-quiz-view'''. This rule of thumb does have a few exceptions, however:


* <div class="named_constant">BLOCK_TYPE_LIST</div>
# The format name for the front page of Moodle is '''site-index'''.
This is one of the two valid values for the [[Blocks_Howto#variable_content_type| $this->content_type]] member variable of every block. Its value specifies the exact requirements that Moodle will then have for [[Blocks_Howto#variable_content| $this->content]].
# The format name for courses is actually not just '''course-view'''<nowiki>; it is </nowiki>'''course-view-weeks''', '''course-view-topics''', etc.
* <div class="named_constant">BLOCK_TYPE_TEXT</div>
# Even though there is no such page, the format name '''all''' can be used as a catch-all option.
This is one of the two valid values for the [[Blocks_Howto#variable_content_type| $this->content_type]] member variable of every block. Its value specifies the exact requirements that Moodle will then have for [[Blocks_Howto#variable_content| $this->content]].


== Appendix B: Differences in the Blocks API for Moodle versions prior to 1.5 ==
We can include as many format names as we want in our definition of the applicable formats. Each format can be allowed or disallowed, and there are also three more rules that help resolve the question "is this block allowed into this page or not?":


This Appendix will discuss what changes in the Blocks API were introduced by Moodle 1.5 and what steps developers need to take to update their blocks to be fully compatible with Moodle 1.5. Unfortunately, with these changes backward compatibility is broken; this means that blocks from Moodle 1.4 will never work with 1.5 and vice versa.
# Prefixes of a format name will match that format name; for example, '''mod''' will match all the activity modules. '''course-view''' will match any course, regardless of the course format. And finally, '''site''' will also match the front page (remember that its full format name is '''site-index''').
# The more specialized a format name that matches our page is, the higher precedence it has when deciding if the block will be allowed. For example, '''mod''', '''mod-quiz''' and '''mod-quiz-view''' all match the quiz view page. But if all three are present, '''mod-quiz-view''' will take precedence over the other two because it is a better match.
# The character '''<nowiki>*</nowiki>''' can be used in place of any word. For example, '''mod''' and '''mod-*''' are equivalent. At the time of this document's writing, there is no actual reason to utilize this "wildcard matching" feature, but it exists for future usage.
# The order that the format names appear does not make any difference.
All of the above are enough to make the situation sound complex, so let's look at some specific examples. First of all, to have our block appear '''only''' in the site front page, we would use:


=== Class naming conventions changed ===
<syntaxhighlight lang="php">
In Moodle 1.4, all block classes were required to have a name like '''CourseBlock_something''' and the base class from which the derived was '''MoodleBlock'''. This has changed in Moodle 1.5, to bring the naming conventions in line with other object-oriented aspects of Moodle (for example there are classes enrolment_base, resource_base etc). The new block classes should instead be named like '''block_something''' and derive from '''block_base'''. This means that in order to make a block compatible with Moodle 1.5, you need to change the class definition
public function applicable_formats() {
  return array('site-index' => true);
}
</syntaxhighlight>
   
   
class CourseBlock_online_users extends MoodleBlock { ... }
Since '''all''' is missing, the block is disallowed from appearing in ''any'' course format; but then '''site''' is set to TRUE, so it's explicitly allowed to appear in the site front page (remember that '''site''' matches '''site-index''' because it's a prefix).
to
 
For another example, if we wanted to allow the block to appear in all course formats ''except'' social, and also to ''not'' be allowed anywhere but in courses, we would use:
 
<syntaxhighlight lang="php">
public function applicable_formats() {
  return array(
          'course-view' => true,
    'course-view-social' => false);
}
</syntaxhighlight>
 
This time, we first allow the block to appear in all courses and then we explicitly disallow the social format.
For our final, most complicated example, suppose that a block can be displayed in the site front page, in courses (but not social courses) and also when we are viewing any activity module, ''except'' quiz. This would be:
   
   
class block_online_users extends block_base { ... }
<syntaxhighlight lang="php">
An exception to the above is the special case where the block is intended to display a list of items instead of arbitrary text; in this case the block class must derive from class '''block_list''' instead, like this:
public function applicable_formats() {
  return array(
class block_admin extends block_list { ... }
          'site-index' => true,
          'course-view' => true,
  'course-view-social' => false,
                  'mod' => true,
            'mod-quiz' => false
  );
}
</syntaxhighlight>
 
It is not difficult to realize that the above accomplishes the objective if we remember that there is a "best match" policy to determine the end result.
 
{{Top}}
 
== Background Processing ==
 
If you want to do some background processing in your block - use the [[Task API]] to create a background task that can be scheduled to run at regular intervals and can be displayed and configured by an administrator (this is the same regardless of the plugin type).
 
{{Top}}
 
== Additional Content Types ==
 
=== Lists ===
 
In this final part of the guide we will briefly discuss several additional capabilities of Moodle's block system, namely the ability to create blocks that display different kinds of content to the user. The first of these creates a list of options and displays them to the user.  This list is displayed with one item per line, and an optional image (icon) next to the item. An example of such a ''list block'' is the standard Moodle "admin" block, which illustrates all the points discussed in this section.
 
As we have seen so far, blocks use two properties of [[Blocks/Appendix_A#.24this-.3Econtent| $this->content]]: "text" and "footer". The text is displayed as-is as the block content, and the footer is displayed below the content in a smaller font size. List blocks use $this->content->footer in the exact same way, but they ignore $this->content->text.
 
Instead, Moodle expects such blocks to set two other properties when the [[Blocks/Appendix_A#get_content.28.29| get_content()]] method is called: $this->content->items and $this->content->icons. $this->content->items should be a numerically indexed array containing elements that represent the HTML for each item in the list that is going to be displayed. Usually these items will be HTML anchor tags which provide links to some page. $this->content->icons should also be a numerically indexed array, with exactly as many items as $this->content->items has. Each of these items should be a fully qualified HTML <img> tag, with "src", "height", "width" and "alt" attributes. Obviously, it makes sense to keep the images small and of a uniform size. We would recommend standard 16x16 images for this purpose.
 
In order to tell Moodle that we want to have a list block instead of the standard text block, we need to make a small change to our block class declaration. Instead of extending class '''block_base''', our block will extend class '''block_list'''. For example:
 
<syntaxhighlight lang="php">
class block_my_menu extends block_list {
    // The init() method does not need to change at all
}
</syntaxhighlight>


=== Constructor versus init() ===
In addition to making this change, we must of course also modify the [[Blocks/Appendix_A#get_content.28.29| get_content()]] method to construct the [[Blocks/Appendix_A#.24this-.3Econtent| $this->content]] variable as discussed above:


In Moodle 1.4, in each block class it was mandatory to define a constructor which accepted a course data record as an argument (the example is from the actual Online Users block):
<syntaxhighlight lang="php">
public function get_content() {
  if ($this->content !== null) {
    return $this->content;
  }
   
   
    function CourseBlock_online_users ($course) {
  $this->content        = new stdClass;
        $this->title = get_string('blockname','block_online_users');
  $this->content->items  = array();
        $this->content_type = BLOCK_TYPE_TEXT;
  $this->content->icons  = array();
        $this->course = $course;
  $this->content->footer = 'Footer here...';
        $this->version = 2004052700;
    }
In contrast, Moodle 1.5 does away with the constructor and instead requires you to define an init() method that takes no arguments:
   
   
    function init() {
  $this->content->items[] = html_writer::tag('a', 'Menu Option 1', array('href' => 'some_file.php'));
        $this->title = get_string('blockname','block_online_users');
  $this->content->icons[] = html_writer::empty_tag('img', array('src' => 'images/icons/1.gif', 'class' => 'icon'));
        $this->version = 2004111600;
 
    }
  // Add more list items here
Of course, this leaves you without access to the $course object, which you might actually need. Since that's probably going to be needed inside [[Blocks_Howto#method_get_content| get_content]], the way to retrieve it is by using this code:
   
   
    $course = get_record('course', 'id', $this->instance->pageid);
  return $this->content;
If you are going to need access to $course from inside other methods in addition to [[Blocks_Howto#method_get_content| get_content]], you might fetch the $course object inside the [[Blocks_Howto#method_specialization| specialization]] method and save it as a class variable for later use, in order to avoid executing the same query multiple times:
}
</syntaxhighlight>
    function specialization() {
 
        $this->course = get_record('course', 'id', $this->instance->pageid);
To summarise, if we want to create a list block instead of a text block, we just need to change the block class declaration and the [[Blocks/Appendix_A#get_content.28.29| get_content()]] method. Adding the mandatory [[Blocks/Appendix_A#init.28.29| init()]] method as discussed earlier will then give us our first list block in no time!
    }
 
=== Trees ===
 
As of 23rd December 2011, this functionality remains inoperable in all Moodle 2.x versions. It appears that classes are missing from the code base. This has been added to the tracker at the URL below. Please upvote this issue if you require this functionality.
 
[http://tracker.moodle.org/browse/MDL-28289 Visit this issue on the tracker @ MDL28289]
 
{{Top}}
 
== Database support ==
In case we need to have a database table that holds some specific information used within our block, we will need to create the file ''/blocks/simplehtml/'''install.xml''''' with the table schema contained within it.
 
To create the install.xml file, use the [[XMLDB editor]]. See [[Database_FAQ#XMLDB|Database FAQ > XMLDB]] for further details.
 
Up-to-date documentation on upgrading our block, as well as providing new capabilities and events to the system, can be found under [https://docs.moodle.org/dev/Installing_and_upgrading_plugin_database_tables#install.php Installing and Upgrading Plugin Database Tables]


=== Blocks with configuration ===
== See also ==
In Moodle 1.4, blocks could only have what are now (in Moodle 1.5) called "global configuration" options, to differentiate from the new "instance configuration" options. If your block has support for configuration, you will need to take these steps:
* [[Blocks Advanced]] A continuation of this tutorial.
## Rename your <span class="filename">config.html</span> file to <span class="filename">config_global.html</span>.
* [http://dev.moodle.org/mod/resource/view.php?id=48 Unit 7 of the Introduction to Moodle Programming course] is a follow up to this course. (But you should follow the forum discussions of that course closely as there are still some bugs and inconsistencies.)
## Edit the newly renamed file and completely remove the <form> tag (Moodle now wraps your configuration in a form automatically).
* Daniel Neis Araujo's [https://github.com/danielneis/moodle-block_newblock NEWBLOCK template].
## If you are using any HTML <input> tags other than those that directly affect your configuration (for example, "sesskey"), REMOVE those too (Moodle will add them automatically as required).
## If you have overridden '''print_config''', rename your method to '''config_print'''.
## If you have overridden '''handle_config''', rename your method to '''config_save'''.
=== Blocks with customized applicable formats ===
The correct way to specify the formats you want to allow or disallow your block to exist has been reworked for Moodle 1.5 to take account of the fact that blocks are no longer restricted to just courses. To have a block retain its intended behavior, you must change these format names (array keys in the return value of [[Blocks_Howto#method_applicable_formats| applicable_formats]]) if they are used in your block:
#* '''social''' should become '''course-view-social'''
#* '''topics''' should become '''course-view-topics'''
#* '''weeks''' should become '''course-view-weeks'''
You should also keep in mind that there is now the possibility of blocks being displayed in other pages too, like the introductory page that users see when they enter an activity module. You might therefore need to make the specification for applicable formats more restrictive to keep your block out of pages it is not supposed to be shown in. Also, there are subtle changes to the way that the final decision to allow or disallow a block is made. For the technical details refer to the definition of [[Blocks_Howto#method_applicable_formats| applicable_formats]], and for a more extended example read [[Blocks_Howto#section_authorized_personnel_only| the section dedicated to this subject]].
That's everything; your block will now be ready for use in Moodle 1.5!


[[Category:Blocks]]
== Appendices ==


[[es:Desarrollo de bloques]]
The appendices have been moved to separate pages:


== Creating Database Tables for Blocks ==
* Appendix A: [[Blocks/Appendix A|''block_base'' Reference]]


'''The following describes what to do in Moodle <= 1.6. For Moodle >= 1.7, you need to use [[XMLDB_Documentation|XMLDB]], that is, create an install.xml file, instead of *.sql files.'''
{{Top}}


You can easily create a database table for your block by adding
two files mysql.sql and postgres7.sql to a subdirectory db/ of
your block. The tables HAVE TO be named the same way as the
block (e.g. block_rss2_feeds) otherwise moodle will not be able
to drop the table upon removal of the block from the system.
Here is an example for mysql.sql:


CREATE TABLE prefix_rss2_feeds (
[[Category:Blocks]]
`id` int(11) NOT NULL auto_increment,
[[Category:Tutorial]]
`userid` int(11) NOT NULL default '0',
`title` text NOT NULL default '',
`description` text NOT NULL default '',
`url` varchar(255) NOT NULL default '',
`pingbacktokenurl` varchar(255) NOT NULL default '',
PRIMARY KEY  (`id`)
) TYPE=MyISAM  COMMENT='Remote news feed information.';


Pay attention that, furthermore, you might want to add a
[[es:Desarrollo de bloques]]
mysql.php and postgres7.php page that contains update
[[ja:開発:ブロック]]
routines for upgrading the database tables with evolving
[[:en:Blocks|Blocks]]
version numbers of the block. In case you use that be sure
that you provide the necessary structure (again function
name should be like the block name + "_upgrade"!).
Here is an example:


function rss_pingback_upgrade( $oldversion ) {
[[Category:Plugins]]
    global $CFG;
    if ($oldversion < 2003111500) {
      # Do something ...
    }
    return true;
}

Latest revision as of 07:31, 7 June 2022

Important:

This content of this page has been updated and migrated to the new Moodle Developer Resources. The information contained on the page should no longer be seen up-to-date.

Why not view this page on the new site and help us to migrate more content to the new site!

A Step-by-step Guide To Creating Blocks

Original Author: Jon Papaioannou (pj@moodle.org)

Updated to Moodle 2.0 and above by: Greg J Preece (greg.preece@blackboard.com)

Moodle 2.0


The present document serves as a guide to developers who want to create their own blocks for use in Moodle. It applies to the 2.0 development version of Moodle (and any newer) only, as the blocks API changed significantly enough to warrant new documentation. Those wishing to read the old tutorial for Moodles 1.5 to 1.9 can find it under Blocks for 1.5 to 1.9.

The guide is written as an interactive course which aims to develop a configurable, multi-purpose block that displays arbitrary HTML. It's targeted mainly at people with little experience with Moodle or programming in general and aims to show how easy it is to create new blocks for Moodle. A certain small amount of PHP programming knowledge is still required, though.

Experienced developers and those who just want a programmer's reference text should refer to Appendix A because the main guide has a rather low concentration of pure information in the text.

Basic Concepts

Through this guide, we will be following the creation of an "HTML" block from scratch in order to demonstrate most of the block features at our disposal. Our block will be named "SimpleHTML". This does not constrain us regarding the name of the actual directory on the server where the files for our block will be stored, but for consistency we will follow the practice of using the lowercased form "simplehtml" in any case where such a name is required.

Whenever we refer to a file or directory name which contains "simplehtml", it's important to remember that only the "simplehtml" part is up to us to change; the rest is standardised and essential for Moodle to work correctly.

Whenever a file's path is mentioned in this guide, it will always start with a slash. This refers to the Moodle home directory; all files and directories will be referred to with respect to that directory.

Ready, Set, Go!

To define a "block" in Moodle, in the most basic case we need to provide just four PHP files. Remember, in this example we are creating a block called 'simplehtml', replace 'simplehtml' with the name of your custom block. The four files should be located in blocks/simplehtml and are:

block_simplehtml.php

This file will hold the class definition for the block, and is used both to manage it as a plugin and to render it onscreen.

We start by creating the main object file, 'block_simplehtml.php'. We then begin coding the block:

<?php
class block_simplehtml extends block_base {
    public function init() {
        $this->title = get_string('simplehtml', 'block_simplehtml');
    }
    // The PHP tag and the curly bracket for the class definition 
    // will only be closed after there is another function added in the next section.
}

The first line is our block class definition; it must be named exactly in the manner shown. Again, only the "simplehtml" part can (and indeed must) change; everything else is standardised.

Our class is then given a small method: init(). This is essential for all blocks, and its purpose is to give values to any class member variables that need instantiating.

In this very basic example, we only want to set $this->title, which is the title displayed in the header of our block. We can set it to whatever we like; in this case it's set to read the actual title from the language file mentioned below, which is then distributed along with the block. I'll skip ahead a bit here and say that if you want your block to display no title at all, then you should set this to any descriptive value you want (but not make it an empty string). We will later see how to disable the title's display.

db/access.php

This file will hold the new capabilities created by the block.

Moodle 2.4 onwards introduced the capabilities addinstance and myaddinstance for core blocks. They were introduced so that it was possible to control the use of individual blocks. These capabilities should also be added to your custom block, so in this case to the file blocks/simplehtml/db/access.php. If your block is not going to be used in the 'My Moodle page' (ie, your applicable_formats function (discussed later) has 'my' set to false.) then the myaddinstance capability does not need to be given to any user, but it must still be defined here otherwise you will get errors on certain pages. The following is the capabilities array and how it should look for any new blocks.

<?php
    $capabilities = array(

    'block/simplehtml:myaddinstance' => array(
        'captype' => 'write',
        'contextlevel' => CONTEXT_SYSTEM,
        'archetypes' => array(
            'user' => CAP_ALLOW
        ),

        'clonepermissionsfrom' => 'moodle/my:manageblocks'
    ),

    'block/simplehtml:addinstance' => array(
        'riskbitmask' => RISK_SPAM | RISK_XSS,

        'captype' => 'write',
        'contextlevel' => CONTEXT_BLOCK,
        'archetypes' => array(
            'editingteacher' => CAP_ALLOW,
            'manager' => CAP_ALLOW
        ),

        'clonepermissionsfrom' => 'moodle/site:manageblocks'
    ),
);

lang/en/block_simplehtml.php

This is the English language file for your block. If you are not an English speaker, you can replace 'en' with your appropriate language code (but even then you will need english folder !). All language files for blocks go under the /lang subfolder of the block's installation folder.

Moodle 2.0 and above require a name for our plugin to show in the upgrading page. We set this value, along with the capabilities we created and any other language strings we wish to use within the block, in a language package as previously mentioned (the same file where we put our string for the plugin title).

The capabilities added above need descriptions for pages that allow setting of capabilities. These should also be added to the language file.

<?php
$string['pluginname'] = 'Simple HTML block';
$string['simplehtml'] = 'Simple HTML';
$string['simplehtml:addinstance'] = 'Add a new simple HTML block';
$string['simplehtml:myaddinstance'] = 'Add a new simple HTML block to the My Moodle page';

version.php

This file will hold version information for the plugin, along with other advanced parameters (not covered here - see version.php if you want more details).

Prior to Moodle 2.0, version details for blocks were stored as class fields; as of Moodle 2.0 these are stored in a file called version.php, stored under /blocks/simplehtml/version.php. The version file is very simple indeed, containing only a few field definitions, depending on your needs. Here is an example:

<?php
$plugin->component = 'block_simplehtml';  // Recommended since 2.0.2 (MDL-26035). Required since 3.0 (MDL-48494)
$plugin->version = 2011062800;  // YYYYMMDDHH (year, month, day, 24-hr time)
$plugin->requires = 2010112400; // YYYYMMDDHH (This is the release version for Moodle 2.0)

This file contains object field definitions that denote the full frankenstyle component name in the form of plugintype_pluginname and the version number of the block, along with the minimum version of Moodle that must be installed in order to use it. Please note that the object being used here is always called $plugin, and that you do not need to create this object yourself within the version file. Note also we don't include a closing "?>" tag. This is intentional, and a workaround for whitespace issues.

The exact Moodle version of a release can be found in Releases.


Back to top of page ↑


I Just Hear Static

In order to get our block to actually display something on screen, we need to add one more method to our class (before the final closing brace in our file) inside of the block_simplehtml.php script. The new code is:

  
  public function get_content() {
    if ($this->content !== null) {
      return $this->content;
    }

    $this->content         =  new stdClass;
    $this->content->text   = 'The content of our SimpleHTML block!';
    $this->content->footer = 'Footer here...';
 
    return $this->content;
}

Add your block to the front page! Don't forget (especially if you're a new Moodle user) to add your block to the front page. Turn Editing On, and add your block to the page.

It can't get any simpler than that, can it? Let's dissect this method to see what's going on...

First of all, there is a check that returns the current value of $this->content if it's not NULL; otherwise we proceed with "computing" it. Since the computation is potentially a time-consuming operation and it will be called several times for each block (Moodle works that way internally), we take a precaution and include this time-saver. Supposing the content had not been computed before (it was NULL), we then define it from scratch. The code speaks for itself there, so there isn't much to say. Just keep in mind that we can use HTML both in the text and in the footer, if we want to.

It's worth mentioning that this is not the only type of content a block can output. You can also create lists and hierarchical trees, which are better suited for certain types of output, such as menus. These different content types have an impact on the content object and how it is constructed. For more information, see Appendix A

At this point our block should be capable of being automatically installed in Moodle and added to courses; visit your administration page to install it (Click "Notifications" under the Site Administration Block) and after seeing it in action come back to continue our tutorial.

Configure That Out

The current version of our block doesn't really do much; it just displays a fixed message, which is not very useful. What we'd really like to do is allow the teachers to customize what goes into the block. This, in block-speak, is called "instance configuration". Basic instance configuration is automatic in Moodle 2.0; if you put any page with blocks on it into "editing mode", you will notice that each block has an edit button in its title bar. Clicking on this will take you to the block configuration form. The settings that Moodle adds to this form by default relate to the block's appearance and position on Moodle pages.

We can extend this configuration form, and add custom preferences fields, so that users can better tailor our block to a given task or page. To extend the configuration form, create the file /blocks/simplehtml/edit_form.php, and fill it with the following code:

<?php

class block_simplehtml_edit_form extends block_edit_form {
        
    protected function specific_definition($mform) {
        
        // Section header title according to language file.
        $mform->addElement('header', 'config_header', get_string('blocksettings', 'block'));

        // A sample string variable with a default value.
        $mform->addElement('text', 'config_text', get_string('blockstring', 'block_simplehtml'));
        $mform->setDefault('config_text', 'default value');
        $mform->setType('config_text', PARAM_RAW);        

    }
}

The first line declares a class that inherits from block_edit_form, and this allows Moodle to identify the code to execute in the configuration page. The specific_definition() method is where your form elements are defined, and these take the same format as with the standard Moodle form library. Within our specific_definition method, we have created a header, and an input field which will accept text to be used within the block.

NOTE: You might want extend language file for your block (lang/en/block_simplehtml.php) and add a value for "blockstring" defined in a code above.

IMPORTANT: All your field names need to start with "config_", otherwise they will not be saved and will not be available within the block via $this->config.

So once our instance configuration form has been saved, we can use the inputted text within the block like so:

if (! empty($this->config->text)) {
    $this->content->text = $this->config->text;
}

Note that $this->config is available in all block methods except init(). This is because init() is called immediately as the block is being created, with the purpose of setting things up, so $this->config has not yet been instantiated.

Note about Checkbox: You cannot use the 'checkbox' element in the form (once set it will stay set). You must use advcheckbox instead.

Back to top of page ↑


The Specialists

Implementing instance configuration for the block's contents was good enough to whet our appetite, but who wants to stop there? Why not customize the block's title, too?

Why not, indeed. Well, our first attempt to achieve this is natural enough: let's add another field to /blocks/simplehtml/edit_form.php. Here goes:

    // A sample string variable with a default value.
    $mform->addElement('text', 'config_title', get_string('blocktitle', 'block_simplehtml'));
    $mform->setDefault('config_title', 'default value');
    $mform->setType('config_title', PARAM_TEXT);

We save the edited file, go to a course, edit the title of the block and... nothing happens! The instance configuration is saved correctly, all right (editing it once more proves that) but it's not being displayed. All we get is just the simple "SimpleHTML" title.

That's not too weird, if we think back a bit. Do you remember that init() method, where we set $this->title? We didn't actually change its value from then, and $this->title is definitely not the same as $this->config->title (to Moodle, at least). What we need is a way to update $this->title with the value in the instance configuration. But as we said a bit earlier, we can use $this->config in all methods except init()! So what can we do?

Let's pull out another ace from our sleeve, and add this small method to our block class:

public function specialization() {
    if (isset($this->config)) {
        if (empty($this->config->title)) {
            $this->title = get_string('defaulttitle', 'block_simplehtml');            
        } else {
            $this->title = $this->config->title;
        }

        if (empty($this->config->text)) {
            $this->config->text = get_string('defaulttext', 'block_simplehtml');
        }    
    }
}

Aha, here's what we wanted to do all along! But what's going on with the specialization() method?

This "magic" method has actually a very nice property: it's guaranteed to be automatically called by Moodle as soon as our instance configuration is loaded and available (that is, immediately after init() is called). That means before the block's content is computed for the first time, and indeed before anything else is done with the block. Thus, providing a specialization() method is the natural choice for any configuration data that needs to be acted upon or made available "as soon as possible", as in this case.

Back to top of page ↑


Now You See Me, Now You Don't

Now would be a good time to mention another nifty technique that can be used in blocks, and which comes in handy quite often. Specifically, it may be the case that our block will have something interesting to display some of the time; but in some other cases, it won't have anything useful to say. An example here would be the "Recent Activity" block, in the case where no recent activity in fact exists.

However in that case the block chooses to explicitly inform you of the lack of said activity, which is arguably useful. It would be nice, then, to be able to have our block "disappear" if it's not needed to display it.

This is indeed possible, and the way to do it is to make sure that after the get_content() method is called, the block has no content to display. This means that all fields in $this->content should be equal to the empty string (''). In the case of our HTML-based block, these fields are $this->content->text and $this->content->footer. Moodle performs this check by calling the block's is_empty() method, and if the block is indeed empty then it is not displayed at all.

Note that the exact value of the block's title and the presence or absence of a hide_header() method do not affect this behavior. A block is considered empty if it has no content, irrespective of anything else.

Back to top of page ↑


We Are Legion

Right now our block is fully configurable, both in title and content. It's so versatile, in fact, that we could make pretty much anything out of it. It would be really nice to be able to add multiple blocks of this type to a single course. And, as you might have guessed, doing that is as simple as adding another small method to our block class:

public function instance_allow_multiple() {
  return true;
}

This tells Moodle that it should allow any number of instances of the SimpleHTML block in any course. After saving the changes to our file, Moodle immediately allows us to add multiple copies of the block without further ado!

Please note that even if a block itself allows multiple instances in the same page, the administrator still has the option of disallowing such behavior. This setting can be set separately for each block from the Administration / Configuration / Blocks page.

Back to top of page ↑


The Effects of Globalization

Configuring each block instance with its own personal data is cool enough, but sometimes administrators need some way to "touch" all instances of a specific block at the same time. In the case of our SimpleHTML block, a few settings that would make sense to apply to all instances aren't that hard to come up with.

For example, we might want to limit the contents of each block to only so many characters, or we might have a setting that filters HTML out of the block's contents, only allowing pure text in. Granted, such a feature wouldn't win us any awards for naming our block "SimpleHTML" but some tormented administrator somewhere might actually find it useful.

This kind of configuration is called "global configuration" and applies only to a specific block type (all instances of that block type are affected, however). Implementing such configuration for our block is quite similar to implementing the instance configuration. We will now see how to implement the second example, having a setting that only allows text and not HTML in the block's contents. To enable global configuration for the block, we create a new file, /blocks/simplehtml/settings.php, and populate it with form field definitions for each setting, which Moodle will use to generate and handle a global settings form. This is quite similar in concept to how we generated the instance configuration form earlier, but the actual code used to generate the form and fields is somewhat different.

Place the following in your settings.php file:

<?php
$settings->add(new admin_setting_heading(
            'headerconfig',
            get_string('headerconfig', 'block_simplehtml'),
            get_string('descconfig', 'block_simplehtml')
        ));

$settings->add(new admin_setting_configcheckbox(
            'simplehtml/Allow_HTML',
            get_string('labelallowhtml', 'block_simplehtml'),
            get_string('descallowhtml', 'block_simplehtml'),
            '0'
        ));

As you can see, to generate a global configuration form, we simply create admin setting objects and add them to an array. This array is then stepped over to create the settings form, and the inputted data is automatically saved to the database. Full details of the setting types available and how to add them can be found under Admin_settings#Individual_settings.

We've now created a header and checkbox form element to accept configuration details from the site admin. You should pay extra attention to the name of our checkbox element, 'simplehtml/Allow_HTML' , as it specifies not only the name of the configuration option, but also how it should be stored. If you simply specify a name for the config option, it will be stored in the global $CFG object, and in the <prefix>_config database table. This will make your config variable available immediately via $CFG without requiring an additional database call, but will also increase the size of the $CFG object. In addition, we must prefix the variable with the name of our block, otherwise we run the risk of our config variable sharing its name with a similar variable in another plugin, or within Moodle itself.

The preferred method of storing your block's configuration data is to prefix each config variable name in your settings.php file with your block's name, followed by a slash ( / ), and the name of the configuration variable, as we have done above. If you write your settings.php file in this way, then your variables will be stored in the <prefix>_config_plugin table, under your block's name. Your config data will still be available via a get_config() call, and name collision will be impossible between plugins.

Finally, if you're wondering why there are two language tags specified for each element, the first tag is for the element's label or primary text, and the second tag is for its description. And that's it. Pretty easy, huh?

Enabling Global Configuration

Moodle 2.4 Since version 2.4, the following line must be added to the /blocks/simplehtml/block_simplehtml.php file in order to enable global configuration:

    function has_config() {return true;}

This line tells Moodle that the block has a settings.php file.


NOTE FOR UPGRADERS

You'll notice that the settings.php file and parsed element names replaces Moodle's old storage method, wherein it would send all the configuration data to your block's config_save() method, and allow you to override how the data is saved. The config_save() method is no longer used in Moodle 2.x; however the instance_config_save() method is very much alive and well, as you will see shortly.

Back to top of page ↑


Accessing Global Config Data

Now that we have global data defined for the plugin, we need to know how to access it within our code. If you saved your config variables in the global namespace, you can access them from the global $CFG object, like so:

$allowHTML = $CFG->Allow_HTML;

If, as recommended, you saved your config variables in a custom namespace for your block, then you can access them via a call to get_config():

$allowHTML = get_config('simplehtml', 'Allow_HTML');

Back to top of page ↑


Rolling It All Together

OK, so we now have an instance configuration form that allows users to enter custom content text for a block, and a global configuration option that dictates whether or not that user should be allowed to enter HTML tags as part of the content. Now we just need to tie the two together. But if Moodle takes care of the form processing for our instance configuration in edit_form.php, how can we capture it and remove the HTML tags where required?

Well, fortunately, there is a way this can be done. By overriding the instance_config_save() method in our block class, we can modify the way in which instance configuration data is stored after input. The default implementation is as follows:

public function instance_config_save($data, $nolongerused = false) {
  $data = stripslashes_recursive($data);
  $this->config = $data;
  return set_field('block_instance', 
                   'configdata',
                    base64_encode(serialize($data)),
                   'id', 
                   $this->instance->id);
}

This may look intimidating at first (what's all this stripslashes_recursive() and base64_encode() and serialize() stuff?) but do not despair; we won't have to touch any of it. We will only add some extra validation code in the beginning and then instruct Moodle to additionally call this default implementation to do the actual storing of the data. Specifically, we will add a method to our class which goes like this:

public function instance_config_save($data,$nolongerused =false) {
  if(get_config('simplehtml', 'Allow_HTML') == '1') {
    $data->text = strip_tags($data->text);
  }

  // And now forward to the default implementation defined in the parent class
  return parent::instance_config_save($data,$nolongerused);
}

(This example assumes you are using a custom namespace for the block.)

At last! Now the administrator has absolute power of life and death over what type of content is allowed in our "SimpleHTML" block! Absolute? Well... not exactly. In fact, if we think about it for a while, it will become apparent that if at some point in time HTML is allowed and some blocks have saved their content with HTML included, and afterwards the administrator changes the setting to "off", this will only prevent subsequent content changes from including HTML. Blocks which already had HTML in their content would continue to display it!

Following that train of thought, the next stop is realizing that we wouldn't have this problem if we had chosen the lazy approach a while back, because in that case we would "sanitize" each block's content just before it was displayed.

The only thing we can do with the eager approach is strip all the tags from the content of all SimpleHTML instances as soon as the admin setting is changed to "HTML off"; but even then, turning the setting back to "HTML on" won't bring back the tags we stripped away. On the other hand, the lazy approach might be slower, but it's more versatile; we can choose whether to strip or keep the HTML before displaying the content, and we won't lose it at all if the admin toggles the setting off and on again. Isn't the life of a developer simple and wonderful?

Exercise

We will let this part of the tutorial come to a close with the obligatory exercise for the reader: In order to have the SimpleHTML block work "correctly", find out how to strengthen the eager approach to strip out all tags from the existing configuration of all instances of our block, or go back and implement the lazy approach instead. (Hint: Do that in the get_content() method.)


Back to top of page ↑


Eye Candy

Our block is just about complete functionally, so now let's take a look at some of the tricks we can use to make its behavior customized in a few more useful ways.

First of all, there are a couple of ways we can adjust the visual aspects of our block. For starters, it might be useful to create a block that doesn't display a header (title) at all. You can see this effect in action in the Course Description block that comes with Moodle. This behavior is achieved by, you guessed it, adding one more method to our block class:

public function hide_header() {
  return true;
}

One more note here: we cannot just set an empty title inside the block's init() method; it's necessary for each block to have a unique, non-empty title after init() is called so that Moodle can use those titles to differentiate between all of the installed blocks.

Next, we can affect some properties of the actual HTML that will be used to print our block. Each block is fully contained within a <div> or <table> elements, inside which all the HTML for that block is printed. We can instruct Moodle to add HTML attributes with specific values to that container. This is generally done to give us freedom to customize the end result using CSS (this is in fact done by default as we'll see below).

The default behavior of this feature in our case will modify our block's "class" HTML attribute by appending the value "block_simplehtml" (the prefix "block_" followed by the name of our block, lowercased). We can then use that class to make CSS selectors in our theme to alter this block's visual style (for example, ".block_simplehtml { border: 1px black solid}").

To change the default behavior, we will need to define a method which returns an associative array of attribute names and values. For example:

public function html_attributes() {
    $attributes = parent::html_attributes(); // Get default values
    $attributes['class'] .= ' block_'. $this->name(); // Append our class to class attribute
    return $attributes;
}

This results in the block having all its normal HTML attributes, as inherited from the base block class, plus our additional class name. We can now use this class name to change the style of the block, add JavaScript events to it via YUI, and so on. And for one final elegant touch, we have not set the class to the hard-coded value "block_simplehtml", but instead used the name() method to make it dynamically match our block's name.

Back to top of page ↑


Authorized Personnel Only

Some blocks are useful in some circumstances, but not in others. An example of this would be the "Social Activities" block, which is useful in courses with the "social" course format, but not courses with the "weeks" format. What we need to be able to do is limit our block's availability, so that it can only be selected on pages where its content or abilities are appropriate.

Moodle allows us to declare which page formats a block is available on, and enforces these restrictions as set by the block's developer at all times. The information is given to Moodle as a standard associative array, with each key corresponding to a page format and defining a boolean value (true/false) that declares whether the block should be allowed to appear in that page format.

Notice the deliberate use of the term page instead of course in the above paragraph. This is because in Moodle 1.5 and onwards, blocks can be displayed in any page that supports them. The best example of such pages are the course pages, but we are not restricted to them. For instance, the quiz view page (the first one we see when we click on the name of the quiz) also supports blocks.

The format names we can use for the pages derive from the name of the script which is actually used to display that page. For example, when we are looking at a course, the script is /course/view.php (this is evident from the browser's address line). Thus, the format name of that page is course-view. It follows easily that the format name for a quiz view page is mod-quiz-view. This rule of thumb does have a few exceptions, however:

  1. The format name for the front page of Moodle is site-index.
  2. The format name for courses is actually not just course-view; it is course-view-weeks, course-view-topics, etc.
  3. Even though there is no such page, the format name all can be used as a catch-all option.

We can include as many format names as we want in our definition of the applicable formats. Each format can be allowed or disallowed, and there are also three more rules that help resolve the question "is this block allowed into this page or not?":

  1. Prefixes of a format name will match that format name; for example, mod will match all the activity modules. course-view will match any course, regardless of the course format. And finally, site will also match the front page (remember that its full format name is site-index).
  2. The more specialized a format name that matches our page is, the higher precedence it has when deciding if the block will be allowed. For example, mod, mod-quiz and mod-quiz-view all match the quiz view page. But if all three are present, mod-quiz-view will take precedence over the other two because it is a better match.
  3. The character * can be used in place of any word. For example, mod and mod-* are equivalent. At the time of this document's writing, there is no actual reason to utilize this "wildcard matching" feature, but it exists for future usage.
  4. The order that the format names appear does not make any difference.

All of the above are enough to make the situation sound complex, so let's look at some specific examples. First of all, to have our block appear only in the site front page, we would use:

 
public function applicable_formats() {
  return array('site-index' => true);
}

Since all is missing, the block is disallowed from appearing in any course format; but then site is set to TRUE, so it's explicitly allowed to appear in the site front page (remember that site matches site-index because it's a prefix).

For another example, if we wanted to allow the block to appear in all course formats except social, and also to not be allowed anywhere but in courses, we would use:

 
public function applicable_formats() {
  return array(
           'course-view' => true, 
    'course-view-social' => false);
}

This time, we first allow the block to appear in all courses and then we explicitly disallow the social format. For our final, most complicated example, suppose that a block can be displayed in the site front page, in courses (but not social courses) and also when we are viewing any activity module, except quiz. This would be:

public function applicable_formats() {
  return array(
           'site-index' => true,
          'course-view' => true, 
   'course-view-social' => false,
                  'mod' => true, 
             'mod-quiz' => false
  );
}

It is not difficult to realize that the above accomplishes the objective if we remember that there is a "best match" policy to determine the end result.

Back to top of page ↑


Background Processing

If you want to do some background processing in your block - use the Task API to create a background task that can be scheduled to run at regular intervals and can be displayed and configured by an administrator (this is the same regardless of the plugin type).

Back to top of page ↑


Additional Content Types

Lists

In this final part of the guide we will briefly discuss several additional capabilities of Moodle's block system, namely the ability to create blocks that display different kinds of content to the user. The first of these creates a list of options and displays them to the user. This list is displayed with one item per line, and an optional image (icon) next to the item. An example of such a list block is the standard Moodle "admin" block, which illustrates all the points discussed in this section.

As we have seen so far, blocks use two properties of $this->content: "text" and "footer". The text is displayed as-is as the block content, and the footer is displayed below the content in a smaller font size. List blocks use $this->content->footer in the exact same way, but they ignore $this->content->text.

Instead, Moodle expects such blocks to set two other properties when the get_content() method is called: $this->content->items and $this->content->icons. $this->content->items should be a numerically indexed array containing elements that represent the HTML for each item in the list that is going to be displayed. Usually these items will be HTML anchor tags which provide links to some page. $this->content->icons should also be a numerically indexed array, with exactly as many items as $this->content->items has. Each of these items should be a fully qualified HTML <img> tag, with "src", "height", "width" and "alt" attributes. Obviously, it makes sense to keep the images small and of a uniform size. We would recommend standard 16x16 images for this purpose.

In order to tell Moodle that we want to have a list block instead of the standard text block, we need to make a small change to our block class declaration. Instead of extending class block_base, our block will extend class block_list. For example:

 
class block_my_menu extends block_list {
     // The init() method does not need to change at all
}

In addition to making this change, we must of course also modify the get_content() method to construct the $this->content variable as discussed above:

 
public function get_content() {
  if ($this->content !== null) {
    return $this->content;
  }
 
  $this->content         = new stdClass;
  $this->content->items  = array();
  $this->content->icons  = array();
  $this->content->footer = 'Footer here...';
 
  $this->content->items[] = html_writer::tag('a', 'Menu Option 1', array('href' => 'some_file.php'));
  $this->content->icons[] = html_writer::empty_tag('img', array('src' => 'images/icons/1.gif', 'class' => 'icon'));

  // Add more list items here
 
  return $this->content;
}

To summarise, if we want to create a list block instead of a text block, we just need to change the block class declaration and the get_content() method. Adding the mandatory init() method as discussed earlier will then give us our first list block in no time!

Trees

As of 23rd December 2011, this functionality remains inoperable in all Moodle 2.x versions. It appears that classes are missing from the code base. This has been added to the tracker at the URL below. Please upvote this issue if you require this functionality.

Visit this issue on the tracker @ MDL28289

Back to top of page ↑


Database support

In case we need to have a database table that holds some specific information used within our block, we will need to create the file /blocks/simplehtml/install.xml with the table schema contained within it.

To create the install.xml file, use the XMLDB editor. See Database FAQ > XMLDB for further details.

Up-to-date documentation on upgrading our block, as well as providing new capabilities and events to the system, can be found under Installing and Upgrading Plugin Database Tables

See also

Appendices

The appendices have been moved to separate pages:

Back to top of page ↑ Blocks