Automatic installer.php lang files by installer_builder (20070224)
[moodle.git] / blocks / HOWTO.html
blob6c2e91427d7761927f8593ed5c1765ca0b070cd8
1 <html>
2 <head>
3 <title>Moodle Developer Documentation: Blocks</title>
4 <style type="text/css">
5 body {
6 background-color: #ffeece;
7 font-family: Verdana, Arial, serif;
8 font-size: 90%;
9 padding: 10px 30px;
11 h2 {
12 border: 1px black solid;
13 background-color: #fff;
14 padding: 10px 20px;
15 -moz-border-radius: 10px;
17 p {
18 text-align: justify;
20 pre {
21 font-family: Lucida Console, courier;
23 .footer {
24 border: 1px black solid;
25 background-color: #FFD991;
26 padding: 5px;
27 margin: 4em;
28 -moz-border-radius: 25px;
30 .header {
31 border: 1px black solid;
32 background-color: #fff;
33 padding: 10px;
34 -moz-border-radius: 25px;
36 .header h1, .footer h1 {
37 text-align: center;
38 font-size: 2em;
40 .header #doc_subject {
41 text-align: center;
42 font-size: 1.6em;
43 margin: 10px;
45 .header #doc_author, .header #doc_version, .header #doc_translator {
46 text-align: right;
48 .code {
49 border-top: 1px #FFC85F solid;
50 border-left: 1px #FFC85F solid;
51 border-bottom: 1px #333 solid;
52 border-right: 1px #333 solid;
53 background-color: #FFD991;
54 padding: 10px;
55 margin: 0px 20px;
57 .filename {
58 font-family: Lucida Console, courier;
59 font-weight: bold;
60 display: inline;
61 font-size: 0.9em;
63 .function_title, .variable_title, .named_constant {
64 font-weight: bold;
66 div.function_title, div.variable_title, div.named_constant {
67 font-size: 1.1em;
68 margin: 10px;
70 a.function_title, a.variable_title, a.named_constant {
71 cursor: help;
72 border: none !important;
74 a, a:visited, a:active {
75 text-decoration: none;
76 color: #009;
78 a:hover {
79 text-decoration: underline;
81 .updating {
82 padding: 10px;
83 border: 1px #999 dotted;
84 background-color: #F76120;
86 ul#methods_reference, ul#variables_reference, ul#constants_reference {
87 list-style-type: decimal;
89 ul#methods_reference ul, ul#variables_reference, ul#constants_reference {
90 border-left: 10px rgb(245, 180, 90) solid;
91 list-style-type: none;
92 margin: 0px;
93 margin-bottom: 3em;
94 padding: 0px 20px;
96 ul#methods_reference h3 {
97 margin-top: 2em;
99 ul#methods_reference ul li .function_title, ul#variables_reference .variable_title, ul#constants_reference .named_constant {
100 margin: 2em 0px 1em 0px;
101 border-bottom: 2px #666 dotted;
103 ul#methods_reference ul ul {
104 border: none;
105 list-style-type: disc;
107 </style>
108 </head>
109 <body>
110 <div class="header">
111 <h1>MOODLE DEVELOPER DOCUMENTATION</h1>
112 <div id="doc_subject">BLOCKS</div>
113 <div id="doc_author"><strong>Author:</strong> Jon Papaioannou (pj@uom.gr)</div>
114 <div id="doc_version"><strong>Version:</strong> $Id$</div>
115 </div>
117 <h2>A Step-by-step Guide To Creating Blocks</h2>
119 <ol class="mainparts">
120 <li>
122 <h3>Summary</h3>
124 <p>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) <strong>only</strong>, 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 <a href="#appendix_b">Appendix B</a>).</p>
126 <p>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 <a href="#appendix_a">Appendix A</a> because the main guide has a rather low concentration of pure information in the text.</p>
128 </li>
130 <li>
132 <h3>Basic Concepts</h3>
134 <p>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 <em>only</em> the "simplehtml" part is up to us to change; the rest is standardized and essential for Moodle to work correctly.</p>
136 <p>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.</p>
138 </li>
140 <li id="ready_set_go">
142 <h3>Ready, Set, Go!</h3>
144 <p>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:</p>
146 <pre class="code">class block_simplehtml extends block_base {
147 function init() {
148 $this->title = get_string('simplehtml', 'block_simplehtml');
149 $this->version = 2004111200;
151 }</pre>
153 <p>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.</p>
155 <p>Our class is then given a small method: <a class="function_title" href="#method_init">init</a>. 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.</p>
157 <p><a class="variable_title" href="#variable_title">$this->title</a> 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 <strong>no</strong> title at all, then you should set this to any descriptive value you want (but <strong>not</strong> make it an empty string). We will later see <a href="#section_eye_candy">how to disable the title's display</a>.</p>
159 <p><a class="variable_title" href="#variable_version">$this->version</a> 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 <a class="variable_title" href="#variable_version">$this->version</a> to <strong>YYYYMMDD00</strong> and forget about it.</p>
161 <p class="updating"><strong>UPDATING:</strong> Prior to version 1.5, the basic structure of each block class was slightly different. Refer to <a href="#appendix_b">Appendix B</a> for more information on the changes that old blocks have to make to conform to the new standard.</p>
163 </li>
165 <li>
167 <h3>I Just Hear Static</h3>
169 <p>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:</p>
171 <pre class="code">function get_content() {
172 if ($this->content !== NULL) {
173 return $this->content;
176 $this->content = new stdClass;
177 $this->content->text = 'The content of our SimpleHTML block!';
178 $this->content->footer = 'Footer here...';
180 return $this->content;
181 }</pre>
183 <p>It can't get any simpler than that, can it? Let's dissect this method to see what's going on...</p>
185 <p>First of all, there is a check that returns the current value of <a class="variable_title" href="#variable_content">$this->content</a> if it's not NULL; otherwise we proceed with "computing" it. Since the computation is potentially a time-consuming operation and it <strong>will</strong> be called several times for each block (Moodle works that way internally), we take a precaution and include this time-saver.</p>
187 <p>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 <strong>and</strong> in the footer, if we want to.</p>
189 <p>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.</p>
191 </li>
193 <li id="section_configure_that_out">
195 <h3>Configure That Out</h3>
197 <p>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...</p>
199 <p>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:</p>
201 <pre class="code">function instance_allow_config() {
202 return true;
204 </pre>
206 <p>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.</p>
208 <p>Moodle's complaints do make sense. We told it that we want to have configuration, but we didn't say <em>what</em> 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:</p>
210 <pre class="code">
211 &lt;table cellpadding="9" cellspacing="0"&gt;
212 &lt;tr valign="top"&gt;
213 &lt;td align="right"&gt;
214 &lt;?php print_string('configcontent', 'block_simplehtml'); ?&gt;:
215 &lt;/td&gt;
216 &lt;td&gt;
217 &lt;?php print_textarea(true, 10, 50, 0, 0, 'text', $this-&gt;config-&gt;text); ?&gt;
218 &lt;/td&gt;
219 &lt;/tr&gt;
220 &lt;tr&gt;
221 &lt;td colspan="2" align="center"&gt;
222 &lt;input type="submit" value="&lt;?php print_string('savechanges') ?&gt;" /&gt;
223 &lt;/td&gt;
224 &lt;/tr&gt;
225 &lt;/table&gt;
226 &lt;?php use_html_editor(); ?&gt;
227 </pre>
229 <p>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...</p>
231 <p>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 <strong>$this->config-><em>variablename</em></strong>, where <em>variablename</em> 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.</p>
233 <p>You also might be surprised by the presence of a submit button and the absence of any &lt;form&gt; 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 <em>except</em> <a class="function_title" href="#method_init">init</a>.</p>
235 <p>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 <a href="#appendix_a">Appendix A</a> for more details.</p>
237 <p>Having now the ability to refer to this instance configuration data through <a class="variable_title" href="#variable_config">$this->config</a>, the final twist is to tell our block to actually <em>display</em> what is saved in is configuration data. To do that, find this snippet in <span class="filename">/blocks/simplehtml/block_simplehtml.php</span>:</p>
239 <pre class="code">
240 $this->content = new stdClass;
241 $this->content->text = 'The content of our SimpleHTML block!';
242 $this->content->footer = 'Footer here...';</pre>
244 <p>and change it to:</p>
246 <pre class="code">
247 $this->content = new stdClass;
248 $this->content->text = $this->config->text;
249 $this->content->footer = 'Footer here...';</pre>
251 <p>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:</p>
253 <pre class="code">
254 $this->content = new stdClass;
255 $this->content->text = $this->config->text;
256 $this->content->footer = '';</pre>
258 <p>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.</p>
260 </li>
262 <li>
264 <h3>The Specialists</h3>
266 <p>Implementing instance configuration for the block's contents was good enough to whet our apetite, but who wants to stop there? Why not customize the block's title, too?</p>
268 <p>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:</p>
270 <pre class="code">
271 &lt;tr valign="top"&gt;
272 &lt;td align="right"&gt;&lt;p&gt;&lt;?php print_string('configtitle', 'block_simplehtml'); ?&gt;:&lt;/td&gt;
273 &lt;td&gt;&lt;input type="text" name="title" size="30" value="&lt;?php echo $this-&gt;config-&gt;title; ?&gt;" /&gt;&lt;/td&gt;
274 &lt;/tr&gt;
275 </pre>
277 <p>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.</p>
279 <p>That's not too wierd, if we think back a bit. Do you remember that <a class="function_title" href="#method_init">init</a> method, where we set <a class="variable_title" href="#variable_title">$this->title</a>? We didn't actually change its value from then, and <a class="variable_title" href="#variable_title">$this->title</a> is definitely not the same as $this->config->title (to Moodle, at least). What we need is a way to update <a class="variable_title" href="#variable_title">$this->title</a> with the value in the instance configuration. But as we said a bit earlier, we can use <a class="variable_title" href="#variable_config">$this->config</a> in all methods <em>except</em> <a class="function_title" href="#method_init">init</a>! So what can we do?</p>
281 <p>Let's pull out another ace from our sleeve, and add this small method to our block class:</p>
283 <pre class="code">
284 function specialization() {
285 $this->title = $this->config->title;
286 }</pre>
288 <p>Aha, here's what we wanted to do all along! But what's going on with the <a class="function_title" href="#method_specialization">specialization</a> method?</p>
290 <p>This "magic" method has actually a very nice property: it's <em>guaranteed</em> to be automatically called by Moodle as soon as our instance configuration is loaded and available (that is, immediately after <a class="function_title" href="#method_init">init</a> is called). That means before the block's content is computed for the first time, and indeed before <em>anything</em> else is done with the block. Thus, providing a <a class="function_title" href="#method_specialization">specialization</a> method is the natural choice for any configuration data that needs to be acted upon "as soon as possible", as in this case.</p>
292 </li>
294 <li>
296 <h3>Now You See Me, Now You Don't</h3>
298 <p>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.</p>
300 <p>This is indeed possible, and the way to do it is to make sure that after the <a class="function_title" href="#method_get_content">get_content</a> 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 <a class="function_title" href="#method_is_empty">is_empty()</a> method, and if the block is indeed empty then it is not displayed at all.</p>
302 <p>Note that the exact value of the block's title and the presence or absence of a <a class="function_title" href="#method_hide_header">hide_header</a> method do <em>not</em> affect this behavior. A block is considered empty if it has no content, irrespective of anything else.</p>
304 </li>
306 <li>
308 <h3>We Are Legion</h3>
310 <p>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:</p>
312 <pre class="code">
313 function instance_allow_multiple() {
314 return true;
315 }</pre>
317 <p>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!</p>
319 <p>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.</p>
321 <p>And finally, a nice detail is that as soon as we defined an <a class="function_title" href="#method_instance_allow_multiple">instance_allow_multiple</a> method, the method <a class="function_title" href="#method_instance_allow_config">instance_allow_config</a> 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 <a class="function_title" href="#method_instance_allow_config">instance_allow_config</a> method now without harm. We had only needed it when multiple instances of the block were not allowed.</p>
323 </li>
325 <li id="section_effects_of_globalization">
327 <h3>The Effects of Globalization</h3>
329 <p>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.</p>
331 <p>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.</p>
333 <p>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:</p>
335 <pre class="code">
336 function has_config() {
337 return true;
338 }</pre>
340 <p>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:</p>
342 <pre class="code">
343 &lt;div style="text-align: center;"&gt;
344 &lt;input type="hidden" name="block_simplehtml_strict" value="0" /&gt;
345 &lt;input type="checkbox" name="block_simplehtml_strict" value="1"
346 &lt;?php if(!empty($CFG-&gt;block_simplehtml_strict)) echo 'checked="checked"'; ?&gt; /&gt;
347 &lt;?php print_string('donotallowhtml', 'block_simplehtml'); ?&gt;
348 &lt;p&gt;&lt;input type="submit" value="&lt;?php print_string('savechanges'); ?&gt;" /&gt;&lt;/p&gt;
349 &lt;/div&gt;
350 </pre>
352 <p>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.</p>
354 <p>The astute reader may have noticed that we actually have <em>two</em> 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?</p>
356 <p>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.</p>
358 <p>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, <em>if</em> 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.</p>
360 <p>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, <em>and</em> have a nice human-readable representation for its two possible values ("0" and "1").</p>
362 <p>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 <a class="function_title" href="#method_config_save">config_save</a>, the default implementation of which is as follows:</p>
364 <pre class="code">
365 function config_save($data) {
366 // Default behavior: save all variables as $CFG properties
367 foreach ($data as $name => $value) {
368 set_config($name, $value);
370 return true;
371 }</pre>
373 <p>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:</p>
375 <pre class="code">
376 function config_save($data) {
377 if(isset($data['block_simplehtml_strict'])) {
378 set_config('block_simplehtml_strict', '1');
380 else {
381 set_config('block_simplehtml_strict', '0');
383 return true;
384 }</pre>
386 <p>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).</p>
388 <p>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?</p>
390 <p>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.</p>
392 <p>Much as we did just before with overriding <a class="function_title" href="#method_config_save">config_save</a>, what is needed here is overriding the method <a class="function_title" href="#method_instance_config_save">instance_config_save</a> which handles the instance configuration. The default implementation is as follows:</p>
394 <pre class="code">
395 function instance_config_save($data) {
396 $data = stripslashes_recursive($data);
397 $this->config = $data;
398 return set_field('block_instance', 'configdata', base64_encode(serialize($data)),
399 'id', $this->instance->id);
400 }</pre>
402 <p>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:</p>
404 <pre class="code">
405 function instance_config_save($data) {
406 // Clean the data if we have to
407 global $CFG;
408 if(!empty($CFG->block_simplehtml_strict)) {
409 $data['text'] = strip_tags($data['text']);
412 // And now forward to the default implementation defined in the parent class
413 return parent::instance_config_save($data);
414 }</pre>
416 <p>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!</p>
418 <p>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?</p>
420 <p>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, <strong>or</strong> go back and implement the lazy approach instead. (Hint: do that in the <a class="function_title" href="#method_get_content">get_content</a> method)</p>
422 <p class="updating"><strong>UPDATING</strong>: Prior to version 1.5, the file <span class="filename">config_global.html</span> was named simply <span class="filename">config.html</span>. Also, the methods <a class="function_title" href="#method_config_save">config_save</a> and <a class="function_title" href="#method_config_print">config_print</a> were named <strong>handle_config</strong> and <strong>print_config</strong> respectively. Upgrading a block to work with Moodle 1.5 involves updating these aspects; refer to <a href="#appendix_b">Appendix B</a> for more information.</p>
424 </li>
426 <li id="section_eye_candy">
428 <h3>Eye Candy</h3>
430 <p>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.</p>
432 <p>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:</p>
434 <pre class="code">
435 function hide_header() {
436 return true;
437 }</pre>
439 <p>One more note here: we cannot just set an empty title inside the block's <a class="function_title" href="#method_init">init</a> method; it's necessary for each block to have a unique, non-empty title after <a class="function_title" href="#method_init">init</a> is called so that Moodle can use those titles to differentiate between all of the installed blocks.</p>
441 <p>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 <em>request</em> a certain width and Moodle will <em>try</em> 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.</p>
443 <p>To instruct Moodle about our block's preferred width, we add one more method to the block class:</p>
445 <pre class="code">
446 function preferred_width() {
447 // The preferred value is in pixels
448 return 200;
449 }</pre>
451 <p>This will make our block (and all the other blocks displayed at the same side of the page) a bit wider than standard.</p>
453 <p>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).</p>
455 <p>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}").</p>
457 <p>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</p>
459 <pre class="code">
460 function html_attributes() {
461 return array(
462 'class' => 'sideblock block_'. $this->name(),
463 'onmouseover' => 'alert("Mouseover on our block!");'
465 }</pre>
467 <p>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 <a class="function_title" href="#method_name">name</a> method to make it dynamically match our block's name.</p>
469 </li>
471 <li id="section_authorized_personnel_only">
473 <h3>Authorized Personnel Only</h3>
475 <p>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.<p>
477 <p>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.</p>
479 <p>Notice the deliberate use of the term <em>page</em> instead of <em>course</em> 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.</p>
481 <p>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 <strong>course-view</strong>. It follows easily that the format name for a quiz view page is <strong>mod-quiz-view</strong>. This rule of thumb does have a few exceptions, however:
482 <ul>
483 <li>The format name for the front page of Moodle is <strong>site-index</strong>.</li>
484 <li>The format name for courses is actually not just <strong>course-view</strong>; it is <strong>course-view-weeks</strong>, <strong>course-view-topics</strong>, etc.</li>
485 <li>Even though there is no such page, the format name <strong>all</strong> can be used as a catch-all option.</li>
486 </ul>
487 </p>
489 <p>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?":
491 <ul>
492 <li>Prefixes of a format name will match that format name; for example, <strong>mod</strong> will match all the activity modules. <strong>course-view</strong> will match any course, regardless of the course format. And finally, <strong>site</strong> will also match the front page (remember that its full format name is <strong>site-index</strong>).</li>
493 <li>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, <strong>mod</strong>, <strong>mod-quiz</strong> and <strong>mod-quiz-view</strong> all match the quiz view page. But if all three are present, <strong>mod-quiz-view</strong> will take precedence over the other two because it is a better match.</li>
494 <li>The character <strong>*</strong> can be used in place of any word. For example, <strong>mod</strong> and <strong>mod-*</strong> 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.</li>
495 <li>The order that the format names appear does not make any difference.</li>
496 </ul>
497 </p>
499 <p>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 <strong>only</strong> in the site front page, we would use:</p>
501 <pre class="code">
502 function applicable_formats() {
503 return array('site' => true);
504 }</pre>
506 <p>Since <strong>all</strong> is missing, the block is disallowed from appearing in <em>any</em> course format; but then <strong>site</strong> is set to true, so it's explicitly allowed to appear in the site front page (remember that <strong>site</strong> matches <strong>site-index</strong> because it's a prefix).</p>
508 <p>For another example, if we wanted to allow the block to appear in all course formats <em>except</em> social, and also to <em>not</em> be allowed anywhere but in courses, we would use:</p>
510 <pre class="code">
511 function applicable_formats() {
512 return array('course-view' => true, 'course-view-social' => false);
513 }</pre>
515 <p>This time, we first allow the block to appear in all courses and then we explicitly disallow the social format.</p>
517 <p>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, <em>except</em> quiz. This would be:</p>
519 <pre class="code">
520 function applicable_formats() {
521 return array('site-index' => true,
522 'course-view' => true, 'course-view-social' => false,
523 'mod' => true, 'mod-quiz' => false);
524 }</pre>
526 <p>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.</p>
528 <p class="updating"><strong>UPDATING:</strong> 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 <a href="#appendix_b">Appendix B</a> for more information on the changes that old blocks have to make to conform to the new standard.</p>
529 </li>
531 <li>
533 <h3>Lists and Icons</h3>
535 <p>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 <em>list block</em> is the standard Moodle "admin" block, which illustrates all the points discussed in this section.</p>
537 <p>As we have seen so far, blocks of use two properties of <a class="variable_title" href="#variable_content">$this->content</a>: "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.</p>
539 <p>Instead, Moodle expects such blocks to set two other properties when the <a class="function_title" href="#method_get_content">get_content</a> 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 &lt;img&gt; tag, with "src", "height", "width" and "alt" attributes. Obviously, it makes sense to keep the images small and of a uniform size.</p>
541 <p>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 <strong>block_base</strong>, our block will extend class <strong>block_list</strong>. For example:</p>
543 <pre class="code">
544 class block_my_menu extends block_list {
545 // The init() method does not need to change at all
547 </pre>
549 <p>In addition to making this change, we must of course also modify the <a class="function_title" href="#method_get_content">get_content</a> method to construct the <a class="variable_title" href="#variable_content">$this->content</a> variable as discussed above:</p>
551 <pre class="code">
552 function get_content() {
553 if ($this->content !== NULL) {
554 return $this->content;
557 $this->content = new stdClass;
558 $this->content->items = array();
559 $this->content->icons = array();
560 $this->content->footer = 'Footer here...';
562 $this->content->items[] = '&lt;a href="some_file.php"&gt;Menu Option 1&lt;/a&gt;';
563 $this->content->icons[] = '&lt;img src="images/icons/1.gif" width="16" height="16" alt="" /&gt;';
565 // Add more list items here
567 return $this->content;
568 }</pre>
570 <p>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 <a class="function_title" href="#method_get_content">get_content</a> method. Adding the mandatory <a class="function_title" href="#method_init">init</a> method as discussed earlier will then give us our first list block in no time!</p>
572 </li>
574 </ol>
576 <h2 id="appendix_a">Appendix A: Reference</h2>
578 <p>This Appendix will discuss the base class <strong>block_base</strong> 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 <strong>not</strong> 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.</p>
580 <p>The methods are divided into three categories: those you may use and override in your block, those that you may <strong>not</strong> override but might want to use, and those internal methods that should <strong>neither</strong> be used <strong>nor</strong> overridden. In each category, methods are presented in alphabetical order.</p>
582 <ul id="methods_reference">
584 <li><h3>Methods you can freely use and override:</h3>
586 <ul>
588 <li id="method_applicable_formats">
590 <div class="function_title">applicable_formats</div>
592 <pre class="code">
593 function applicable_formats() {
594 // Default case: the block can be used in courses and site index, but not in activities
595 return array('all' => true, 'mod' => false);
596 }</pre>
598 <p>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.</p>
600 <p>Example format names are: <strong>course-view</strong>, <strong>site-index</strong> (this is an exception, referring front page of the Moodle site), <strong>course-format-weeks</strong> (referring to a specific course format), <strong>mod-quiz</strong> (referring to the quiz module) and <strong>all</strong> (this will be used for those formats you have not explicitly allowed or disallowed).</p>
602 <p>The full matching rules are:
603 <ul>
604 <li>Prefixes of a format name will match that format name; for example, <strong>mod</strong> will match all the activity modules. <strong>course-view</strong> will match any course, regardless of the course format. And finally, <strong>site</strong> will also match the front page (remember that its full format name is <strong>site-index</strong>).</li>
605 <li>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, <strong>mod</strong>, <strong>mod-quiz</strong> and <strong>mod-quiz-view</strong> all match the quiz view page. But if all three are present, <strong>mod-quiz-view</strong> will take precedence over the other two because it is a better match.</li>
606 <li>The character <strong>*</strong> can be used in place of any word. For example, <strong>mod</strong> and <strong>mod-*</strong> 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.</li>
607 <li>The order that the format names appear does not make any difference.</li>
608 </ul>
609 </p>
611 </li>
613 <li id="method_config_print">
615 <div class="function_title">config_print</div>
617 <pre class="code">
618 function config_print() {
619 // Default behavior: print the config_global.html file
620 // You don't need to override this if you're satisfied with the above
621 if (!$this->has_config()) {
622 return false;
624 global $CFG, $THEME;
625 print_simple_box_start('center', '', $THEME->cellheading);
626 include($CFG->dirroot.'/blocks/'. $this->name() .'/config_global.html');
627 print_simple_box_end();
628 return true;
629 }</pre>
631 <p>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:</p>
633 <ol>
634 <li>If you save your configuration options in $CFG, you will probably need to use global $CFG; before including any HTML configuration screens.</li>
635 <li>The HTML &lt;input&gt; elements that you include in your method's output will be automatically enclosed in a &lt;form&gt; element. You do not need to worry about where and how that form is submitted; however, you <strong>must</strong> provide a way to submit it (i.e., an &lt;input type="submit" /&gt;.</li>
636 </ol>
638 <p>You should return a boolean value denoting the success or failure of your method's actions.</p>
640 </li>
642 <li id="method_config_save">
644 <div class="function_title">config_save</div>
646 <pre class="code">
647 function config_save($data) {
648 // Default behavior: save all variables as $CFG properties
649 // You don't need to override this if you 're satisfied with the above
650 foreach ($data as $name => $value) {
651 set_config($name, $value);
653 return true;
654 }</pre>
656 <p>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.</p>
658 <p>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.</p>
660 <p>You should return a boolean value denoting the success or failure of your method's actions.</p>
662 </li>
664 <li id="method_get_content">
666 <div class="function_title">get_content</div>
668 <pre class="code">
669 function get_content() {
670 // This should be implemented by the derived class.
671 return NULL;
672 }</pre>
674 <p>This method should, when called, populate the <a class="variable_title" href="#variable_content">$this->content</a> variable of your block. Populating the variable means:
676 <p><strong>EITHER</strong><br />defining $this->content->text and $this->content->footer if your block derives from <strong>block_base</strong>. Both of these should be strings, and can contain arbitrary HTML.</p>
678 <p><strong>OR</strong><br />defining $this->content->items, $this->content->icons and $this->content->footer if your block derives from <strong>block_list</strong>. 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 &lt;img&gt; tags <strong>and nothing else</strong>. $this->content->footer is a string, as above.</p>
680 <p>If you set <em>all</em> of these variables to their default "empty" values (empty arrays for the arrays and empty strings for the strings), the block will <strong>not</strong> 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.</p>
682 <p>Before starting to populate <a class="variable_title" href="#variable_content">$this->content</a>, you should also include a simple caching check. If <a class="variable_title" href="#variable_content">$this->content</a> 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.</p>
684 <p>In any case, your method should return the fully constructed <a class="variable_title" href="#variable_content">$this->content</a> variable.</p>
686 </li>
688 <li id="method_has_config">
690 <div class="function_title">has_config</div>
692 <pre class="code">
693 function has_config() {
694 return false;
695 }</pre>
697 <p>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.</p>
699 <p>To actually implement the configuration interface, you will either need to rely on the default <a class="function_title" href="#method_instance_config_print">config_print</a> method or override it. The full guide contains <a href="#section_effects_of_globalization">more information on this</a>.</p>
700 </li>
702 <li id="method_hide_header">
704 <div class="function_title">hide_header</div>
706 <pre class="code">
707 function hide_header() {
708 //Default, false--> the header is shown
709 return false;
710 }</pre>
712 <p>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.</p>
714 </li>
716 <li id="method_html_attributes">
718 <div class="function_title">html_attributes</div>
720 <pre class="code">
721 function html_attributes() {
722 // Default case: an id with the instance and a class with our name in it
723 return array('id' => 'inst'.$this->instance->id, 'class' => 'block_'. $this->name());
724 }</pre>
726 <p>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.</p>
728 <p>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:</p>
730 <pre class="code">
731 function html_attributes() {
732 $attrs = parent::html_attributes();
733 // Add your own attributes here, e.g.
734 // $attrs['width'] = '50%';
735 return $attrs;
736 }</pre>
738 </li>
740 <li id="method_init">
742 <div class="function_title">init</div>
744 <pre class="code">
745 function init() {
746 $this->title = get_string('simplehtml', 'block_simplehtml');
747 $this->version = 2004111200;
748 }</pre>
750 <p>This method must be implemented for all blocks. It has to assign meaningful values to the object variables <a class="variable_title" href="#variable_title">$this->title</a> and <a class="variable_title" href="#variable_version">$this->version</a> (which is used by Moodle for performing automatic updates when available).</p>
752 <p>No return value is expected from this method.</p>
754 </li>
756 <li id="method_instance_allow_config">
758 <div class="function_title">instance_allow_config</div>
760 <pre class="code">
761 function instance_allow_config() {
762 return false;
763 }</pre>
765 <p>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 <a href="#section_configure_that_out">more information</a>.</p>
767 <p>This method's return value is irrelevant if <a class="function_title" href="#method_instance_allow_multiple">instance_allow_multiple</a> returns true; it is assumed that if you want multiple instances then each instance needs its own configuration.</p>
769 </li>
771 <li id="method_instance_allow_multiple">
773 <div class="function_title">instance_allow_multiple</div>
775 <pre class="code">
776 function instance_allow_multiple() {
777 // Are you going to allow multiple instances of each block?
778 // If yes, then it is assumed that the block WILL USE per-instance configuration
779 return false;
780 }</pre>
782 <p>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 <a href="#section_configure_that_out">more information</a>.</p>
784 </li>
786 <li id="method_instance_config_print">
788 <div class="function_title">instance_config_print</div>
790 <pre class="code">
791 function instance_config_print() {
792 // Default behavior: print the config_instance.html file
793 // You don't need to override this if you're satisfied with the above
794 if (!$this->instance_allow_multiple() && !$this->instance_allow_config()) {
795 return false;
797 global $CFG, $THEME;
799 if (is_file($CFG->dirroot .'/blocks/'. $this->name() .'/config_instance.html')) {
800 print_simple_box_start('center', '', $THEME->cellheading);
801 include($CFG->dirroot .'/blocks/'. $this->name() .'/config_instance.html');
802 print_simple_box_end();
803 } else {
804 notice(get_string('blockconfigbad'),
805 str_replace('blockaction=', 'dummy=', qualified_me()));
808 return true;
809 }</pre>
811 <p>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 <a class="function_title" href="#method_instance_config_print">config_print</a>, it will be enclosed in a HTML form automatically. You only need to provide a way to submit that form.</p>
813 <p>You should return a boolean value denoting the success or failure of your method's actions.</p>
815 <li id="method_instance_config_save">
817 <div class="function_title">instance_config_save</div>
819 <pre class="code">
820 function instance_config_save($data) {
821 $data = stripslashes_recursive($data);
822 $this->config = $data;
823 return set_field('block_instance', 'configdata', base64_encode(serialize($data)),
824 'id', $this->instance->id);
825 }</pre>
827 <p>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.</p>
829 <p>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.</p>
831 <p>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.</p>
833 <p>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 <a class="function_title" href="#method_instance_config_commit">instance_config_commit</a>.</p>
835 <p>You should return a boolean value denoting the success or failure of your method's actions.</p>
837 </li>
839 <li id="method_preferred_width">
841 <div class="function_title">preferred_width</div>
843 <pre class="code">
844 function preferred_width() {
845 // Default case: the block wants to be 180 pixels wide
846 return 180;
847 }</pre>
849 <p>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.</p>
851 <p>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.</p>
853 </li>
855 <li id="method_refresh_content">
857 <div class="function_title">refresh_content</div>
859 <pre class="code">
860 function refresh_content() {
861 // Nothing special here, depends on content()
862 $this->content = NULL;
863 return $this->get_content();
864 }</pre>
866 <p>This method should cause your block to recalculate its content immediately. If you follow the guidelines for <a class="function_title" href="#get_content">get_content</a>, which say to respect the current content value unless it is NULL, then the default implementation will do the job just fine.</p>
868 <p>You should return the new value of <a class="variable_title" href="#variable_content">$this->content</a> after refreshing it.</p>
870 </li>
872 <li id="method_specialization">
874 <div class="function_title">specialization</div>
876 <pre class="code">
877 function specialization() {
878 // Just to make sure that this method exists.
879 }</pre>
881 <p>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.</p>
883 <p>The instance data will be available in the variables <a class="variable_title" href="#variable_instance">$this->instance</a> and <a class="variable_title" href="#variable_config">$this->config</a>.</p>
885 <p>This method should not return anything at all.</p>
887 </li>
889 </ul>
891 <li><h3>Methods which you should <em>not</em> override but may want to use:</h3>
893 <ul>
895 <li id="method_instance_config_commit">
896 <div class="function_title">instance_config_commit</div>
897 <pre class="code">
898 function instance_config_commit() {
899 return set_field('block_instance',
900 'configdata', base64_encode(serialize($this->config)),
901 'id', $this->instance->id);
902 }</pre>
904 <p>This method saves the current contents of <a class="variable_title" href="#variable_config">$this->config</a> 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 <a class="variable_title" href="#variable_config">$this->config</a> and then call this method.</p>
905 </li>
906 <li id="method_get_content_type">
907 <div class="function_title">get_content_type</div>
908 <pre class="code">
909 function get_content_type() {
910 return $this->content_type;
911 }</pre>
913 <p>This method returns the value of <a class="variable_title" href="#variable_content_type">$this->content_type</a>, and is the preferred way of accessing that variable. It is guaranteed to always work, now and forever. Directly accessing the variable is <strong>not recommended</strong>; future library changes may break compatibility with code that does so.</p>
915 </li>
916 <li id="method_get_title">
917 <div class="function_title">get_title</div>
918 <pre class="code">
919 function get_title() {
920 return $this->title;
921 }</pre>
923 <p>This method returns the value of <a class="variable_title" href="#variable_title">$this->title</a>, and is the preferred way of accessing that variable. It is guaranteed to always work, now and forever. Directly accessing the variable is <strong>not recommended</strong>; future library changes may break compatibility with code that does so.</p>
925 </li>
926 <li id="method_get_version">
927 <div class="function_title">get_version</div>
928 <pre class="code">
929 function get_version() {
930 return $this->version;
931 }</pre>
933 <p>This method returns the value of <a class="variable_title" href="#variable_version">$this->version</a>, and is the preferred way of accessing that variable. It is guaranteed to always work, now and forever. Directly accessing the variable is <strong>not recommended</strong>; future library changes may break compatibility with code that does so.</p>
935 </li>
937 <li id="method_is_empty">
938 <div class="function_title">is_empty</div>
939 <p>For blocks that extend class <strong>block_base</strong>:</p>
940 <pre class="code">
941 function is_empty() {
942 $this->get_content();
943 return(empty($this->content->text) && empty($this->content->footer));
944 }</pre>
945 <p>For blocks that extend class <strong>block_list</strong>:</p>
946 <pre class="code">
947 function is_empty() {
948 $this->get_content();
949 return (empty($this->content->items) && empty($this->content->footer));
951 </pre>
953 <p>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.</p>
955 </li>
957 <li id="method_name">
958 <div class="function_title">name</div>
959 <pre class="code">
960 function name() {
961 static $myname;
962 if ($myname === NULL) {
963 $myname = strtolower(get_class($this));
964 $myname = substr($myname, strpos($myname, '_') + 1);
966 return $myname;
967 }</pre>
969 <p>This method returns the internal name of your block inside Moodle, without the <strong>block_</strong> 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 <a class="function_title" href="#method_config_print">config_print</a> method.</p>
970 </li>
972 </ul>
974 </li>
976 <li><h3>Methods which you should <em>not</em> override and <em>not</em> use at all:</h3>
977 <ul>
978 <li id="method__self_test">
979 <div class="function_title">_self_test</div>
980 <p>This is a private method; no description is given.</p>
981 </li>
982 <li id="method__add_edit_controls">
983 <div class="function_title">_add_edit_controls</div>
984 <p>This is a private method; no description is given.</p>
985 </li>
986 <li id="method__load_instance">
987 <div class="function_title">_load_instance</div>
988 <p>This is a private method; no description is given.</p>
989 </li>
990 <li id="method__print_block">
991 <div class="function_title">_print_block</div>
992 <p>This is a private method; no description is given.</p>
993 </li>
994 <li id="method__print_shadow">
995 <div class="function_title">_print_shadow</div>
996 <p>This is a private method; no description is given.</p>
997 </li>
998 </ul>
999 </li>
1001 </ul>
1003 <p>The class <strong>block_base</strong> 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.</p>
1005 <h3>Class variables:</h3>
1007 <ul id="variables_reference">
1009 <li id="variable_config">
1011 <div class="variable_title">$this->config</div>
1013 <p>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 &lt;input&gt; elements in the block's <span class="filename">config_instance.html</span> file.</p>
1015 <p>The variable is initialized just after the block object is constructed, immediately before <a class="function_title" href="#method_specialization">specialization</a> is called for the object. It is possible that the block has no instance configuration, in which case the variable will be NULL.</p>
1017 <p>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 <em>strongly</em> 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 <a class="function_title" href="#method_instance_config_commit">instance_config_commit</a> to do the actual work.</p>
1019 </li>
1021 <li id="variable_content_type">
1023 <div class="variable_title">$this->content_type</div>
1025 <p>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 <a class="variable_title" href="#variable_content">$this->content</a>. The variable is expected to have a valid value after the framework calls the <a class="function_title" href="#method_init">init</a> method for each block.</p>
1027 <p>The only valid values for this variable are the two named constants <a class="named_constant" href="#constant_block_type_text">BLOCK_TYPE_TEXT</a> and <a class="named_constant" href="#constant_block_type_list">BLOCK_TYPE_LIST</a>.</p>
1028 </li>
1030 <li id="variable_content">
1032 <div class="variable_title">$this->content</div>
1034 <p>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 <a class="function_title" href="#method_get_content">get_content</a> is called.</p>
1036 <p>After it is fully constructed, this object is expected to have certain properties, depending on the value of <a class="variable_title" href="#variable_content_type">$this->content_type</a>. Specifically:
1038 <ul>
1040 <li>
1041 If <a class="variable_title" href="#variable_content_type">$this->content_type</a> is <a class="named_constant" href="#constant_block_type_text">BLOCK_TYPE_TEXT</a>, then <a class="variable_title" href="#variable_content">$this->content</a> is expected to have the following member variables:
1043 <ul>
1044 <li><div><strong>text</strong></div>This is a string of arbitrary length and content. It is displayed inside the main area of the block, and can contain HTML.</li>
1045 <li><div><strong>footer</strong></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.</li>
1046 </ul>
1047 </li>
1049 <li>If <a class="variable_title" href="#variable_content_type">$this->content_type</a> is <a class="named_constant" href="#constant_block_type_list">BLOCK_TYPE_LIST</a>, then <a class="variable_title" href="#variable_content">$this->content</a> is expected to have the following member variables:
1050 <ul>
1051 <li><div><strong>items</strong></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 &lt;a&gt; tag.</li>
1052 <li><div><strong>icons</strong></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 &lt;img&gt; tag.</li>
1053 <li><div><strong>footer</strong></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.</li>
1054 </ul>
1055 </li>
1057 </ul>
1058 </p>
1060 </li>
1062 <li id="variable_instance">
1064 <div class="variable_title">$this->instance</div>
1066 <p>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.</p>
1068 </li>
1070 <li id="variable_title">
1072 <div class="variable_title">$this->title</div>
1074 <p>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 <a class="function_title" href="#method_init">init</a> method for each object.</p>
1076 <p>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 <a class="function_title" href="#method_init">init</a>. This title may then be overridden when the <a class="function_title" href="#method_specialization">specialization</a> method is called by the framework:</p>
1078 <pre class="code">
1079 function specialization() {
1080 // At this point, $this->instance and $this->config are available
1081 // for use. We can now change the title to whatever we want.
1082 $this->title = $this->config->variable_holding_the_title;
1083 }</pre>
1085 </li>
1087 <li id="variable_version">
1089 <div class="variable_title">$this->version</div>
1091 <p>This variable should hold each block's version number in the form <strong>YYYYMMDDXX</strong>, 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 <a class="function_title" href="#method_init">init</a> method for each block.</p>
1093 <p>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.</p>
1095 </li>
1097 </ul>
1099 <p>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:</p>
1101 <h3>Named constants:</h3>
1103 <ul id="constants_reference">
1104 <li id="constant_block_type_list">
1106 <div class="named_constant">BLOCK_TYPE_LIST</div>
1108 <p>This is one of the two valid values for the <a class="variable_title" href="#variable_content_type">$this->content_type</a> member variable of every block. Its value specifies the exact requirements that Moodle will then have for <a class="variable_title" href="#variable_content">$this->content</a>.</p>
1110 </li>
1112 <li id="constant_block_type_text">
1114 <div class="named_constant">BLOCK_TYPE_TEXT</div>
1116 <p>This is one of the two valid values for the <a class="variable_title" href="#variable_content_type">$this->content_type</a> member variable of every block. Its value specifies the exact requirements that Moodle will then have for <a class="variable_title" href="#variable_content">$this->content</a>.</p>
1118 </li>
1119 </ul>
1121 <h2 id="appendix_b">Appendix B: Differences in the Blocks API for Moodle versions prior to 1.5</h2>
1123 <p>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.</p>
1125 <ol>
1127 <li>
1129 <h3>Class naming conventions changed</h3>
1131 <p>In Moodle 1.4, all block classes were required to have a name like <strong>CourseBlock_something</strong> and the base class from which the derived was <strong>MoodleBlock</strong>. 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 <strong>block_something</strong> and derive from <strong>block_base</strong>. This means that in order to make a block compatible with Moodle 1.5, you need to change the class definition</p>
1133 <pre class="code">
1134 class CourseBlock_online_users extends MoodleBlock { ... }
1135 </pre>
1137 <p>to</p>
1139 <pre class="code">
1140 class block_online_users extends block_base { ... }
1141 </pre>
1143 <p>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 <strong>block_list</strong> instead, like this:<p>
1145 <pre class="code">
1146 class block_admin extends block_list { ... }
1147 </pre>
1149 </li>
1151 <li>
1153 <h3>Constructor versus init()</h3>
1155 <p>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):</p>
1157 <pre class="code">
1158 function CourseBlock_online_users ($course) {
1159 $this->title = get_string('blockname','block_online_users');
1160 $this->content_type = BLOCK_TYPE_TEXT;
1161 $this->course = $course;
1162 $this->version = 2004052700;
1164 </pre>
1166 <p>In contrast, Moodle 1.5 does away with the constructor and instead requires you to define an init() method that takes no arguments:</p>
1168 <pre class="code">
1169 function init() {
1170 $this->title = get_string('blockname','block_online_users');
1171 $this->version = 2004111600;
1173 </pre>
1175 <p>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 <a class="function_title" href="#method_get_content">get_content</a>, the way to retrieve it is by using this code:</p>
1177 <pre class="code">
1178 $course = get_record('course', 'id', $this->instance->pageid);
1179 </pre>
1181 <p>If you are going to need access to $course from inside other methods in addition to <a class="function_title" href="#method_get_content">get_content</a>, you might fetch the $course object inside the <a class="function_title" href="#method_specialization">specialization</a> method and save it as a class variable for later use, in order to avoid executing the same query multiple times:</p>
1183 <pre class="code">
1184 function specialization() {
1185 $this->course = get_record('course', 'id', $this->instance->pageid);
1187 </pre>
1189 </li>
1191 <li>
1193 <h3>Blocks with configuration</h3>
1195 <p>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:</p>
1197 <ol style="list-style-type: lower-alpha;">
1198 <li>Rename your <span class="filename">config.html</span> file to <span class="filename">config_global.html</span>.</li>
1199 <li>Edit the newly renamed file and completely remove the &lt;form&gt; tag (Moodle now wraps your configuration in a form automatically).</li>
1200 <li>If you are using any HTML &lt;input&gt; tags other than those that directly affect your configuration (for example, "sesskey"), REMOVE those too (Moodle will add them automatically as required).</li>
1201 <li>If you have overridden <strong>print_config</strong>, rename your method to <strong>config_print</strong>.</li>
1202 <li>If you have overridden <strong>handle_config</strong>, rename your method to <strong>config_save</strong>.</li>
1203 </ol>
1205 </li>
1207 <li>
1209 <h3>Blocks with customized applicable formats</h3>
1211 <p>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 <a class="function_title" href="#method_applicable_formats">applicable_formats</a>) if they are used in your block:
1213 <ul>
1214 <li><strong>social</strong> should become <strong>course-view-social</strong></li>
1215 <li><strong>topics</strong> should become <strong>course-view-topics</strong></li>
1216 <li><strong>weeks</strong> should become <strong>course-view-weeks</strong></li>
1217 </ul>
1219 </p>
1221 <p>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 <a class="function_title" href="#method_applicable_formats">applicable_formats</a>, and for a more extended example read <a href="#section_authorized_personnel_only">the section dedicated to this subject</a>.
1223 <p>That's everything; your block will now be ready for use in Moodle 1.5!</p>
1226 </li>
1228 </ol>
1230 <div class="footer"><h1>The End</h1></div>
1232 </body>