Note:

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

Blocks/Appendix A

From MoodleDocs

Appendix A: block_base Reference

Main article: Blocks

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.

The methods are divided into three categories:

  1. those you may use and override in your block;
  2. those that you may not override but might want to use;
  3. those internal methods that should neither be used nor overridden.

In each category, methods are presented in alphabetical order.

Methods you can freely use and override:

Moodle1.7

after_install()

function after_install() {
}

Available between Moodle 1.7 and Moodle 1.9

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.

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

Moodle 2.0


The after_install() method is no longer present in Moodle 2.0. Instead, you should use an install.php file, located within your /blocks/<yourblock>/db/ folder, to perform these actions.

applicable_formats()

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,
  );
}

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. 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:

  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.

The format name for the Dashboard (or My Moodle in earlier versions) is my.

before_delete()

function before_delete() {
}

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 deleted. It allows block authors to perform any necessary cleanup - removing temporary files and so on - before the block is deleted.

instance_create()

function instance_create() {
}

Available in Moodle 1.5 and later

Do any additional initialization you may need at the time a new block instance is created.

instance_copy()

function instance_copy($fromid) {
}

Available in Moodle 2.9 and later

Copy any block-specific data when copying to a new block instance.

instance_delete()

function instance_delete() {
}

Available in Moodle 1.5 and later

Delete everything related to this instance if you have been using persistent storage other than the configdata field.

config_print()

function config_print() {
  // 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;
}

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 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.

config_save()

function config_save($data) {
  // Default behaviour: 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. 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.

You should return a boolean value denoting the success or failure of your method's actions.

get_content()

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 $this->content variable of your block. For details of how to do this, see the $this->content section below.

has_config()

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. To actually implement the configuration interface, you will either need to rely on the default config_print() method or override it. The full guide contains more information on this.

hide_header()

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.

html_attributes()

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.

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;
}

init()

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 $this->title and $this->version (which is used by Moodle for performing automatic updates when available).

No return value is expected from this method.

instance_allow_config()

Moodle1.9


function instance_allow_config() {
  return FALSE;
}

Available in Moodle 1.5 through 1.9.

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 more information.

This method's return value is irrelevant if instance_allow_multiple() returns true; it is assumed that if you want multiple instances then each instance needs its own configuration.

instance_allow_multiple()

function instance_allow_multiple() {
  // Are you going to allow multiple instances of each block?
  // If yes, then it is assumed that the block WILL USE per-instance configuration
  return FALSE;
}

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 more information.

instance_config_print()

function instance_config_print() {
  // 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;
}

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 config_print(), it will be enclosed in a HTML form automatically. You only need to provide a way to submit that form.

You should return a boolean value denoting the success or failure of your method's actions.

instance_config_save()

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.

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 instance_config_commit().

You should return a boolean value denoting the success or failure of your method's actions.

Moodle1.9

preferred_width()

function preferred_width() {
  // Default case: the block wants to be 180 pixels wide
  return 180;
}

Available in Moodle 1.5 to Moodle 1.9

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.

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.

refresh_content()

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 get_content(), which say to respect the current content value unless it is NULL, then the default implementation will do the job just fine. You should return the new value of $this->content after refreshing it.

specialization()

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.

The instance data will be available in the variables $this->instance and $this->config.

This method should not return anything at all.

Back to top of page ↑


Methods which you should not override but may want to use:

get_content_type()

function get_content_type() {
  return $this->content_type;
}

Available in Moodle 1.5 and later

This method returns the value of $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; future library changes may break compatibility with code that does so.

get_title()

function get_title() {
  return $this->title;
}

Available in Moodle 1.5 and later

This method returns the value of $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; future library changes may break compatibility with code that does so.

Moodle1.9

get_version()

function get_version() {
  return $this->version;
}

Available in Moodle 1.5 and later

This method returns the value of $this->version, and is the preferred way of accessing that variable. Directly accessing the variable is not recommended; future library changes may break compatibility with code that does so.

Moodle 2.0


In previous versions of the documentation, this method was noted as being "guaranteed to always work, now and forever." This turned out to not be the case, as $this->version is no longer present in Moodle 2.0. Instead, you should use a version.php file as described on the main blocks documentation page.

instance_config_commit()

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 $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 $this->config and then call this method.

is_empty()

For blocks that extend class block_base:

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:

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.

name()

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 config_print() method.

Back to top of page ↑


Methods which you should not override and not use at all:

_add_edit_controls()

This is a private method; no description is given.

_load_instance()

This is a private method; no description is given.

_print_block()

This is a private method; no description is given.

_print_shadow()

This is a private method; no description is given.

_self_test()

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.

Back to top of page ↑


Class variables:

$this->config

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 config_instance.html file.

The variable is initialized just after the block object is constructed, immediately before 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 instance_config_commit() to do the actual work.

$this->content

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 get_content() is called.

After it is fully constructed, this object is expected to have certain properties, depending on the value of $this->content_type.

Specifically:

  1. text This is a string of arbitrary length and content. It is displayed inside the main area of the block, and can contain HTML.
  2. footer 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.


  1. items 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.
  2. icons 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.
  3. footer 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.

Moodle 2.0


  1. items This is an array of tree_item objects, representing the top level of the tree to be displayed. Each tree_item::children property may contain more tree_item objects for the next level down, which in turn contain more tree_item objects, and so on. Note that the tree block type has no footer.


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 $this->content, you should also include a simple caching check. If $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.


$this->content_type

This variable instructs Moodle on what type of content it should assume the block has, and is used to differentiate text blocks from list or tree 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 $this->content. The variable is expected to have a valid value after the framework calls the init() method for each block.

Prior to Moodle 2.0, the only valid values for this variable are the two named constants BLOCK_TYPE_TEXT and BLOCK_TYPE_LIST. Moodle 2.0 adds a third content type, BLOCK_TYPE_TREE.


Moodle 2.0


$this->context

As of Moodle 2.0, every block now has its own context, and you can always access it via $this->context. However when checking permissions you need to decide which of two contexts is more appropriate:

  1. The block context ($this->context)
  2. The page context the block is appearing on ($this->page->context). For sticky blocks, this may be a more appropriate choice.

For example, when deciding whether the user can edit the block settings, or see the block, you should use the block context. When deciding whether the user can do something relating to the context where the block appears (can the user see participants here) you should probably use the page context.


Moodle1.9

$this->instance

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.

This field no longer exists in Moodle 2.0. You should use the $this->page variable instead.


Moodle 2.0


$this->page

As of Moodle 2.0, very block now has access to the page it appears on, via $this->page. (Therefore, you do not have to use the global $PAGE object in blocks!)

For upgraders, any code that previously relied on $this->instance->... will probably break. Information about the page the block is appearing on is available from $this->page->.... Specifically:

  • $this->instance->pagetype should be changed to $this->page->pagetype
  • $this->instance->pageid - there is no longer a concept of page id. Instead, you are probably looking for $this->page->course, $this->page->cm or $this->page->activityrecord.

$this->title

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 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 init(). This title may then be overridden when the 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

 $this->title = get_string('blockname', ... );

to set the title of the block (and then put a more specific title inside the language file).

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...

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

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

Moodle1.9

$this->version

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 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.

Moodle 2.0


$this->version is no longer present in Moodle 2.0. Instead, you should use a version.php file as described on the main blocks documentation page.

Back to top of page ↑


Named constants:

Appearing throughout the code related to the Blocks API, there are a number of predefined constants that are utilized to avoid the use of "magic numbers" in the code. These constants are:

BLOCK_TYPE_LIST

This is one of the valid values for the $this->content_type member variable of every block. Its value specifies the exact requirements that Moodle will then have for $this->content.

BLOCK_TYPE_TEXT

This is one of the valid values for the $this->content_type member variable of every block. Its value specifies the exact requirements that Moodle will then have for $this->content.

Moodle 2.0


BLOCK_TYPE_TREE

Introduced in Moodle 2.0, this is one of the valid values for the $this->content_type member variable of every block. Its value specifies the exact requirements that Moodle will then have for $this->content.

Extended block types

Several additional classes are defined in the block library that extend block_base. These are basically shorthand ways of creating blocks with list or tree content types, rather than instantiating a block_base object and setting values on it. The block_list class can be used to create list-based blocks as described above, and as of Moodle 2.0, the block_tree class will allow you to create tree-structured blocks easily. If you are using one of these blocks, you will not need to set $this->content_type as described above. ru:Blocks/Appendix_A