forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHOWTO.html
1244 lines (871 loc) · 81.9 KB
/
HOWTO.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<html>
<head>
<title>Moodle Developer Documentation: Blocks</title>
<style type="text/css">
body {
background-color: #ffeece;
font-family: Verdana, Arial, serif;
font-size: 90%;
padding: 10px 30px;
}
h2 {
border: 1px black solid;
background-color: #fff;
padding: 10px 20px;
-moz-border-radius: 10px;
}
p {
text-align: justify;
}
pre {
font-family: Lucida Console, courier;
}
.footer {
border: 1px black solid;
background-color: #FFD991;
padding: 5px;
margin: 4em;
-moz-border-radius: 25px;
}
.header {
border: 1px black solid;
background-color: #fff;
padding: 10px;
-moz-border-radius: 25px;
}
.header h1, .footer h1 {
text-align: center;
font-size: 2em;
}
.header #doc_subject {
text-align: center;
font-size: 1.6em;
margin: 10px;
}
.header #doc_author {
text-align: right;
}
.header #doc_author:before {
content: "Author: ";
font-weight: bold;
}
.header #doc_version {
text-align: right;
}
.header #doc_version:before {
content: "Version: ";
font-weight: bold;
}
.code {
border-top: 1px #FFC85F solid;
border-left: 1px #FFC85F solid;
border-bottom: 1px #333 solid;
border-right: 1px #333 solid;
background-color: #FFD991;
padding: 10px;
margin: 0px 20px;
}
.filename {
font-family: Lucida Console, courier;
font-weight: bold;
display: inline;
font-size: 0.9em;
}
.function_title, .variable_title, .named_constant {
font-weight: bold;
}
div.function_title, div.variable_title, div.named_constant {
font-size: 1.1em;
margin: 10px;
}
a.function_title, a.variable_title, a.named_constant {
cursor: help;
border: none !important;
}
a, a:visited, a:active {
text-decoration: none;
color: #009;
}
a:hover {
text-decoration: underline;
}
.updating {
padding: 10px;
border: 1px #999 dotted;
background-color: #F76120;
}
ul#methods_reference, ul#variables_reference, ul#constants_reference {
list-style-type: decimal;
}
ul#methods_reference ul, ul#variables_reference, ul#constants_reference {
border-left: 10px rgb(245, 180, 90) solid;
list-style-type: none;
margin: 0px;
margin-bottom: 3em;
padding: 0px 20px;
}
ul#methods_reference h3 {
margin-top: 2em;
}
ul#methods_reference ul li .function_title, ul#variables_reference .variable_title, ul#constants_reference .named_constant {
margin: 2em 0px 1em 0px;
border-bottom: 2px #666 dotted;
}
ul#methods_reference ul ul {
border: none;
list-style-type: disc;
}
</style>
</head>
<body>
<div class="header">
<h1>MOODLE DEVELOPER DOCUMENTATION</h1>
<div id="doc_subject">BLOCKS</div>
<div id="doc_author">Jon Papaioannou ([email protected])</div>
<div id="doc_version">$Id$</div>
</div>
<h2>A Step-by-step Guide To Creating Blocks</h2>
<ol class="mainparts">
<li>
<h3>Summary</h3>
<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>
<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>
</li>
<li>
<h3>Basic Concepts</h3>
<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>
<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>
</li>
<li id="ready_set_go">
<h3>Ready, Set, Go!</h3>
<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>
<pre class="code">class block_simplehtml extends block_base {
function init() {
$this->title = get_string('simplehtml', 'block_simplehtml');
$this->version = 2004111200;
}
}</pre>
<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>
<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>
<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>
<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>
<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>
</li>
<li>
<h3>I Just Hear Static</h3>
<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>
<pre class="code">function get_content() {
if ($this->content !== NULL) {
return $this->content;
}
$this->content = new stdClass;
$this->content->text = 'The content of our SimpleHTML block!';
$this->content->footer = 'Footer here...';
return $this->content;
}</pre>
<p>It can't get any simpler than that, can it? Let's dissect this method to see what's going on...</p>
<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>
<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>
<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>
</li>
<li id="section_configure_that_out">
<h3>Configure That Out</h3>
<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>
<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>
<pre class="code">function instance_allow_config() {
return true;
}
</pre>
<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>
<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>
<pre class="code">
<table cellpadding="9" cellspacing="0">
<tr valign="top">
<td align="right">
<?php print_string('configcontent', 'block_simplehtml'); ?>:
</td>
<td>
<?php print_textarea(true, 10, 50, 0, 0, 'text', $this->config->text); ?>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="<?php print_string('savechanges') ?>" />
</td>
</tr>
</table>
<?php use_html_editor(); ?>
</pre>
<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>
<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>
<p>You also might be surprised by the presence of a submit button and the absence of any <form> element at the same time. But the truth is, we don't need to worry about that at all; Moodle goes a really long way to make things easier for developers! We just print the configuration options we want, in any format we want; include a submit button, and Moodle will handle all the rest itself. The instance configuration variables are automatically at our disposal to access from any of the class methods <em>except</em> <a class="function_title" href="#method_init">init</a>.</p>
<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>
<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>
<pre class="code">
$this->content = new stdClass;
$this->content->text = 'The content of our SimpleHTML block!';
$this->content->footer = 'Footer here...';</pre>
<p>and change it to:</p>
<pre class="code">
$this->content = new stdClass;
$this->content->text = $this->config->text;
$this->content->footer = 'Footer here...';</pre>
<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>
<pre class="code">
$this->content = new stdClass;
$this->content->text = $this->config->text;
$this->content->footer = '';</pre>
<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>
</li>
<li>
<h3>The Specialists</h3>
<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>
<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>
<pre class="code">
<tr valign="top">
<td align="right"><p><?php print_string('configtitle', 'block_simplehtml'); ?>:</td>
<td><input type="text" name="title" size="30" value="<?php echo $this->config->title; ?>" /></td>
</tr>
</pre>
<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>
<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>
<p>Let's pull out another ace from our sleeve, and add this small method to our block class:</p>
<pre class="code">
function specialization() {
$this->title = $this->config->title;
}</pre>
<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>
<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>
</li>
<li>
<h3>Now You See Me, Now You Don't</h3>
<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>
<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>
<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>
</li>
<li>
<h3>We Are Legion</h3>
<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>
<pre class="code">
function instance_allow_multiple() {
return true;
}</pre>
<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>
<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>
<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>
</li>
<li id="section_effects_of_globalization">
<h3>The Effects of Globalization</h3>
<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>
<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>
<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>
<pre class="code">
function has_config() {
return true;
}</pre>
<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>
<pre class="code">
<div style="text-align: center;">
<input type="hidden" name="block_simplehtml_strict" value="0" />
<input type="checkbox" name="block_simplehtml_strict" value="1"
<?php if(!empty($CFG->block_simplehtml_strict)) echo 'checked="checked"'; ?> />
<?php print_string('donotallowhtml', 'block_simplehtml'); ?>
<p><input type="submit" value="<?php print_string('savechanges'); ?>" /></p>
</div>
</pre>
<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>
<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>
<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>
<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>
<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>
<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>
<pre class="code">
function config_save($data) {
// Default behavior: save all variables as $CFG properties
foreach ($data as $name => $value) {
set_config($name, $value);
}
return true;
}</pre>
<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>
<pre class="code">
function config_save($data) {
if(isset($data['block_simplehtml_strict'])) {
set_config('block_simplehtml_strict', '1');
}
else {
set_config('block_simplehtml_strict', '0');
}
return true;
}</pre>
<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>
<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>
<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>
<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>
<pre class="code">
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);
}</pre>
<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>
<pre class="code">
function instance_config_save($data) {
// Clean the data if we have to
global $CFG;
if(!empty($CFG->block_simplehtml_strict)) {
$data['text'] = strip_tags($data['text']);
}
// And now forward to the default implementation defined in the parent class
return parent::instance_config_save($data);
}</pre>
<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>
<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>
<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>
<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>
</li>
<li id="section_eye_candy">
<h3>Eye Candy</h3>
<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>
<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>
<pre class="code">
function hide_header() {
return true;
}</pre>
<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>
<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>
<p>To instruct Moodle about our block's preferred width, we add one more method to the block class:</p>
<pre class="code">
function preferred_width() {
// The preferred value is in pixels
return 200;
}</pre>
<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>
<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 <table> 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>
<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>
<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>
<pre class="code">
function html_attributes() {
return array(
'class' => 'sideblock block_'. $this->name(),
'onmouseover' => 'alert("Mouseover on our block!");'
);
}</pre>
<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>
</li>
<li id="section_authorized_personnel_only">
<h3>Authorized Personnel Only</h3>
<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>
<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>
<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>
<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:
<ul>
<li>The format name for the front page of Moodle is <strong>site-index</strong>.</li>
<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>
<li>Even though there is no such page, the format name <strong>all</strong> can be used as a catch-all option.</li>
</ul>
</p>
<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?":
<ul>
<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>
<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>
<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>
<li>The order that the format names appear does not make any difference.</li>
</ul>
</p>
<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>
<pre class="code">
function applicable_formats() {
return array('site' => true);
}</pre>
<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>
<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>
<pre class="code">
function applicable_formats() {
return array('course-view' => true, 'course-view-social' => false);
}</pre>
<p>This time, we first allow the block to appear in all courses and then we explicitly disallow the social format.</p>
<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>
<pre class="code">
function applicable_formats() {
return array('site-index' => true,
'course-view' => true, 'course-view-social' => false,
'mod' => true, 'mod-quiz' => false);
}</pre>
<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>
<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>
</li>
<li>
<h3>Lists and Icons</h3>
<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>
<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>
<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 <img> tag, with "src", "height", "width" and "alt" attributes. Obviously, it makes sense to keep the images small and of a uniform size.</p>
<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>
<pre class="code">
class block_my_menu extends block_list {
// The init() method does not need to change at all
}
</pre>
<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>
<pre class="code">
function get_content() {
if ($this->content !== NULL) {
return $this->content;
}
$this->content = new stdClass;
$this->content->items = array();
$this->content->icons = array();
$this->content->footer = 'Footer here...';
$this->content->items[] = '<a href="some_file.php">Menu Option 1</a>';
$this->content->icons[] = '<img src="images/icons/1.gif" width="16" height="16" alt="" />';
// Add more list items here
return $this->content;
}</pre>
<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>
</li>
</ol>
<h2 id="appendix_a">Appendix A: Reference</h2>
<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>
<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>
<ul id="methods_reference">
<li><h3>Methods you can freely use and override:</h3>
<ul>
<li id="method_applicable_formats">
<div class="function_title">applicable_formats</div>
<pre class="code">
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);
}</pre>
<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>
<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>
<p>The full matching rules are:
<ul>
<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>
<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>
<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>
<li>The order that the format names appear does not make any difference.</li>
</ul>
</p>
</li>
<li id="method_config_print">
<div class="function_title">config_print</div>
<pre class="code">
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;
}</pre>
<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>
<ol>
<li>If you save your configuration options in $CFG, you will probably need to use global $CFG; before including any HTML configuration screens.</li>
<li>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 <strong>must</strong> provide a way to submit it (i.e., an <input type="submit" />.</li>
</ol>
<p>You should return a boolean value denoting the success or failure of your method's actions.</p>
</li>
<li id="method_config_save">
<div class="function_title">config_save</div>
<pre class="code">
function config_save($data) {
// Default behavior: save all variables as $CFG properties
// You don't need to override this if you 're satisfied with the above
foreach ($data as $name => $value) {
set_config($name, $value);
}
return true;
}</pre>
<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>
<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>
<p>You should return a boolean value denoting the success or failure of your method's actions.</p>
</li>
<li id="method_get_content">
<div class="function_title">get_content</div>
<pre class="code">
function get_content() {
// This should be implemented by the derived class.
return NULL;
}</pre>
<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:
<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>
<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 <img> tags <strong>and nothing else</strong>. $this->content->footer is a string, as above.</p>
<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>
<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>
<p>In any case, your method should return the fully constructed <a class="variable_title" href="#variable_content">$this->content</a> variable.</p>
</li>
<li id="method_has_config">
<div class="function_title">has_config</div>
<pre class="code">
function has_config() {
return false;
}</pre>
<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>
<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>
</li>
<li id="method_hide_header">
<div class="function_title">hide_header</div>
<pre class="code">
function hide_header() {
//Default, false--> the header is shown
return false;
}</pre>
<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>
</li>
<li id="method_html_attributes">
<div class="function_title">html_attributes</div>
<pre class="code">
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());
}</pre>
<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>
<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>
<pre class="code">
function html_attributes() {
$attrs = parent::html_attributes();
// Add your own attributes here, e.g.
// $attrs['width'] = '50%';
return $attrs;
}</pre>
</li>
<li id="method_init">
<div class="function_title">init</div>
<pre class="code">
function init() {
$this->title = get_string('simplehtml', 'block_simplehtml');
$this->version = 2004111200;
}</pre>
<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>
<p>No return value is expected from this method.</p>
</li>
<li id="method_instance_allow_config">
<div class="function_title">instance_allow_config</div>
<pre class="code">
function instance_allow_config() {
return false;
}</pre>
<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>
<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>
</li>
<li id="method_instance_allow_multiple">
<div class="function_title">instance_allow_multiple</div>
<pre class="code">
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;
}</pre>
<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>
</li>
<li id="method_instance_config_print">
<div class="function_title">instance_config_print</div>
<pre class="code">
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;
}</pre>
<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>
<p>You should return a boolean value denoting the success or failure of your method's actions.</p>
<li id="method_instance_config_save">
<div class="function_title">instance_config_save</div>
<pre class="code">
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);
}</pre>
<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>
<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>
<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>
<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>
<p>You should return a boolean value denoting the success or failure of your method's actions.</p>
</li>
<li id="method_preferred_width">
<div class="function_title">preferred_width</div>
<pre class="code">
function preferred_width() {
// Default case: the block wants to be 180 pixels wide
return 180;
}</pre>
<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>
<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>
</li>
<li id="method_refresh_content">
<div class="function_title">refresh_content</div>
<pre class="code">
function refresh_content() {
// Nothing special here, depends on content()
$this->content = NULL;
return $this->get_content();
}</pre>
<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>
<p>You should return the new value of <a class="variable_title" href="#variable_content">$this->content</a> after refreshing it.</p>
</li>
<li id="method_specialization">
<div class="function_title">specialization</div>
<pre class="code">
function specialization() {
// Just to make sure that this method exists.
}</pre>
<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>
<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>
<p>This method should not return anything at all.</p>
</li>
</ul>
<li><h3>Methods which you should <em>not</em> override but may want to use:</h3>
<ul>
<li id="method_instance_config_commit">
<div class="function_title">instance_config_commit</div>
<pre class="code">
function instance_config_commit() {
return set_field('block_instance',
'configdata', base64_encode(serialize($this->config)),
'id', $this->instance->id);
}</pre>
<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>
</li>
<li id="method_get_content_type">
<div class="function_title">get_content_type</div>
<pre class="code">
function get_content_type() {
return $this->content_type;
}</pre>
<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>
</li>
<li id="method_get_title">
<div class="function_title">get_title</div>
<pre class="code">
function get_title() {
return $this->title;
}</pre>
<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>
</li>
<li id="method_get_version">
<div class="function_title">get_version</div>
<pre class="code">
function get_version() {
return $this->version;
}</pre>
<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>
</li>
<li id="method_is_empty">
<div class="function_title">is_empty</div>
<p>For blocks that extend class <strong>block_base</strong>:</p>
<pre class="code">
function is_empty() {
$this->get_content();
return(empty($this->content->text) && empty($this->content->footer));
}</pre>
<p>For blocks that extend class <strong>block_list</strong>:</p>
<pre class="code">
function is_empty() {
$this->get_content();
return (empty($this->content->items) && empty($this->content->footer));
}
</pre>
<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>
</li>
<li id="method_name">
<div class="function_title">name</div>
<pre class="code">
function name() {
static $myname;
if ($myname === NULL) {
$myname = strtolower(get_class($this));
$myname = substr($myname, strpos($myname, '_') + 1);
}
return $myname;
}</pre>
<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>
</li>
</ul>
</li>
<li><h3>Methods which you should <em>not</em> override and <em>not</em> use at all:</h3>
<ul>
<li id="method__self_test">
<div class="function_title">_self_test</div>
<p>This is a private method; no description is given.</p>
</li>
<li id="method__add_edit_controls">
<div class="function_title">_add_edit_controls</div>
<p>This is a private method; no description is given.</p>
</li>
<li id="method__load_instance">
<div class="function_title">_load_instance</div>
<p>This is a private method; no description is given.</p>
</li>