<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
	<id>https://docs.moodle.org/dev/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Mohessaid</id>
	<title>MoodleDocs - User contributions [en]</title>
	<link rel="self" type="application/atom+xml" href="https://docs.moodle.org/dev/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Mohessaid"/>
	<link rel="alternate" type="text/html" href="https://docs.moodle.org/dev/Special:Contributions/Mohessaid"/>
	<updated>2026-11-20T23:41:49Z</updated>
	<subtitle>User contributions</subtitle>
	<generator>MediaWiki 1.43.5</generator>
	<entry>
		<id>https://docs.moodle.org/dev/index.php?title=Better_handling_of_overdue_quiz_attempts&amp;diff=56330</id>
		<title>Better handling of overdue quiz attempts</title>
		<link rel="alternate" type="text/html" href="https://docs.moodle.org/dev/index.php?title=Better_handling_of_overdue_quiz_attempts&amp;diff=56330"/>
		<updated>2019-08-18T10:05:05Z</updated>

		<summary type="html">&lt;p&gt;Mohessaid: There is no function such as &amp;#039;finish_attempt&amp;#039; anywhere even in version 2.3 like the documentation indicate. I replaced the method with &amp;#039;process_attempt&amp;#039; to correct the documentation.&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Infobox Project&lt;br /&gt;
|name = Handling of overdue quiz attempts&lt;br /&gt;
|state = Implementation complete. Testing.&lt;br /&gt;
|tracker = MDL-3030, MDL-4309&lt;br /&gt;
|discussion = [http://moodle.org/mod/forum/discuss.php?d=201355 Quiz forum thread about testing] [http://moodle.org/mod/forum/discuss.php?d=188534 Old Quiz forum thread about the proposal]&lt;br /&gt;
|assignee = [[User:Tim Hunt|Tim Hunt]]&lt;br /&gt;
}}&lt;br /&gt;
{{Moodle 2.3}}&lt;br /&gt;
&lt;br /&gt;
There is a tricky issue to do with what happens exactly when time runs on on a quiz. On the one hand, we want to let students use every second of time. On the other hand, the end of a quiz is often a time of high server load, and so Moodle is likely to responding slowly. Therefore, we have to prevent students from cheating on the time-limit while still processing their last-minute submission even if the server is heavily loaded.&lt;br /&gt;
&lt;br /&gt;
There is also the problem of what happens if the student just logs out and does not submit at all. At the moment the attempt goes into a sort of limbo where Moodle can&#039;t really do anything with it.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==What happens at the moment==&lt;br /&gt;
&lt;br /&gt;
Currently there are only really two states a quiz attempt can be in, and they are distinguished by whether quiz_attempts.timefinish is 0 or contains a time-stamp.&lt;br /&gt;
&lt;br /&gt;
[[Image:Quiz_attempt_states_now.png]]&lt;br /&gt;
&lt;br /&gt;
At most one attempt is allowed to be in the &#039;&#039;&#039;In progress&#039;&#039;&#039; state at any time.&lt;br /&gt;
&lt;br /&gt;
After time expires, (either because the time limit runs out, or the close date passes) the attempt is in a weird state. Well, not really, the attempt is still considered to be &#039;&#039;&#039;In progress&#039;&#039;&#039;, but the student is no longer allowed to access it, so there is no way to get at the &#039;&#039;&#039;Submit all and finish&#039;&#039;&#039; button to submit it. Also, if the quiz allows more than one attempt, the student cannot start a new attempt, because they already have an &#039;&#039;&#039;In progress&#039;&#039;&#039; attempt (which they are not allowed to access!)&lt;br /&gt;
&lt;br /&gt;
The known work-around is, as teacher, to:&lt;br /&gt;
# edit quiz settings to allow more time;&lt;br /&gt;
# login-as the student and submit the quiz;&lt;br /&gt;
# set the time-limit or close data back to what it should be.&lt;br /&gt;
This is a real pain.&lt;br /&gt;
&lt;br /&gt;
Before reading on, you may wish to remind yourself of the [[Quiz user interface overview]], so you know what the key scripts view/startattempt/attempt/processattempt/summar/review.php each do.&lt;br /&gt;
&lt;br /&gt;
To document the two existing transitions in some detail (note, all transitions are logged, I have not bothered to say that every time):&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Transition: Start attempt===&lt;br /&gt;
&lt;br /&gt;
Goes to: In progress&lt;br /&gt;
&lt;br /&gt;
Allowed when: If the student does not currently have any &#039;&#039;&#039;In progress&#039;&#039;&#039; attempt, and if they meet all the conditions imposed by the [[Quiz access rules|access rules]], they may start one.&lt;br /&gt;
&lt;br /&gt;
How it is done: The student clicks the &#039;&#039;&#039;Start attempt&#039;&#039;&#039; button on view.php. Technically, this takes the form of a POST request to startattempt.php.&lt;br /&gt;
&lt;br /&gt;
What happens:&lt;br /&gt;
# The attempt, and corresponding $quba, are created.&lt;br /&gt;
# They are initialised by adding all the questions, which may depend on randomisation, and &#039;each attempt builds on last&#039;.&lt;br /&gt;
# The attempt and all associated data is written to the database.&lt;br /&gt;
# A quiz_attempt_started event is raised. (This even it not used in standard Moodle.)&lt;br /&gt;
&lt;br /&gt;
===Transition: Submit all and finish===&lt;br /&gt;
&lt;br /&gt;
Goes from: In progress&lt;br /&gt;
&lt;br /&gt;
Goes to: Finished&lt;br /&gt;
&lt;br /&gt;
Allowed when: The student has an &#039;&#039;&#039;In progress&#039;&#039;&#039; attempt, which they are currently allowed to access according to the access rules. In particular, where the time limit has not run out, and the close date has not passed.&lt;br /&gt;
&lt;br /&gt;
How it is done: Either&lt;br /&gt;
* The student clicks the &#039;&#039;&#039;Submit all and finish&#039;&#039;&#039; button on summary.php; or&lt;br /&gt;
* Time runs out while the student is working on the quiz, and so the quiz is submitted automatically (if JavaScript is enabled).&lt;br /&gt;
Technically, this takes the form of a POST request to processattempt.php, althought the code that does the work is the quiz_attempt::process_attempt method in attemptlib.php.&lt;br /&gt;
&lt;br /&gt;
What happens:&lt;br /&gt;
# All questions that are not already finishes are finished.&lt;br /&gt;
# The updated question states are written to the database.&lt;br /&gt;
# The quiz_attempt record is updated with the timefinish and the total mark.&lt;br /&gt;
# The overall quiz grade (combining all the student&#039;s attempt scores) is updated, and stored in the gradebook.&lt;br /&gt;
# A quiz_attempt_submitted event is raised. (This is used by the quiz itself to send out any tutor or student notification messages that are enabled.)&lt;br /&gt;
&lt;br /&gt;
==Rough outline of the solution==&lt;br /&gt;
&lt;br /&gt;
We will introduce a new quiz settings &#039;&#039;&#039;When time expires&#039;&#039;&#039; and &#039;&#039;&#039;Grace period&#039;&#039;&#039;. When time expires is the strategy we will use for overdue attempts. For some strategies, they will need an amount of extra time that is the grace period. The possible strategies are:&lt;br /&gt;
&lt;br /&gt;
# Submit attempt automatically,&lt;br /&gt;
# Allow a grace period to submit, but not change any responses, or&lt;br /&gt;
# That&#039;s it. Tough luck! - &#039;&#039;we need a better name for this!&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
1. Corresponds to doing an automatic submit all and finish. 3. Corresponds to automatically moving the attempt to the &#039;&#039;&#039;Abandoned state&#039;&#039;&#039;. See below. 2. is more interesting (and is what the OU wants for assessed tests).&lt;br /&gt;
&lt;br /&gt;
If the student has not submitted their attempt when time runs out, then the attempt moves into the &#039;&#039;&#039;Overdue&#039;&#039;&#039; state. In this state, when the student tries to get to the quiz attempt, then can only go to the Summary page, where all they can do is to click the &#039;&#039;&#039;Submit all and finish&#039;&#039;&#039; button.&lt;br /&gt;
&lt;br /&gt;
If they finish submitted before the grace period runs out, then their attempt is counted.&lt;br /&gt;
&lt;br /&gt;
If the student still does not submit, then the attempt moves into the &#039;&#039;&#039;Abandoned&#039;&#039;&#039; state. This means that the student is not prevented from starting a new attempt, if the quiz allows it.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Question: should we allow the student to abandon the current attempt at any time? For example, if an interactive quiz allows multiple attempts, and the student has got off to a bad start, should we let them abandon and start again, or should we force them to &#039;&#039;&#039;Submit all and finish&#039;&#039;&#039; if they want a new attempt? - for now we will not allow students to abandon any attempt.&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
In addition, we will start storing the quiz_attempt.state explicitly in the database, rather than relying on deducing it from timefinish or other columns. In a sense this is redundant information, but since significant things happen when the state changes (e.g. a message might be sent) I think making the state, and hence the state transition, explicit, will make the code clearer.&lt;br /&gt;
&lt;br /&gt;
We will need code that detects when an attempt is in the &#039;wrong&#039; state. For example, if a state is stored in the database as &#039;&#039;&#039;In progress&#039;&#039;&#039;, but time has now expired, then we will need to detect that and correct it by triggering the correct state transition. I think we need to do this in two ways:&lt;br /&gt;
# Whenever we load an attempt from the database. This ensure that if the user is actively working on the quiz when a state transition is supposed to happen, they will immediately see the attempt change state.&lt;br /&gt;
# We will need to add a cron script that detects attempts becoming overdue when no-one is looking at them.&lt;br /&gt;
(Note there is a subtlety, the JavaScript timer that runs in the user&#039;s browser will try to automatically trigger a submit, they may be happening at the same time as a teacher is reviewing the attempt (which might trigger 1) and cron may also be running at the same time (which might trigger 2). Therefore, we need a clear protocol to avoid nasty race-conditions.&lt;br /&gt;
&lt;br /&gt;
Actually, a possible third way (instead of, or in addition to cron). Perhaps we should detect this when the quiz settings (or overrides) are edited, and check all attempts then and trigger state transitions. This might be a performance problem on quizzes with thousands of attempts.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==New state diagram==&lt;br /&gt;
&lt;br /&gt;
[[Image:Quiz_attempt_states.png]]&lt;br /&gt;
&lt;br /&gt;
At most one attempt can be in either the &#039;&#039;&#039;In progress&#039;&#039;&#039; or &#039;&#039;&#039;Overdue&#039;&#039;&#039; states at any time.&lt;br /&gt;
&lt;br /&gt;
The existing transitions need to be updated:&lt;br /&gt;
* They all need to set the new quiz_attempt.state column as part of What happens.&lt;br /&gt;
* The transition Submit all and finish can now also go from &#039;&#039;&#039;Overdue&#039;&#039;&#039; to &#039;&#039;&#039;Finished&#039;&#039;&#039;.&lt;br /&gt;
* When time runs out as a student is working on their quiz attempt, this should no longer trigger an automatic Submit all and finish. Instead it should trigger an automatic Time expires.&lt;br /&gt;
&lt;br /&gt;
The new transitions are:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Transition: Time expires===&lt;br /&gt;
&lt;br /&gt;
Goes from: In progress&lt;br /&gt;
&lt;br /&gt;
Goes to: Overdue&lt;br /&gt;
&lt;br /&gt;
Allowed when: Time expires, either due to the time-limit, the close date, or some other custom access rule; or because the teacher has edited the time limit and/or close date and shortened them; and when the overdue strategy is &amp;quot;Allow a grace period to submit, but not change any responses&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
How it is done: Detected automatically by the Moodle code, either because&lt;br /&gt;
* time has passed;&lt;br /&gt;
* the teacher has edited the quiz settings or overrides to shorten the time limit and/or close date; or&lt;br /&gt;
* triggered by the countdown timer JavaScript, in which case this will trigger a POST to processattempt.php.&lt;br /&gt;
&lt;br /&gt;
What happens:&lt;br /&gt;
# quiz_attempt.state is updated&lt;br /&gt;
# quiz_attempt_overdue event is raised. (The quiz will use this itself to send a warning message to the student, if that is enabled.)&lt;br /&gt;
# If the student is currently working on the quiz, they are redirected to the summary.php page.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Transition: Give up===&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;(not sure that is the best name)&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Goes from: Overdue / In progress&lt;br /&gt;
&lt;br /&gt;
Goes to: Abandoned&lt;br /&gt;
&lt;br /&gt;
Allowed when: Time expires, and the overdue strategy is &amp;quot;That&#039;s it. Tough luck!&amp;quot;; or the grace period expires when an attempt is in the &#039;&#039;&#039;Overdue&#039;&#039;&#039; state.&lt;br /&gt;
&lt;br /&gt;
How it is done: Detected automatically by the Moodle code, either because&lt;br /&gt;
* time has passed;&lt;br /&gt;
* the teacher has edited the quiz settings or overrides to shorten the time limit, close date and/or grace period; or&lt;br /&gt;
* triggered by the countdown timer JavaScript, in which case this will trigger a POST to processattempt.php; or&lt;br /&gt;
* if we decide to allow it, the student clicks a &#039;Give up button&#039;, perhaps on the summary page.&lt;br /&gt;
&lt;br /&gt;
What happens:&lt;br /&gt;
# quiz_attempt.state is updated&lt;br /&gt;
# quiz_attempt_abandoned event is raised. (For completeness. I don&#039;t foresee a use for this at the moment.)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Transition: Time limit extended===&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;This shows the kind of tricky thing that can happen. We have to consider what happens if the teacher edits the quiz settings to extend the time limit when an attempt has already been marked overdue.&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Goes from: Overdue&lt;br /&gt;
&lt;br /&gt;
Goes to: In progress&lt;br /&gt;
&lt;br /&gt;
Allowed when: The teacher edits the quiz settings or the overrides and extends the time limit.&lt;br /&gt;
&lt;br /&gt;
How it is done: Detected automatically by the Moodle code.&lt;br /&gt;
&lt;br /&gt;
What happens:&lt;br /&gt;
# quiz_attempt.state is updated&lt;br /&gt;
# quiz_attempt_restarted event is raised. (For completeness. I don&#039;t foresee a use for this at the moment.)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==What can be accessed when==&lt;br /&gt;
&lt;br /&gt;
For an &#039;&#039;&#039;In progress&#039;&#039;&#039;&#039; attempt: The student can access attempt.php and summary.php; the teacher can access review.php.&lt;br /&gt;
&lt;br /&gt;
For an &#039;&#039;&#039;Overdue&#039;&#039;&#039;&#039; attempt: The student can access review.php and summary.php; the teacher can access review.php.&lt;br /&gt;
&lt;br /&gt;
For a &#039;&#039;&#039;Finished&#039;&#039;&#039;&#039; attempt: The student and teacher can access review.php.&lt;br /&gt;
&lt;br /&gt;
For an &#039;&#039;&#039;Abandoned&#039;&#039;&#039;&#039; attempt: The student and teacher can access review.php.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Summary of changes==&lt;br /&gt;
&lt;br /&gt;
===Database changes===&lt;br /&gt;
&lt;br /&gt;
* New column quiz.overduehandling (char) to store which strategy we will use for overdue attempts.&lt;br /&gt;
* New column quiz.graceperiod (int) to store the time an attempt is allowed to remain in the &#039;&#039;&#039;Overdue&#039;&#039;&#039; state.&lt;br /&gt;
* New column quiz_attempt.state (char) to explicitly store the attempt state.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===New capability===&lt;br /&gt;
&lt;br /&gt;
* mod/quiz:emailwarnoverdue to control overdue warning messages.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===UI changes===&lt;br /&gt;
&lt;br /&gt;
* New fields &#039;When time expires&#039; and &#039;Grace period&#039; on the quiz settings form, with corresponding admin settings.&lt;br /&gt;
* Do we need even more columns of &#039;review options&#039; on the quiz settings form? (For example for &#039;&#039;&#039;Overdue&#039;&#039;&#039; and &#039;&#039;&#039;Abandoned&#039;&#039;&#039; attempts.) Perhaps it is time to move these settings to a separate page?&lt;br /&gt;
* Information about the grace period may need to be displayed on the quiz settings page, or on the summary page for overdue attempts.&lt;br /&gt;
* List of attempts on the view.php page needs to indicate the state of attempts.&lt;br /&gt;
* review.php page needs to indicate the attempt state.&lt;br /&gt;
* Display attempt state in the quiz reports where appropriate.&lt;br /&gt;
&lt;br /&gt;
==Rough work break-down==&lt;br /&gt;
&lt;br /&gt;
# &amp;lt;span style=&amp;quot;color:green&amp;quot;&amp;gt;Done!&amp;lt;/span&amp;gt; New quiz.overduehandling, quiz.graceperiod and quiz_attempt.state DB columns definition, upgrade code, backup &amp;amp; restore.&lt;br /&gt;
# &amp;lt;span style=&amp;quot;color:green&amp;quot;&amp;gt;Done!&amp;lt;/span&amp;gt; Overdue handling and Grace period setting on quiz form, with any validation. Verify create / edit works.&lt;br /&gt;
# &amp;lt;span style=&amp;quot;color:green&amp;quot;&amp;gt;Done!&amp;lt;/span&amp;gt; Implement back end of the three new transitions.&lt;br /&gt;
# &amp;lt;span style=&amp;quot;color:green&amp;quot;&amp;gt;Done!&amp;lt;/span&amp;gt; Code where attempts are loaded to identify attempts in the wrong state and trigger a transition if necessary.&lt;br /&gt;
# &amp;lt;span style=&amp;quot;color:green&amp;quot;&amp;gt;Done!&amp;lt;/span&amp;gt; Catch the quiz_attempt_overdue event and send an email.&lt;br /&gt;
# &amp;lt;span style=&amp;quot;color:green&amp;quot;&amp;gt;Done!&amp;lt;/span&amp;gt; Make attempt_state clear on the view page list of past attempts.&lt;br /&gt;
# &amp;lt;span style=&amp;quot;color:green&amp;quot;&amp;gt;Done!&amp;lt;/span&amp;gt; Update logic for the &#039;Start attempt button&#039;, and in startattempt.php so that for overdue attempts users are redirected to the summary page.&lt;br /&gt;
# &amp;lt;span style=&amp;quot;color:green&amp;quot;&amp;gt;Done!&amp;lt;/span&amp;gt; Update summary page to display appropriate information about overdue attempts.&lt;br /&gt;
# &amp;lt;span style=&amp;quot;color:green&amp;quot;&amp;gt;Done!&amp;lt;/span&amp;gt; Update processattempts.php so that it correctly handles one single submission after an attempt becomes overdue, and, for overdue attempts, will only redirect to the summary page.&lt;br /&gt;
# &amp;lt;span style=&amp;quot;color:green&amp;quot;&amp;gt;Done!&amp;lt;/span&amp;gt; Display the attempt state on the review page.&lt;br /&gt;
# &amp;lt;span style=&amp;quot;color:green&amp;quot;&amp;gt;Done!&amp;lt;/span&amp;gt; Add the attempt state to the overview and responses quiz reports (this will actually be a change in the base class).&lt;br /&gt;
# &amp;lt;span style=&amp;quot;color:green&amp;quot;&amp;gt;Done!&amp;lt;/span&amp;gt; Add new options to the attempt and overview reports to filter the report by attempt state. (We can probably usefully refactor the settings forms and preferences handling to extract a base class.)&lt;br /&gt;
# &amp;lt;span style=&amp;quot;color:red&amp;quot;&amp;gt;Out of scope&amp;lt;/span&amp;gt; While we are working here, we should really update these two reports to use the Moodle 2.x enrolment SQL, instead of get_users_by_capability.&lt;br /&gt;
# &amp;lt;span style=&amp;quot;color:green&amp;quot;&amp;gt;Done!&amp;lt;/span&amp;gt; Change the statistics report to analyse attempts with state = finished, rather than timefinish &amp;lt;&amp;gt; 0.&lt;br /&gt;
# &amp;lt;span style=&amp;quot;color:green&amp;quot;&amp;gt;Done!&amp;lt;/span&amp;gt; Cron to detect attempts in the wrong state and trigger state transitions.&lt;br /&gt;
# &amp;lt;span style=&amp;quot;color:green&amp;quot;&amp;gt;Done!&amp;lt;/span&amp;gt; Review all remaining occurrences of -&amp;gt;timefinish in the quiz code.&lt;br /&gt;
# &amp;lt;span style=&amp;quot;color:green&amp;quot;&amp;gt;Done!&amp;lt;/span&amp;gt; Check the quiz results block - no changes required.&lt;br /&gt;
# &amp;lt;span style=&amp;quot;color:red&amp;quot;&amp;gt;Out of scope&amp;lt;/span&amp;gt; - the official work-around is: &amp;quot;Don&#039;t do that&amp;quot;, at least for now - Deal with what happens when the teacher edits the quiz settings - which might change the times or the policies. Work out what to update.&lt;br /&gt;
&lt;br /&gt;
== Test script==&lt;br /&gt;
&lt;br /&gt;
The 3 examples at http://moodle.org/mod/forum/discuss.php?d=188534 are a good starting point. They just need to be elaborated.&lt;br /&gt;
&lt;br /&gt;
==Hypothetical other transitions==&lt;br /&gt;
&lt;br /&gt;
The following state-transitions can also be conceived, and could be implemented in the future, but they are out-of-scope for this proposal.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Transition: Reopen attempt===&lt;br /&gt;
&lt;br /&gt;
Goes from: Finished / Abandoned&lt;br /&gt;
&lt;br /&gt;
Goes to: In progress&lt;br /&gt;
&lt;br /&gt;
Allowed when: Time has not expired, and the current user has the appropriate capability.&lt;br /&gt;
&lt;br /&gt;
(For example, the student accidentally clicked Submit all and finish, and the teacher wants to be nice and undo that for them. Alternatively an attempt has become Abandoned because time ran out, but then the teacher extended the grace period or time limit, and so wants to re-open some attempts. In this case, the transition may go to &#039;&#039;&#039;Overdue&#039;&#039;&#039;, or perhaps that is a different transition, or perhaps the right way to handle that is to first transition to &#039;&#039;&#039;In progress&#039;&#039;&#039; and then transition to &#039;&#039;&#039;Overdue&#039;&#039;&#039;. I think it is clear why this is being considered out-of-scope.)&lt;br /&gt;
&lt;br /&gt;
How it is done: Probably clicking a button on the review page or in the quiz reports. This would probably be a POST to a new reopenattempt.php&lt;br /&gt;
&lt;br /&gt;
What happens: This is a bit tricky because lots of complex stuff happens on Submit all and finish that now needs to be undone, but I think a possible approach is to delete any question_attempts_steps added by the finish action (and any that follow them) and then use a regrade of the attempt to reset everything else.&lt;br /&gt;
&lt;br /&gt;
Actually, it is much easier to re-open an &#039;&#039;&#039;Abandoned&#039;&#039;&#039; attempt than a &#039;&#039;&#039;Finished&#039;&#039;&#039; one. Perhaps we should consider them two different transitions, or perhaps reopening an &#039;&#039;&#039;Abandoned&#039;&#039;&#039; attempt can be treated the same as Time limit extended.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
===Transition: Count this anyway===&lt;br /&gt;
&lt;br /&gt;
Goes from: Abandoned&lt;br /&gt;
&lt;br /&gt;
Goes to: Submitted&lt;br /&gt;
&lt;br /&gt;
Allowed when: The current user has the appropriate capability.&lt;br /&gt;
&lt;br /&gt;
(For example a teacher decides that even though the student abandoned their attempt, it should be counted anyway.)&lt;br /&gt;
&lt;br /&gt;
How it is done: Probably clicking a button on the review page or in the quiz reports. This would probably be a POST either to processattempt.php with extra arguments, or to a new script.&lt;br /&gt;
&lt;br /&gt;
What happens: Probably very similar to Submit all and finish.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==See also==&lt;br /&gt;
&lt;br /&gt;
* MDL-3030 Late quiz attempts should be closed automatically&lt;br /&gt;
* MDL-4309 Ability for late quizzes (with penalty)&lt;br /&gt;
* MDL-35322 Student didn&#039;t submit quiz, status is Never Submitted, version 2.3.1&lt;br /&gt;
* [[Quiz]] developer documentation&lt;br /&gt;
* Draft user documentation: [[Quiz time controls on attempts]]&lt;/div&gt;</summary>
		<author><name>Mohessaid</name></author>
	</entry>
	<entry>
		<id>https://docs.moodle.org/dev/index.php?title=Data_manipulation_API&amp;diff=55301</id>
		<title>Data manipulation API</title>
		<link rel="alternate" type="text/html" href="https://docs.moodle.org/dev/index.php?title=Data_manipulation_API&amp;diff=55301"/>
		<updated>2018-12-26T10:39:10Z</updated>

		<summary type="html">&lt;p&gt;Mohessaid: Omit an &amp;#039;is&amp;#039; from the sentence (typos)&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Moodle_2.0}}This page describes the functions available to access data in the Moodle database. You should &#039;&#039;&#039;exclusively&#039;&#039;&#039; use these functions in order to retrieve or modify database content because these functions provide a high level of abstraction and guarantee that your database manipulation will work against different RDBMSes.&lt;br /&gt;
&lt;br /&gt;
Where possible, tricks and examples will be documented here in order to make developers&#039; lives a bit easier. Of course, feel free to clarify, complete and add more information to  this documentation. It will be welcome, absolutely!&lt;br /&gt;
&lt;br /&gt;
== Main info ==&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Important note:&#039;&#039;&#039; All the functions shown on this page are for use in &#039;&#039;&#039;Moodle 2.0 upwards&#039;&#039;&#039;, where we changed the [[DB layer 2.0|DB layer]] to support some new features. If you need information for previous Moodle version, take a look to the [[DML functions - pre 2.0|DML functions - pre 2.0]] page. For a detailed reference of changes, see the [[DB layer 2.0 migration docs|migration docs]].&lt;br /&gt;
&lt;br /&gt;
* All the function calls on this page are public methods of the $DB global object, so you&#039;ll need to &amp;quot;import&amp;quot; it within your functions (not needed in global scripts) with one simple:&lt;br /&gt;
&amp;lt;code php&amp;gt;global $DB;&amp;lt;/code&amp;gt;&lt;br /&gt;
* The $DB global object is an instance of the moodle_database class, which is defined in [http://git.moodle.org/gw?p=moodle.git;a=blob;f=lib/dml/moodle_database.php;h=2a6676c84e7c77b0534f18a13ba584f58a8ed024;hb=refs/heads/master moodle_database.php]&lt;br /&gt;
* All the $table parameters in the functions are meant to be the table name &#039;&#039;without&#039;&#039; prefixes.&lt;br /&gt;
&amp;lt;code php&amp;gt;$user = $DB-&amp;gt;get_record(&#039;user&#039;, array(&#039;id&#039;=&amp;gt;&#039;1&#039;));&amp;lt;/code&amp;gt;&lt;br /&gt;
* When using the xxx_sql() functions, table names must be enclosed between curly braces.&lt;br /&gt;
&amp;lt;code php&amp;gt;$user = $DB-&amp;gt;get_record_sql(&#039;SELECT * FROM {user} WHERE id = ?&#039;, array(1));&amp;lt;/code&amp;gt;&lt;br /&gt;
* All the $conditions parameters in the functions are arrays of fieldname=&amp;gt;fieldvalue elements.&lt;br /&gt;
&amp;lt;code php&amp;gt;$user = $DB-&amp;gt;get_record(&#039;user&#039;, array(&#039;firstname&#039;=&amp;gt;&#039;Martin&#039;, &#039;lastname&#039;=&amp;gt;&#039;Dougiamas&#039;));&amp;lt;/code&amp;gt;&lt;br /&gt;
* All the $params parameters in the functions are arrays of values used to fill placeholders in SQL statements. Both the question mark and named placeholders can be used. Note that named params &#039;&#039;&#039;must be unique&#039;&#039;&#039; even if the value passed is the same.&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
/// Question mark placeholders:&lt;br /&gt;
   $DB-&amp;gt;get_record_sql(&#039;SELECT * FROM {user} WHERE firstname = ? AND lastname = ?&#039;, &lt;br /&gt;
                       array(&#039;Martin&#039;, &#039;Dougiamas&#039;));&lt;br /&gt;
&lt;br /&gt;
/// Named placeholders:&lt;br /&gt;
   $DB-&amp;gt;get_record_sql(&#039;SELECT * FROM {user} WHERE firstname = :firstname AND lastname = :lastname&#039;,&lt;br /&gt;
                       array(&#039;firstname&#039;=&amp;gt;&#039;Martin&#039;, &#039;lastname&#039;=&amp;gt;&#039;Dougiamas&#039;));&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== The functions ==&lt;br /&gt;
&lt;br /&gt;
===Getting a single record===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
o $DB-&amp;gt;get_record($table, array $conditions, $fields=&#039;*&#039;, $strictness=IGNORE_MISSING) &lt;br /&gt;
  /// Get a single database record as an object where all the given conditions met.&lt;br /&gt;
  /// @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;&lt;br /&gt;
  ///                        IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);&lt;br /&gt;
  ///                        MUST_EXIST means throw exception if no record or multiple records found&lt;br /&gt;
o $DB-&amp;gt;get_record_select($table, $select, array $params=null, $fields=&#039;*&#039;, $strictness=IGNORE_MISSING)&lt;br /&gt;
  /// Get a single database record as an object which match a particular WHERE clause.&lt;br /&gt;
o $DB-&amp;gt;get_record_sql($sql, array $params=null, $strictness=IGNORE_MISSING)&lt;br /&gt;
  /// Get a single database record as an object using a SQL statement.&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Getting a hashed array of records===&lt;br /&gt;
Each of the following methods return an array of objects. The array is indexed by the first column of the fields returned by the query. Thus to assure consistent data, it appears to be best practice to ensure that your query include an &amp;quot;id column&amp;quot; as the first field. (When developing custom tables, be sure to make id your first column for this reason!)&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
o $DB-&amp;gt;get_records($table, array $conditions=null, $sort=&#039;&#039;, $fields=&#039;*&#039;, $limitfrom=0, $limitnum=0) &lt;br /&gt;
  /// Get a number of records as an array of objects where all the given conditions met.&lt;br /&gt;
o $DB-&amp;gt;get_records_select($table, $select, array $params=null, $sort=&#039;&#039;, $fields=&#039;*&#039;, $limitfrom=0, $limitnum=0) &lt;br /&gt;
  /// Get a number of records as an array of objects which match a particular WHERE clause.&lt;br /&gt;
o $DB-&amp;gt;get_records_sql($sql, array $params=null, $limitfrom=0, $limitnum=0)&lt;br /&gt;
  /// Get a number of records as an array of objects using a SQL statement.&lt;br /&gt;
o $DB-&amp;gt;get_records_list($table, $field, array $values, $sort=&#039;&#039;, $fields=&#039;*&#039;, $limitfrom=&#039;&#039;, $limitnum=&#039;&#039;) &lt;br /&gt;
  /// Get a number of records as an array of objects where one field match one list of values.&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Getting data as key/value pairs in an associative array===&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
o $DB-&amp;gt;get_records_menu($table, array $conditions=null, $sort=&#039;&#039;, $fields=&#039;*&#039;, $limitfrom=0, $limitnum=0) &lt;br /&gt;
  /// Get the first two columns from a number of records as an associative array where all the given conditions met.&lt;br /&gt;
o $DB-&amp;gt;get_records_select_menu($table, $select, array $params=null, $sort=&#039;&#039;, $fields=&#039;*&#039;, $limitfrom=0, $limitnum=0)&lt;br /&gt;
  /// Get the first two columns from a number of records as an associative array which match a particular WHERE clause.&lt;br /&gt;
o $DB-&amp;gt;get_records_sql_menu($sql, array $params=null, $limitfrom=0, $limitnum=0)&lt;br /&gt;
  /// Get the first two columns from a number of records as an associative array using a SQL statement.&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Seeing how many records match a given criterion===&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
o $DB-&amp;gt;count_records($table, array $conditions=null) &lt;br /&gt;
  /// Count the records in a table where all the given conditions met.&lt;br /&gt;
o $DB-&amp;gt;count_records_select($table, $select, array $params=null, $countitem=&amp;quot;COUNT(&#039;x&#039;)&amp;quot;) &lt;br /&gt;
  /// Count the records in a table which match a particular WHERE clause.&lt;br /&gt;
o $DB-&amp;gt;count_records_sql($sql, array $params=null) &lt;br /&gt;
  /// Get the result of an SQL SELECT COUNT(...) query.&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Seeing if one record exists===&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
o $DB-&amp;gt;record_exists($table, array $conditions=null) &lt;br /&gt;
  /// Test whether a record exists in a table where all the given conditions met.&lt;br /&gt;
o $DB-&amp;gt;record_exists_select($table, $select, array $params=null) &lt;br /&gt;
  /// Test whether any records exists in a table which match a particular WHERE clause.&lt;br /&gt;
o $DB-&amp;gt;record_exists_sql($sql, array $params=null) &lt;br /&gt;
  /// Test whether a SQL SELECT statement returns any records.&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Examples====&lt;br /&gt;
=====moodle_database::get_records()=====&lt;br /&gt;
Get a number of records as an array of objects where all the given conditions met.&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
///Get all records where foo = bar&lt;br /&gt;
$result = $DB-&amp;gt;get_records($table,array(&#039;foo&#039;=&amp;gt;&#039;bar&#039;));&lt;br /&gt;
&lt;br /&gt;
///Get all records where foo = bar and jon = doe&lt;br /&gt;
$result = $DB-&amp;gt;get_records($table,array(&#039;foo&#039; =&amp;gt; &#039;bar&#039; , &#039;jon&#039; =&amp;gt; &#039;doe&#039;));&lt;br /&gt;
&lt;br /&gt;
///Get all records where foo = bar, but only return the fields foo,bar,jon,doe&lt;br /&gt;
$result = $DB-&amp;gt;get_records($table,array(&#039;foo&#039;=&amp;gt;&#039;bar&#039;),null,&#039;foo,bar,jon,doe&#039;);&lt;br /&gt;
///The previous example would cause data issues unless the &#039;foo&#039; field happens to have unique values.&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=====moodle_database::get_records_select()=====&lt;br /&gt;
Get a number of records as an array of objects which match a particular WHERE clause. Note that the array keys will be the id of the object so you must not rely on the first item having a key of 0.&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
///Get all records where jon = &#039;doe&#039; and bob is not = &#039;tom&#039;&lt;br /&gt;
///The &#039;select&#039; parameter is (if not empty) is dropped directly into the WHERE clause without alteration.&lt;br /&gt;
$table = &#039;foo&#039;;&lt;br /&gt;
$select = &amp;quot;jon = &#039;doe&#039; AND bob &amp;lt;&amp;gt; &#039;tom&#039;&amp;quot;; //is put into the where clause&lt;br /&gt;
$result = $DB-&amp;gt;get_records_select($table,$select);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=====moodle_database::get_records_sql()=====&lt;br /&gt;
Get a number of records as an array of objects using a SQL statement. Defined as an abstract function in moodle_database, this method is implemented per database type.&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
///Get all records from &#039;table&#039; where foo = bar&lt;br /&gt;
$result = $DB-&amp;gt;get_records_sql(&#039;SELECT * FROM {table} WHERE foo = ?&#039;, array(&#039;bar&#039;));&lt;br /&gt;
&lt;br /&gt;
///Get all records from &#039;table&#039; where foo = &#039;bar&#039; and bob = &#039;tom&#039;&lt;br /&gt;
///This is somewhat similar to how Drupal makes its queries&lt;br /&gt;
$result = $DB-&amp;gt;get_records_sql(&#039;SELECT * FROM {table} WHERE foo = ? AND bob = ?&#039;, array( &#039;bar&#039; , &#039;tom&#039; ));&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=====moodle_database::get_records_list()=====&lt;br /&gt;
Get a number of records as an array of objects where one field match one list of values.&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
///Get all records where the values(&#039;bar&#039;, &#039;elephant&#039;, &#039;moodle&#039;) are found in the field &#039;foo&#039;&lt;br /&gt;
$result = $DB-&amp;gt;get_records_list($table, &#039;foo&#039;, array( &#039;bar&#039;, &#039;elephant&#039;, &#039;moodle&#039;));&lt;br /&gt;
&lt;br /&gt;
///Get all records where the values(&#039;bar&#039;, &#039;elephant&#039;, &#039;moodle&#039;) are found in the field &#039;foo&#039;&lt;br /&gt;
///Only returning the fields &#039;id&#039;, &#039;test&#039; and &#039;taco&#039;&lt;br /&gt;
$result = $DB-&amp;gt;get_records_list($table, &#039;foo&#039;, array( &#039;bar&#039;, &#039;elephant&#039;, &#039;moodle&#039;), null, &#039;id,test,taco&#039;);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=====moodle_database::get_records_menu()=====&lt;br /&gt;
Get the first two columns from a number of records as an associative array where all the given conditions met. &lt;br /&gt;
You can choose the two fields or leave the parameter blank and the method will return the first two columns of the table.&lt;br /&gt;
Returns an associative array. &lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
///Get all records from table &#039;foo&#039; where column &#039;foo&#039; is equal to the value &#039;bar&#039;&lt;br /&gt;
$table = &#039;foo&#039;; ///name of table&lt;br /&gt;
$conditions = array(&#039;foo&#039;=&amp;gt;&#039;bar&#039;); ///the name of the field (key) and the desired value&lt;br /&gt;
&lt;br /&gt;
$result = $DB-&amp;gt;get_records_menu($table,$conditions));&lt;br /&gt;
&lt;br /&gt;
///Get all records from table &#039;foo&#039; where column &#039;foo&#039; is equal to the value &#039;bar&#039;&lt;br /&gt;
///Returning the values from the columns &#039;id&#039; and &#039;tacos&#039;&lt;br /&gt;
$table = &#039;foo&#039;; ///name of table&lt;br /&gt;
$conditions = array(&#039;foo&#039;=&amp;gt;&#039;bar&#039;); ///the name of the field (key) and the desired value&lt;br /&gt;
$sort = &#039;id&#039;; //field or fields you want to sort the result by&lt;br /&gt;
$fields = &#039;id, tacos&#039;; ///list of fields to return&lt;br /&gt;
&lt;br /&gt;
$result = $DB-&amp;gt;get_records_menu($table,$conditions,$sort,$fields));  //If you do not specify $fields, the first two columns of the table will be returned&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
The result of this last example will look something like:&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
/// The value of the id field  is 909 and the value of the &#039;tacos&#039; column is 6&lt;br /&gt;
array(1) { [909]=6 }&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=====moodle_database::get_records_select_menu()=====&lt;br /&gt;
Get the first two columns from a number of records as an associative array which match a particular WHERE clause.&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
///Get all records where jon = &#039;doe&#039; and bob is not = &#039;tom&#039;&lt;br /&gt;
///The &#039;select&#039; parameter is (if not empty) is dropped directly into the WHERE clause without alteration.&lt;br /&gt;
$table = &#039;foo&#039;;&lt;br /&gt;
$select = &#039;jon = ? AND bob &amp;lt;&amp;gt; ? &#039;; //is put into the where clause&lt;br /&gt;
$result = $DB-&amp;gt;get_records_select_menu($table, $select, array(&#039;doe&#039;, &#039;tom&#039;));&lt;br /&gt;
&lt;br /&gt;
$table = &#039;foo&#039;;&lt;br /&gt;
$select = &#039;jon = ? AND bob &amp;lt;&amp;gt; ? &#039;; //is put into the where clause&lt;br /&gt;
$params = array(&#039;doe&#039;, &#039;tom&#039;);&lt;br /&gt;
$fields = &#039;id, tacos&#039;;//return these fields&lt;br /&gt;
$sort = &#039;id&#039;; //field or fields you want to sort the result by&lt;br /&gt;
$result = $DB-&amp;gt;get_records_select_menu($table,$select,$params,$sort,$fields);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The result of this last example will look something like:&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
/// The value of the id field  is 909 and the value of the &#039;tacos&#039; column is 6&lt;br /&gt;
array(1) { [909]=6 }&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=====moodle_database::get_records_sql_menu()=====&lt;br /&gt;
Get the first two columns from a number of records as an associative array using a SQL statement.&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
///Get all records from table foo where bar = 6&lt;br /&gt;
$sql = &#039;SELECT * FROM foo WHERE bar = ?&#039;;&lt;br /&gt;
$params = array(6);&lt;br /&gt;
&lt;br /&gt;
$result = $DB-&amp;gt;get_records_sql_menu($sql,$params);&lt;br /&gt;
&lt;br /&gt;
///Get all records from table foo where bar = 6&lt;br /&gt;
$sql = &#039;SELECT id,tacos FROM foo WHERE bar = ?&#039;;&lt;br /&gt;
$params = array(6);&lt;br /&gt;
&lt;br /&gt;
$result = $DB-&amp;gt;get_records_sql_menu($sql,$params);&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The result of this last example will look something like:&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
/// The value of the id field  is 909 and the value of the &#039;tacos&#039; column is 6&lt;br /&gt;
array(1) { [909]=6 } &lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Getting a particular field value from one record===&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
o $DB-&amp;gt;get_field($table, $return, array $conditions, $strictness=IGNORE_MISSING)&lt;br /&gt;
  /// Get a single field value from a table record where all the given conditions met.&lt;br /&gt;
  /// @param int $strictness&lt;br /&gt;
  ///   IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;&lt;br /&gt;
  ///   IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);&lt;br /&gt;
  ///   MUST_EXIST means throw exception if no record or multiple records found&lt;br /&gt;
o $DB-&amp;gt;get_field_select($table, $return, $select, array $params=null, $strictness=IGNORE_MISSING)&lt;br /&gt;
  /// Get a single field value from a table record which match a particular WHERE clause.&lt;br /&gt;
o $DB-&amp;gt;get_field_sql($sql, array $params=null, $strictness=IGNORE_MISSING)&lt;br /&gt;
  /// Get a single field value (first field) using a SQL statement.&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Getting a particular field value from various records===&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
o $DB-&amp;gt;get_fieldset_select($table, $return, $select, array $params=null)&lt;br /&gt;
  /// Selects records and return values of chosen field as an array which match a particular WHERE clause.&lt;br /&gt;
o $DB-&amp;gt;get_fieldset_sql($sql, array $params=null)&lt;br /&gt;
  /// Selects records and return values (first field) as an array using a SQL statement.&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Setting a particular field in the database===&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
o $DB-&amp;gt;set_field($table, $newfield, $newvalue, array $conditions=null)&lt;br /&gt;
  /// Set a single field in every table record where all the given conditions met.&lt;br /&gt;
o $DB-&amp;gt;set_field_select($table, $newfield, $newvalue, $select, array $params=null)&lt;br /&gt;
  /// Set a single field in every table record which match a particular WHERE clause.&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Deleting Records===&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
o $DB-&amp;gt;delete_records($table, array $conditions=null) &lt;br /&gt;
  /// Delete the records from a table where all the given conditions met.&lt;br /&gt;
o $DB-&amp;gt;delete_records_select($table, $select, array $params=null)&lt;br /&gt;
  /// Delete one or more records from a table which match a particular WHERE clause.&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Inserting Records===&lt;br /&gt;
The method to insert records is called aptly enough, insert_record(). The method accepts 4 parameters, but the fourth, &amp;quot;bulk&amp;quot;, in most implementations is unused. Note, you cannot specify the record id using this method. If you need to specify an id use $DB-&amp;gt;insert_record_raw() with $customsequence set to true or use $DB-&amp;gt;execute().&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
  $DB-&amp;gt;insert_record($table, $dataobject, $returnid=true, $bulk=false) &lt;br /&gt;
  /// Insert a record into a table and return the &amp;quot;id&amp;quot; field if required.&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Starting with Moodle 2.7, you can do bulk record inserts using the following method call: {{Moodle_2.7}} &lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
/**&lt;br /&gt;
* Insert multiple records into database as fast as possible.&lt;br /&gt;
*&lt;br /&gt;
* Order of inserts is maintained, but the operation is not atomic, use transactions if necessary.&lt;br /&gt;
*&lt;br /&gt;
* This method is intended for inserting of large number of small objects, do not use for huge objects with text or binary fields.&lt;br /&gt;
*&lt;br /&gt;
* @param string $table  The database table to be inserted into&lt;br /&gt;
* @param array|Traversable $dataobjects list of objects to be inserted, must be compatible with foreach&lt;br /&gt;
* @return void&lt;br /&gt;
*/&lt;br /&gt;
  $DB-&amp;gt;insert_records($table, $dataobjects)&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Example(s)====&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$record = new stdClass();&lt;br /&gt;
$record-&amp;gt;name         = &#039;overview&#039;;&lt;br /&gt;
$record-&amp;gt;displayorder = &#039;10000&#039;;&lt;br /&gt;
$lastinsertid = $DB-&amp;gt;insert_record(&#039;quiz_report&#039;, $record, false);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$record1 = new stdClass();&lt;br /&gt;
$record1-&amp;gt;name         = &#039;overview&#039;;&lt;br /&gt;
$record1-&amp;gt;displayorder = &#039;10000&#039;;&lt;br /&gt;
$record2 = new stdClass();&lt;br /&gt;
$record2-&amp;gt;name         = &#039;overview&#039;;&lt;br /&gt;
$record2-&amp;gt;displayorder = &#039;10000&#039;;&lt;br /&gt;
$records = array($record1, $record2);&lt;br /&gt;
$DB-&amp;gt;insert_records(&#039;quiz_report&#039;, $records);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Updating Records===&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
o $DB-&amp;gt;update_record($table, $dataobject, $bulk=false)&lt;br /&gt;
  /// Update a record in a table.&lt;br /&gt;
  /// &lt;br /&gt;
  /// $dataobject is an object containing needed data&lt;br /&gt;
  /// Relies on $dataobject having a variable &amp;quot;id&amp;quot; to&lt;br /&gt;
  /// specify the record to update&lt;br /&gt;
  /// &lt;br /&gt;
  /// @param string $table The database table to be checked against.&lt;br /&gt;
  /// @param object $dataobject An object with contents equal to fieldname=&amp;gt;fieldvalue.&lt;br /&gt;
  ///        Must have an entry for &#039;id&#039; to map to the table specified.&lt;br /&gt;
  /// @param bool $bulk true means repeated updates expected&lt;br /&gt;
  /// @return bool true&lt;br /&gt;
  /// @throws dml_exception if an error occurs.&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If you need to perform a more complex update using arbitrary SQL, you can use the &#039;execute&#039; method. Only use this when nothing more specific will work&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
o $DB-&amp;gt;execute($sql, array $params=null)&lt;br /&gt;
  /// Executes a general sql query. Should be used only when no other method suitable.&lt;br /&gt;
  /// Do NOT use this to make changes in db structure, use database_manager methods instead!&lt;br /&gt;
  /// @param string $sql query&lt;br /&gt;
  /// @param array $params query parameters&lt;br /&gt;
  /// @return bool true&lt;br /&gt;
  /// @throws dml_exception A DML specific exception is thrown for any errors.&lt;br /&gt;
 &amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Using Recordsets===&lt;br /&gt;
&lt;br /&gt;
Where the number of records to be retrieved from DB is high, the &#039;&#039;&#039;get_records_xxx()&#039;&#039;&#039; functions above are far from optimal, because they load all the records in memory at the same time. Under those circumstances, it is highly recommended to use these &#039;&#039;&#039;get_recordset_xxx()&#039;&#039;&#039; functions instead, which use one nice mechanism to iterate over all the target records and save a lot of memory.&lt;br /&gt;
&lt;br /&gt;
Only one thing is &#039;&#039;&#039;absolutely important&#039;&#039;&#039;: Don&#039;t forget to close the recordsets after using them! (This will free up a lot of resources in the RDBMS).&lt;br /&gt;
&lt;br /&gt;
Here is the general way to iterate over records using the &#039;&#039;&#039;get_recordset_xxx()&#039;&#039;&#039; functions:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$rs = $DB-&amp;gt;get_recordset(....) {&lt;br /&gt;
foreach ($rs as $record) {&lt;br /&gt;
    // Do whatever you want with this record&lt;br /&gt;
}&lt;br /&gt;
$rs-&amp;gt;close(); // Don&#039;t forget to close the recordset!&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
And this is the list of available functions (100% paired with the get_records_xxx() above):&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
o $DB-&amp;gt;get_recordset($table, array $conditions=null, $sort=&#039;&#039;, $fields=&#039;*&#039;, $limitfrom=0, $limitnum=0) &lt;br /&gt;
  /// Get a number of records as a moodle_recordset where all the given conditions met.&lt;br /&gt;
o $DB-&amp;gt;get_recordset_select($table, $select, array $params=null, $sort=&#039;&#039;, $fields=&#039;*&#039;, $limitfrom=0, $limitnum=0) &lt;br /&gt;
  /// Get a number of records as a moodle_recordset which match a particular WHERE clause.&lt;br /&gt;
o $DB-&amp;gt;get_recordset_sql($sql, array $params=null, $limitfrom=0, $limitnum=0);&lt;br /&gt;
  /// Get a number of records as a moodle_recordset using a SQL statement.&lt;br /&gt;
 &lt;br /&gt;
o $DB-&amp;gt;get_recordset_list($table, $field=&#039;&#039;, $values=&#039;&#039;, $sort=&#039;&#039;, $fields=&#039;*&#039;, $limitfrom=&#039;&#039;, $limitnum=&#039;&#039;) &lt;br /&gt;
  /// Get a number of records as a moodle_recordset where one field matches one list of values.&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Unlike get_record functions, you cannot use &amp;lt;tt&amp;gt;$rs == true&amp;lt;/tt&amp;gt; or &amp;lt;tt&amp;gt;!empty($rs)&amp;lt;/tt&amp;gt; to determine if any records were found.&lt;br /&gt;
Recordsets implement the standard PHP Iterator interface (http://uk.php.net/manual/en/class.iterator.php)&lt;br /&gt;
&lt;br /&gt;
So,&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
if ($rs-&amp;gt;valid()) {&lt;br /&gt;
    // The recordset contains records.&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Delegated transactions===&lt;br /&gt;
&lt;br /&gt;
* Please note some databases do not support transactions (such as the MyISAM MySQL database engine), however all server administrators are strongly encouraged to migrate to databases that support transactions (such as the InnoDB MySQL database engine).&lt;br /&gt;
* Previous versions supported only one level of transaction. Since Moodle 2.0, the DML layer emulates delegated transactions that allow nesting of transactions.&lt;br /&gt;
* Transactions should not be used much in Moodle core; they are intended for various plugins such as web services, enrol and auth plugins.&lt;br /&gt;
* Some subsystems (such as messaging) do not support transactions because it is not possible to rollback in external systems.&lt;br /&gt;
&lt;br /&gt;
A transaction is started by:&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$transaction = $DB-&amp;gt;start_delegated_transaction();&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
and finished by:&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$transaction-&amp;gt;allow_commit();&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Usually a transaction is rolled back when an exception is thrown. &amp;lt;code&amp;gt;$transaction-&amp;gt;rollback($ex);&amp;lt;/code&amp;gt; must be used very carefully because it might break compatibility with databases that do not support transactions. Transactions cannot be used as part of expected code flow; they can be used only as an emergency protection of data consistency.&lt;br /&gt;
&lt;br /&gt;
See more details in [[DB layer 2.0 delegated transactions]] or MDL-20625.&lt;br /&gt;
&lt;br /&gt;
====Example(s)====&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
global $DB;&lt;br /&gt;
try {&lt;br /&gt;
     $transaction = $DB-&amp;gt;start_delegated_transaction();&lt;br /&gt;
     // Insert a record&lt;br /&gt;
     $DB-&amp;gt;insert_record(&#039;foo&#039;, $object);&lt;br /&gt;
     $DB-&amp;gt;insert_record(&#039;bar&#039;, $otherobject);&lt;br /&gt;
&lt;br /&gt;
     // Assuming the both inserts work, we get to the following line.&lt;br /&gt;
     $transaction-&amp;gt;allow_commit();&lt;br /&gt;
} catch(Exception $e) {&lt;br /&gt;
     $transaction-&amp;gt;rollback($e);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===SQL compatibility functions===&lt;br /&gt;
&lt;br /&gt;
In order have real cross-db compatibility, there are some helper functions used to build SQL fragments based on the DB Moodle is running. Using them we&#039;ll avoid conditional queries here and there and have those &amp;quot;incompatibilities&amp;quot; fixed once and for ever.&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
o $DB-&amp;gt;sql_bitand($int1, $int2) &lt;br /&gt;
  /// Returns the SQL text to be used in order to perform one bitwise AND &lt;br /&gt;
  /// operation between 2 integers.&lt;br /&gt;
o $DB-&amp;gt;sql_bitnot($int1) &lt;br /&gt;
  /// Returns the SQL text to be used in order to perform one bitwise NOT &lt;br /&gt;
  /// operation with 1 integer.&lt;br /&gt;
o $DB-&amp;gt;sql_bitor($int1, $int2)&lt;br /&gt;
  /// Returns the SQL text to be used in order to perform one bitwise OR &lt;br /&gt;
  /// operation between 2 integers.&lt;br /&gt;
o $DB-&amp;gt;sql_bitxor($int1, $int2) &lt;br /&gt;
  /// Returns the SQL text to be used in order to perform one bitwise XOR &lt;br /&gt;
  /// operation between 2 integers.&lt;br /&gt;
 &lt;br /&gt;
o $DB-&amp;gt;sql_null_from_clause()&lt;br /&gt;
  /// Returns the FROM clause required by some DBs in all SELECT statements.&lt;br /&gt;
 &lt;br /&gt;
o $DB-&amp;gt;sql_ceil($fieldname)&lt;br /&gt;
  /// Returns the correct CEIL expression applied to fieldname.&lt;br /&gt;
o $DB-&amp;gt;sql_equal($fieldname, $param, $casesensitive = true, $accentsensitive = true, $notequal = false) (available since Moodle 3.2)&lt;br /&gt;
  /// Returns the proper SQL to perform cross-db varchar comparisons when case-sensitiveness is mission-critical.&lt;br /&gt;
o $DB-&amp;gt;sql_like($fieldname, $param, $casesensitive = true, $accentsensitive = true, $notlike = false, $escapechar = &#039; \\ &#039;)&lt;br /&gt;
  /// Returns the proper SQL to do LIKE. For example:&lt;br /&gt;
  $DB-&amp;gt;get_records_sql(&#039;SELECT ...  WHERE &#039;.$DB-&amp;gt;sql_like(&#039;idnumber&#039;, &#039;:idnum&#039;).&#039; ... &#039;, array( &#039;idnum&#039; =&amp;gt; &#039;%foo%&#039;));&lt;br /&gt;
  /// Note: Apply $DB-&amp;gt;sql_like_escape(...) to the param values when its user input from a form. Don&#039;t forget to add the % character(s) to the param value&lt;br /&gt;
&lt;br /&gt;
o $DB-&amp;gt;sql_length($fieldname)&lt;br /&gt;
  /// Returns the SQL text to be used to calculate the length in characters of one expression.&lt;br /&gt;
o $DB-&amp;gt;sql_modulo($int1, $int2)&lt;br /&gt;
  /// Returns the SQL text to be used in order to calculate module - remainder after division&lt;br /&gt;
o $DB-&amp;gt;sql_position($needle, $haystack)&lt;br /&gt;
  /// Returns the SQL for returning searching one string for the location of another.&lt;br /&gt;
  /// Note: If using placeholders BOTH in $needle and $haystack, they MUST be named placeholders.&lt;br /&gt;
o $DB-&amp;gt;sql_substr($expr, $start, $length=false)&lt;br /&gt;
  /// Returns the proper substr() SQL text used to extract substrings from DB.&lt;br /&gt;
  /// Note: This fuction has changed in Moodle 2.0 and now at least 2 params are mandatory.&lt;br /&gt;
  /// Note: Now it returns the whole SQL text to be used instead of only the function name.&lt;br /&gt;
 &lt;br /&gt;
o $DB-&amp;gt;sql_cast_char2int($fieldname, $text=false)&lt;br /&gt;
  /// Returns the SQL to be used in order to CAST one CHAR column to INTEGER.&lt;br /&gt;
o $DB-&amp;gt;sql_cast_char2real($fieldname, $text=false)&lt;br /&gt;
  /// Returns the SQL to be used in order to CAST one CHAR column to REAL number.&lt;br /&gt;
 &lt;br /&gt;
o $DB-&amp;gt;sql_compare_text($fieldname, $numchars=32) &lt;br /&gt;
  /// Returns the SQL text to be used to compare one TEXT (clob) column.&lt;br /&gt;
  /// with one VARCHAR column.&lt;br /&gt;
o $DB-&amp;gt;sql_order_by_text($fieldname, $numchars=32)&lt;br /&gt;
  /// Returns the SQL text to be used to order by one TEXT (clob) column.&lt;br /&gt;
 &lt;br /&gt;
o $DB-&amp;gt;sql_concat()&lt;br /&gt;
  /// Returns the proper SQL to do CONCAT between the elements passed.&lt;br /&gt;
o $DB-&amp;gt;sql_concat_join($separator=&amp;quot;&#039; &#039;&amp;quot;, $elements=array())&lt;br /&gt;
  /// Returns the proper SQL to do CONCAT between the elements passed using one separator.&lt;br /&gt;
o $DB-&amp;gt;sql_fullname($first=&#039;firstname&#039;, $last=&#039;lastname&#039;)&lt;br /&gt;
  /// Returns the proper SQL to concatenate $firstname and $lastname.&lt;br /&gt;
 &lt;br /&gt;
o $DB-&amp;gt;sql_isempty($tablename, $fieldname, $nullablefield, $textfield)&lt;br /&gt;
  /// Returns the proper SQL to know if one field is empty.&lt;br /&gt;
o $DB-&amp;gt;sql_isnotempty($tablename, $fieldname, $nullablefield, $textfield)&lt;br /&gt;
  /// Returns the proper SQL to know if one field is not empty.&lt;br /&gt;
&lt;br /&gt;
o $DB-&amp;gt;get_in_or_equal($items, $type=SQL_PARAMS_QM, $prefix=&#039;param&#039;, $equal=true, $onemptyitems=false)&lt;br /&gt;
  /// Constructs &#039;IN()&#039; or &#039;=&#039; sql fragment&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Debug fuctions===&lt;br /&gt;
&lt;br /&gt;
If you execute&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$DB-&amp;gt;set_debug(true)&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
then $DB will outout the SQL of every query executed, along with timing information. This can be useful when debugging your code. Obviously, all such calls should be removed before code is submitted for integration.&lt;br /&gt;
&lt;br /&gt;
==Special cases==&lt;br /&gt;
&lt;br /&gt;
===get_course===&lt;br /&gt;
&lt;br /&gt;
From Moodle 2.5.1 onwards, you should use the get_course function instead of using get_record(&#039;course&#039;, ...) if you want to get a course record based on its ID, especially if there is a significant possibility that the course being retrieved is either the current course for the page, or the site course. Those two course records have probably already been loaded, and using this function will save a database query. &lt;br /&gt;
&lt;br /&gt;
As another advantage, the code is shorter and easier to read.&lt;br /&gt;
&lt;br /&gt;
Replace:&lt;br /&gt;
&lt;br /&gt;
    $course = $DB-&amp;gt;get_record(&#039;course&#039;, array(&#039;id&#039; =&amp;gt; $courseid), &#039;*&#039;, MUST_EXIST);&lt;br /&gt;
&lt;br /&gt;
With:&lt;br /&gt;
 &lt;br /&gt;
    $course = get_course($courseid);&lt;br /&gt;
&lt;br /&gt;
===get_courses===&lt;br /&gt;
&lt;br /&gt;
If you want to get all the current courses in your Moodle, use get_courses() without parameter:&lt;br /&gt;
&lt;br /&gt;
    $courses = get_courses();&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==See also==&lt;br /&gt;
&lt;br /&gt;
* [[SQL coding style]]&lt;br /&gt;
* [[Core APIs]]&lt;br /&gt;
* [[DML exceptions|DML exceptions]]: New DML code is throwing exceptions instead of returning false if anything goes wrong&lt;br /&gt;
* [[DML drivers|DML drivers]]: Database drivers for new DML layer&lt;br /&gt;
* [[DML functions - pre 2.0|DML functions - pre 2.0]]: &#039;&#039;&#039;(deprecated!)&#039;&#039;&#039; For information valid before Moodle 2.0.&lt;br /&gt;
* [[DDL functions|DDL functions]]: Where all the functions used to handle DB objects ([[wikipedia:Data_Definition_Language|DDL]]) are defined.&lt;br /&gt;
* [[DB layer 2.0 examples|DB layer 2.0 examples]]: To see some code examples using various DML functions.&lt;br /&gt;
* [[DB layer 2.0 migration docs|DB layer 2.0 migration docs]]: Information about how to modify your code to work with the new Moodle 2.0 DB layer.&lt;br /&gt;
* [[DTL functions|DTL functions]]: Exporting, importing and moving of data stored in SQL databases&lt;br /&gt;
&lt;br /&gt;
[[Category:DB]]&lt;br /&gt;
[[Category:XMLDB]]&lt;br /&gt;
[[Category:API]]&lt;/div&gt;</summary>
		<author><name>Mohessaid</name></author>
	</entry>
	<entry>
		<id>https://docs.moodle.org/dev/index.php?title=Blocks_Advanced&amp;diff=53794</id>
		<title>Blocks Advanced</title>
		<link rel="alternate" type="text/html" href="https://docs.moodle.org/dev/index.php?title=Blocks_Advanced&amp;diff=53794"/>
		<updated>2018-03-12T15:06:23Z</updated>

		<summary type="html">&lt;p&gt;Mohessaid: Typo error&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Moodle 2.0}}&lt;br /&gt;
=Introduction=&lt;br /&gt;
This is a continuation of the [[Blocks| simpleHTML block example]].&lt;br /&gt;
&lt;br /&gt;
=Adding forms=&lt;br /&gt;
The next thing that we want to do is add a form to create a simpleHTML page.&lt;br /&gt;
&lt;br /&gt;
We are going to create two pages - view.php and simplehtml_form.php &lt;br /&gt;
All of our logic will be contained in view.php and simplehtml_form.php will just display the form elements.&lt;br /&gt;
&lt;br /&gt;
Create a new file in the blocks/simplehtml directory called simplehtml_form.php. Add the following code:&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
require_once(&amp;quot;{$CFG-&amp;gt;libdir}/formslib.php&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
class simplehtml_form extends moodleform {&lt;br /&gt;
    &lt;br /&gt;
    function definition() {&lt;br /&gt;
        &lt;br /&gt;
        $mform =&amp;amp; $this-&amp;gt;_form;&lt;br /&gt;
        $mform-&amp;gt;addElement(&#039;header&#039;,&#039;displayinfo&#039;, get_string(&#039;textfields&#039;, &#039;block_simplehtml&#039;));&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
Now let&#039;s create view.php.&lt;br /&gt;
&lt;br /&gt;
Create a new file in the blocks/simplehtml directory called view.php. In this file add the following code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
&lt;br /&gt;
require_once(&#039;../../config.php&#039;);&lt;br /&gt;
require_once(&#039;simplehtml_form.php&#039;);&lt;br /&gt;
&lt;br /&gt;
global $DB;&lt;br /&gt;
&lt;br /&gt;
// Check for all required variables.&lt;br /&gt;
$courseid = required_param(&#039;courseid&#039;, PARAM_INT);&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
if (!$course = $DB-&amp;gt;get_record(&#039;course&#039;, array(&#039;id&#039; =&amp;gt; $courseid))) {&lt;br /&gt;
    print_error(&#039;invalidcourse&#039;, &#039;block_simplehtml&#039;, $courseid);&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
require_login($course);&lt;br /&gt;
&lt;br /&gt;
$simplehtml = new simplehtml_form();&lt;br /&gt;
&lt;br /&gt;
$simplehtml-&amp;gt;display();&lt;br /&gt;
?&amp;gt;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
Next we will add a link from our block to this page so that we can see what we have created.&lt;br /&gt;
&lt;br /&gt;
In the get_content() method of our block_simplehtml class replace&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$this-&amp;gt;content-&amp;gt;footer = &#039;Footer here...&#039;;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
with&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
global $COURSE;&lt;br /&gt;
&lt;br /&gt;
// The other code.&lt;br /&gt;
&lt;br /&gt;
$url = new moodle_url(&#039;/blocks/simplehtml/view.php&#039;, array(&#039;blockid&#039; =&amp;gt; $this-&amp;gt;instance-&amp;gt;id, &#039;courseid&#039; =&amp;gt; $COURSE-&amp;gt;id));&lt;br /&gt;
$this-&amp;gt;content-&amp;gt;footer = html_writer::link($url, get_string(&#039;addpage&#039;, &#039;block_simplehtml&#039;));&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Add a Header==&lt;br /&gt;
If you visit the page now you will see a very basic non-themed form without any of the necessary navigational structure. Note that this happens because the form processing page, in this case view.php, is being accessed directly via the URL and not by being included in another page. This means that the necessary infrastructure must be added directly to the script. Add this by using the print_header function, but a few pieces of data are needed to build appropriate navigation. Make the following adjustments to view.php:&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In the global declaration:&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
global $DB, $OUTPUT, $PAGE;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
After require_login($course);&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$PAGE-&amp;gt;set_url(&#039;/blocks/simplehtml/view.php&#039;, array(&#039;id&#039; =&amp;gt; $courseid));&lt;br /&gt;
$PAGE-&amp;gt;set_pagelayout(&#039;standard&#039;);&lt;br /&gt;
$PAGE-&amp;gt;set_heading(get_string(&#039;edithtml&#039;, &#039;block_simplehtml&#039;));&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
One last lot of code to add. The following lines should be added after $simplehtml = new simplehtml_form();&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
echo $OUTPUT-&amp;gt;header();&lt;br /&gt;
$simplehtml-&amp;gt;display();&lt;br /&gt;
echo $OUTPUT-&amp;gt;footer();&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Navigation breadcrumbs===&lt;br /&gt;
To really make this look like it&#039;s a part of moodle we will add the navigation breadcrumbs to the header of our page.&lt;br /&gt;
&lt;br /&gt;
In view.php, add the following after $courseid = required_param(&#039;courseid&#039;, PARAM_INT);&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$blockid = required_param(&#039;blockid&#039;, PARAM_INT);&lt;br /&gt;
&lt;br /&gt;
// Next look for optional variables.&lt;br /&gt;
$id = optional_param(&#039;id&#039;, 0, PARAM_INT);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
Then add the following after the header code&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$settingsnode = $PAGE-&amp;gt;settingsnav-&amp;gt;add(get_string(&#039;simplehtmlsettings&#039;, &#039;block_simplehtml&#039;));&lt;br /&gt;
$editurl = new moodle_url(&#039;/blocks/simplehtml/view.php&#039;, array(&#039;id&#039; =&amp;gt; $id, &#039;courseid&#039; =&amp;gt; $courseid, &#039;blockid&#039; =&amp;gt; $blockid));&lt;br /&gt;
$editnode = $settingsnode-&amp;gt;add(get_string(&#039;editpage&#039;, &#039;block_simplehtml&#039;), $editurl);&lt;br /&gt;
$editnode-&amp;gt;make_active();&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
Don&#039;t forget to include definitions for the new strings that you are creating, into block_simplehtml.php&lt;br /&gt;
&lt;br /&gt;
==Form State Control==&lt;br /&gt;
Now to add some basic form state control: The first step is to setup the appropriate actions based on the form state, accounting for three scenarios:&lt;br /&gt;
&lt;br /&gt;
#user has cancelled&lt;br /&gt;
#form submitted and passes validation protocol. Process form data accordingly.&lt;br /&gt;
#form either doesn&#039;t pass validation protocol or it is being displayed for the first time&lt;br /&gt;
&lt;br /&gt;
To implement these three scenarios adjust the code a bit. The existing form display and header code will be used as the first time display code, and an if statement added after instantiating the simplehtml_form object will handle the logic behind the application flow:&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
if($simplehtml-&amp;gt;is_cancelled()) {&lt;br /&gt;
    // Cancelled forms redirect to the course main page.&lt;br /&gt;
    $courseurl = new moodle_url(&#039;/course/view.php&#039;, array(&#039;id&#039; =&amp;gt; $id));&lt;br /&gt;
    redirect($courseurl);&lt;br /&gt;
} else if ($simplehtml-&amp;gt;get_data()) {&lt;br /&gt;
    // We need to add code to appropriately act on and store the submitted data&lt;br /&gt;
    // but for now we will just redirect back to the course main page.&lt;br /&gt;
    $courseurl = new moodle_url(&#039;/course/view.php&#039;, array(&#039;id&#039; =&amp;gt; $courseid));&lt;br /&gt;
    redirect($courseurl);&lt;br /&gt;
} else {&lt;br /&gt;
    // form didn&#039;t validate or this is the first display&lt;br /&gt;
    $site = get_site();&lt;br /&gt;
    echo $OUTPUT-&amp;gt;header();&lt;br /&gt;
    $simplehtml-&amp;gt;display();&lt;br /&gt;
    echo $OUTPUT-&amp;gt;footer();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
Notice that the existing header and form display code have been moved into the third branch of the conditional. Also, there isn&#039;t any code to handle form processing. That code will be added shortly.&lt;br /&gt;
&lt;br /&gt;
==Final Steps==&lt;br /&gt;
Reviewing the progress so far:&lt;br /&gt;
&lt;br /&gt;
#simplehtml_form.php is created which defines the class used later to display our form.&lt;br /&gt;
#view.php is created which:&lt;br /&gt;
#*loads base moodle API and any necessary third party modules or non-base API files.&lt;br /&gt;
#*loads the necessary course object and globals.&lt;br /&gt;
#*performs necessary access control.&lt;br /&gt;
#*loads our form and branches execution appropriately based on our form state.&lt;br /&gt;
&lt;br /&gt;
So the form class is defined and the form is displayed in a separate file. Adding elements to the form and finishing the processing of our form will wrap it up!&lt;br /&gt;
===Add Form Elements===&lt;br /&gt;
Currently there are no form elements which can submit data. Editing the form class definition in simplehtml_form.php will change that by adding a wide set of form elements to the form for demonstrative purposes only. This will give an example of how to add and process various form elements.&lt;br /&gt;
&lt;br /&gt;
To add the link title text field and the displaytext HTML area to the form, paste the following text in the function definition of the simplehtml_form.php file: &lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
        &lt;br /&gt;
// add page title element.&lt;br /&gt;
$mform-&amp;gt;addElement(&#039;text&#039;, &#039;pagetitle&#039;, get_string(&#039;pagetitle&#039;, &#039;block_simplehtml&#039;));&lt;br /&gt;
$mform-&amp;gt;setType(&#039;pagetitle&#039;, PARAM_RAW);&lt;br /&gt;
$mform-&amp;gt;addRule(&#039;pagetitle&#039;, null, &#039;required&#039;, null, &#039;client&#039;);&lt;br /&gt;
        &lt;br /&gt;
// add display text field&lt;br /&gt;
$mform-&amp;gt;addElement(&#039;htmleditor&#039;, &#039;displaytext&#039;, get_string(&#039;displayedhtml&#039;, &#039;block_simplehtml&#039;));&lt;br /&gt;
$mform-&amp;gt;setType(&#039;displaytext&#039;, PARAM_RAW);&lt;br /&gt;
$mform-&amp;gt;addRule(&#039;displaytext&#039;, null, &#039;required&#039;, null, &#039;client&#039;);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
For full details on addElement() review the moodle documentation on addElement. Also review addRule() in moodle&#039;s documentation and the PEAR web site. PEAR is an included form processing library that moodle uses for form processing.&lt;br /&gt;
&lt;br /&gt;
Now add additional form elements to simplehtml_form.php: &lt;br /&gt;
====File Upload====&lt;br /&gt;
Add the file field to the form after the existing elements: &lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
// add filename selection.&lt;br /&gt;
$mform-&amp;gt;addElement(&#039;filepicker&#039;, &#039;filename&#039;, get_string(&#039;file&#039;), null, array(&#039;accepted_types&#039; =&amp;gt; &#039;*&#039;));&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
This field allows the user to choose a file in the course file directory. Notice that the name of the element in the form is the same name as the field in the database. This will make it easy to insert and update the database records later.&lt;br /&gt;
&lt;br /&gt;
====Fieldset Header====&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
// add picture fields grouping&lt;br /&gt;
$mform-&amp;gt;addElement(&#039;header&#039;, &#039;picfield&#039;, get_string(&#039;picturefields&#039;, &#039;block_simplehtml&#039;), null, false);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
====Yes/No Select====&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
// add display picture yes / no option&lt;br /&gt;
$mform-&amp;gt;addElement(&#039;selectyesno&#039;, &#039;displaypicture&#039;, get_string(&#039;displaypicture&#039;, &#039;block_simplehtml&#039;));&lt;br /&gt;
$mform-&amp;gt;setDefault(&#039;displaypicture&#039;, 1);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
====Radio Select====&lt;br /&gt;
To control the available options, create a function that will return the list of available options as an array keyed by an integer. This is preferred for several reasons:&lt;br /&gt;
&lt;br /&gt;
*It keeps the database free from enum field types by providing data key by integers. This is database engine independent.&lt;br /&gt;
*It makes it easy to add additional options at a later date by changing our function&lt;br /&gt;
*It avoids the use of global variables.&lt;br /&gt;
&lt;br /&gt;
Create a file lib.php and place the following code into it which will define the image options via radio select.&lt;br /&gt;
&amp;lt;code php&amp;gt; &lt;br /&gt;
function block_simplehtml_images() {&lt;br /&gt;
    return array(html_writer::tag(&#039;img&#039;, &#039;&#039;, array(&#039;alt&#039; =&amp;gt; get_string(&#039;red&#039;, &#039;block_simplehtml&#039;), &#039;src&#039; =&amp;gt; &amp;quot;pix/picture0.gif&amp;quot;)),&lt;br /&gt;
                html_writer::tag(&#039;img&#039;, &#039;&#039;, array(&#039;alt&#039; =&amp;gt; get_string(&#039;blue&#039;, &#039;block_simplehtml&#039;), &#039;src&#039; =&amp;gt; &amp;quot;pix/picture1.gif&amp;quot;)),&lt;br /&gt;
                html_writer::tag(&#039;img&#039;, &#039;&#039;, array(&#039;alt&#039; =&amp;gt; get_string(&#039;green&#039;, &#039;block_simplehtml&#039;), &#039;src&#039; =&amp;gt; &amp;quot;pix/picture2.gif&amp;quot;)));&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
Now include the above file in any files that need to use the function, for now this is just simplehtml_form.php. Add the following after require_once(&amp;quot;$CFG-&amp;gt;libdir/formslib.php&amp;quot;); in simplehtml_form.php &lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
require_once($CFG-&amp;gt;dirroot.&#039;/blocks/simplehtml/lib.php&#039;);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
You now need to add some pictures to the pix directory. In this example I have three gif images each a different colour, but you could use any image (small is better). Create a directory called pix in your simplehtml block directory. Now add the radio select to the form definition (simplethml_form.php)&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
// add image selector radio buttons&lt;br /&gt;
$images = block_simplehtml_images();&lt;br /&gt;
$radioarray = array();&lt;br /&gt;
for ($i = 0; $i &amp;lt; count($images); $i++) {&lt;br /&gt;
    $radioarray[] =&amp;amp; $mform-&amp;gt;createElement(&#039;radio&#039;, &#039;picture&#039;, &#039;&#039;, $images[$i], $i);&lt;br /&gt;
}&lt;br /&gt;
$mform-&amp;gt;addGroup($radioarray, &#039;radioar&#039;, get_string(&#039;pictureselect&#039;, &#039;block_simplehtml&#039;), array(&#039; &#039;), FALSE);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
A group is also added to capture multiple form elements on one line. Another approach would be to just display each radio element on its own line. &lt;br /&gt;
====Alt Text Input====&lt;br /&gt;
Finally, to wrap-up the image display selection, allow the user to choose the alternate text that will be displayed with the selected image. &lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
// add description field&lt;br /&gt;
$attributes = array(&#039;size&#039; =&amp;gt; &#039;50&#039;, &#039;maxlength&#039; =&amp;gt; &#039;100&#039;);&lt;br /&gt;
$mform-&amp;gt;addElement(&#039;text&#039;, &#039;description&#039;, get_string(&#039;picturedesc&#039;, &#039;block_simplehtml&#039;), $attributes);&lt;br /&gt;
$mform-&amp;gt;setType(&#039;description&#039;, PARAM_TEXT);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
Note that there is an attributes variable added to the text field to limit its size and length.&lt;br /&gt;
&lt;br /&gt;
====Date Time Selector====&lt;br /&gt;
The setAdvanced() function adds advanced options to a form. To use this function pass in the name of the form element, group of elements, or header. The &amp;quot;Advanced Options&amp;quot; button appears in the upper right corner of the fieldset. In this example, there is a single element, but later you&#039;ll see an element within a header. Learn more about setAdvanced. The&amp;quot;Show/Hide Advanced&amp;quot; button won&#039;t be displayed until adding action buttons to the form during the next step of this tutorial.&lt;br /&gt;
&lt;br /&gt;
Now add the date field as an optional element:&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
 // add optional grouping&lt;br /&gt;
$mform-&amp;gt;addElement(&#039;header&#039;, &#039;optional&#039;, get_string(&#039;optional&#039;, &#039;form&#039;), null, false);&lt;br /&gt;
&amp;lt;/code&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
 // add date_time selector in optional area&lt;br /&gt;
$mform-&amp;gt;addElement(&#039;date_time_selector&#039;, &#039;displaydate&#039;, get_string(&#039;displaydate&#039;, &#039;block_simplehtml&#039;), array(&#039;optional&#039; =&amp;gt; true));&lt;br /&gt;
$mform-&amp;gt;setAdvanced(&#039;optional&#039;);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
The above code adds a form header and sets it to hide the date/time selector within the optional (advanced) form controls.&lt;br /&gt;
&lt;br /&gt;
===Add State Variables and Finalize the Form===&lt;br /&gt;
====Adding Form Buttons====&lt;br /&gt;
Most moodle forms have a basic set of buttons. &amp;quot;Submit&amp;quot; and &amp;quot;Cancel&amp;quot; are added by calling the moodleform member function add_action_buttons(). Add the following at the end of simplehtml_form.php&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$this-&amp;gt;add_action_buttons();&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
Notice when calling add_action_buttons(), $this is used rather than $mform because add_action_buttons() is defined in the base class moodleform and would be outside scope for $mform. &lt;br /&gt;
====Add State Variables====&lt;br /&gt;
Sometimes forms need to keep track of additional data that is not intended to be visible to users. These fields should be placed in hidden elements. For this form blockid and the courseid are needed. Before the call to add_action_buttons() add: &lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
// hidden elements&lt;br /&gt;
$mform-&amp;gt;addElement(&#039;hidden&#039;, &#039;blockid&#039;);&lt;br /&gt;
$mform-&amp;gt;addElement(&#039;hidden&#039;, &#039;courseid&#039;);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
These elements will need to be populated by displaying code because these will be passed in via the URL initially. after $simplehtml = new simplehtml_form(); in view.php add:&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$toform[&#039;blockid&#039;] = $blockid;&lt;br /&gt;
$toform[&#039;courseid&#039;] = $courseid;&lt;br /&gt;
$simplehtml-&amp;gt;set_data($toform);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
===Process Form Data===&lt;br /&gt;
After creating the form, appropriate code must be added to process the submitted form data. Accomplish this by adding code to view.php. Typically when processing form data it is helpful to remove some of the final processing steps so that your script essentially terminates execution and does not redirect you to the course page or wherever makes sense. This is tremendously helpful while debugging. The processing code will be added to this block of code in view.php :&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
} else if ($fromform = $simplehtml-&amp;gt;get_data()) {&lt;br /&gt;
    // We need to add code to appropriately act on and store the submitted data&lt;br /&gt;
    // but for now we will just redirect back to the course main page.&lt;br /&gt;
    $courseurl = new moodle_url(&#039;/course/view.php&#039;, array(&#039;id&#039; =&amp;gt; $courseid));&lt;br /&gt;
    redirect($courseurl);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
Notice that the else if statement has been modified to create the variable $fromform.&lt;br /&gt;
&lt;br /&gt;
For now comment out the redirect and add the following above it.&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
print_object($fromform);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
print_object() is a useful moodle function which prints out data from mixed data types showing the keys and data for arrays and objects. Now visit the &amp;quot;Add Page&amp;quot; link for the block and submit some form data. You should see something similar to: &lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
stdClass Object&lt;br /&gt;
(&lt;br /&gt;
    [pagetitle] =&amp;gt; fish&lt;br /&gt;
    [displaytext] =&amp;gt; &amp;lt;p&amp;gt;fish&amp;lt;/p&amp;gt;&lt;br /&gt;
    [filename] =&amp;gt; 687195712&lt;br /&gt;
    [displaypicture] =&amp;gt; 1&lt;br /&gt;
    [picture] =&amp;gt; 1&lt;br /&gt;
    [description] =&amp;gt; ocean blue&lt;br /&gt;
    [displaydate] =&amp;gt; 1333609200&lt;br /&gt;
    [mform_showadvanced_last] =&amp;gt; 1&lt;br /&gt;
    [blockid] =&amp;gt; 114&lt;br /&gt;
    [courseid] =&amp;gt; 1&lt;br /&gt;
    [submitbutton] =&amp;gt; Save changes&lt;br /&gt;
)&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
The values in brackets are the keys and the portion after =&amp;gt; is the data for that particular key. Since the form submission is verified as working as expected, save the submitted form data. The most direct way to save is with a call to insert_record(). This function takes the name of the table, &#039;block_simplehtml&#039; in our case, and the object to be inserted. The object must have keys that map one-to-one with table column names. Choosing form element names that map directly to the database columns saves a bit of code. Save the submitted form data with the following code pasted above the commented out redirect: &lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
// We need to add code to appropriately act on and store the submitted data&lt;br /&gt;
if (!$DB-&amp;gt;insert_record(&#039;block_simplehtml&#039;, $fromform)) {&lt;br /&gt;
    print_error(&#039;inserterror&#039;, &#039;block_simplehtml&#039;);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
This code checks to see if we are updating or inserting into the database. We have not created the database yet, so this code won&#039;t work. Continue on to the next section and create the database before testing this code.&lt;br /&gt;
&lt;br /&gt;
=Creating a Database=&lt;br /&gt;
&lt;br /&gt;
We will be using the XMLDB Editor to design and create the database table that will hold the data from the form that we have just created. We have eight pieces of information to store from the simplehtml form.&lt;br /&gt;
First create a folder named &#039;&#039;&#039;db&#039;&#039;&#039; under you main block directory. Next login to Moodle and navigate to the XMLDB editor, located in the &#039;Site administration-&amp;gt;Development-&amp;gt;XMLDB editor&#039;. The XMLDB editor is a graphical interface to help generate the xml files that Moodle uses to create and maintain database tables. When you get to the XMLDB editor you will see all the blocks, modules and other areas that have db directories. Those that show a link already have tables defined that can be loaded and modified. Find the &#039;&#039;&#039;blocks/simplehtml/db&#039;&#039;&#039; and click on Create. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The db directory has an install.xml file with some basic information about your block and one table called simplehtml. In Moodle you will now see the block/simplehtml/db highlighted in green and the Load and Delete commands will be linked. Click on Load. Now you will see the Edit and Unload text linked. Click on Edit.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The simplehtml table must be modified to include the information entered from the form: click on the Edit link next to the simplehtml table to display the definition that is created by default for the table. Id field will be there and a primary key that links to the id field. Rename the table to block_simplehtml (if necessary). Alter the comments for this table here as well. Any changes to the comments field requires a click on the Change button for the changes to be recorded.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now add the following fields:&lt;br /&gt;
&lt;br /&gt;
#blockid&lt;br /&gt;
#pagetitle&lt;br /&gt;
#displaytext&lt;br /&gt;
#format&lt;br /&gt;
#filename&lt;br /&gt;
#picture&lt;br /&gt;
#description&lt;br /&gt;
#displaypicture&lt;br /&gt;
#displaydate&lt;br /&gt;
&lt;br /&gt;
==blockid==&lt;br /&gt;
The blockid is a foreign key that references the block table. This will be used to join our data rows to the block table. The block table houses generic block information for installed block instances. To add the blockid field:&lt;br /&gt;
#Click the &amp;quot;New Field&amp;quot; link&lt;br /&gt;
#Change the Name to blockid&lt;br /&gt;
#Enter a Comment about the field&lt;br /&gt;
#Set the Type to int&lt;br /&gt;
#Enter a Length of 10&lt;br /&gt;
#Set Not Null to not null&lt;br /&gt;
#Set Sequence to No&lt;br /&gt;
#Enter 0 for the Default&lt;br /&gt;
#Click the Change button.&lt;br /&gt;
&lt;br /&gt;
==pagetitle==&lt;br /&gt;
The pagetitle is simply text that will be used for links to this simplehtml page. &#039;&#039;&#039;Using default Moodle Themes, Moodle blocks cannot handle more than 25 characters without wrapping&#039;&#039;&#039;. To add the pagetitle field:&lt;br /&gt;
&lt;br /&gt;
#Click the &amp;quot;New Field&amp;quot; link&lt;br /&gt;
#Change the Name to pagetitle&lt;br /&gt;
#Enter a Comment about the field&lt;br /&gt;
#Set the Type to char&lt;br /&gt;
#Enter a Length of 25&lt;br /&gt;
#Set Not Null to not null&lt;br /&gt;
#Click the Change button.&lt;br /&gt;
&lt;br /&gt;
==display text==&lt;br /&gt;
The displaytext field will be displayed as text on the simplehtml page, potentially as HTML. To add the dispaytext field:&lt;br /&gt;
&lt;br /&gt;
#Click the &amp;quot;New Field&amp;quot; link&lt;br /&gt;
#Change the Name to displaytext&lt;br /&gt;
#Enter a Comment about the field&lt;br /&gt;
#Set the Type to text&lt;br /&gt;
#Set Not Null to not null&lt;br /&gt;
#Click the Change button.&lt;br /&gt;
&lt;br /&gt;
==format==&lt;br /&gt;
The format field will contain the integer value that represents the format the text was entered in. To add the format field:&lt;br /&gt;
&lt;br /&gt;
#Click the &amp;quot;New Field&amp;quot; link&lt;br /&gt;
#Change the Name to format&lt;br /&gt;
#Enter a Comment about the field&lt;br /&gt;
#Set the Type to int&lt;br /&gt;
#Enter a Length of 3&lt;br /&gt;
#Set Not Null to not null&lt;br /&gt;
#Set Sequence to No&lt;br /&gt;
#Enter 0 for the Default&lt;br /&gt;
#Click the Change button.&lt;br /&gt;
&lt;br /&gt;
==filename==&lt;br /&gt;
The filename field stores the name of a file the instructor posts on the simplehtml page, which students can then download or view. To add the filename field:&lt;br /&gt;
&lt;br /&gt;
#Click the &amp;quot;New Field&amp;quot; link&lt;br /&gt;
#Change the Name to filename&lt;br /&gt;
#Enter a Comment about the field&lt;br /&gt;
#Set the Type to char&lt;br /&gt;
#Enter a Length of 255&lt;br /&gt;
#Set Not Null to not null&lt;br /&gt;
#Click the Change button.&lt;br /&gt;
&lt;br /&gt;
==picture==&lt;br /&gt;
The URL for the user&#039;s chosen picture is in a predefined static variable that associates a number to a picture. This will allow the addition of more pictures later if necessary, or for changing the current pictures&#039; URLs without updating the database. Because only the number is stored the database field should be created as an int rather than a char. To add the picture field:&lt;br /&gt;
&lt;br /&gt;
#Click the &amp;quot;New Field&amp;quot; link&lt;br /&gt;
#Change the Name to picture&lt;br /&gt;
#Enter a Comment about the field&lt;br /&gt;
#Set the Type to int&lt;br /&gt;
#Enter a Length of 2&lt;br /&gt;
#Set Not Null to not null&lt;br /&gt;
#Set Sequence to No&lt;br /&gt;
#Enter 0 for the Default&lt;br /&gt;
#Click the Change button.&lt;br /&gt;
&lt;br /&gt;
==description==&lt;br /&gt;
Add the description field that will be displayed on the page. To add the description field:&lt;br /&gt;
&lt;br /&gt;
#Click the &amp;quot;New Field&amp;quot; link&lt;br /&gt;
#Change the Name to description&lt;br /&gt;
#Enter a Comment about the field&lt;br /&gt;
#Set the Type to text&lt;br /&gt;
#Set Not Null to not null&lt;br /&gt;
#Click the Change button.&lt;br /&gt;
&lt;br /&gt;
==displaypicture==&lt;br /&gt;
The displaypicture field will be the &amp;quot;yes&amp;quot; or &amp;quot;no&amp;quot; question on the form. This is best represented as an &#039;int&#039;. To add the displaypicture field:&lt;br /&gt;
&lt;br /&gt;
#Click the &amp;quot;New Field&amp;quot; link&lt;br /&gt;
#Change the Name to displaypicture&lt;br /&gt;
#Enter a Comment about the field&lt;br /&gt;
#Set the Type to int&lt;br /&gt;
#Enter a Length of 1&lt;br /&gt;
#Set Not Null to not null&lt;br /&gt;
#Set Sequence to No&lt;br /&gt;
#Enter 0 for the Default&lt;br /&gt;
#Click the Change button.&lt;br /&gt;
&lt;br /&gt;
==displaydate==&lt;br /&gt;
The final field to add to the table is the displaydate. It is a UNIX timestamp which is an integer value. To add the displaydate field:&lt;br /&gt;
&lt;br /&gt;
#Click the &amp;quot;New Field&amp;quot; link&lt;br /&gt;
#Change the Name to displaydate&lt;br /&gt;
#Enter a Comment about the field&lt;br /&gt;
#Set the Type to int&lt;br /&gt;
#Enter a Length of 10&lt;br /&gt;
#Set Not Null to not null&lt;br /&gt;
#Set Sequence to No&lt;br /&gt;
#Enter 0 for the Default&lt;br /&gt;
#Click the Change button.&lt;br /&gt;
&lt;br /&gt;
Now that the fields have been added to the table the install.xml needs to be saved. Click the &amp;quot;Back&amp;quot; link and the &amp;quot;Back to Main&amp;quot;. Once on the main page click the &amp;quot;Save&amp;quot; link to save the changes to the install.xml. Remember update code wasn&#039;t added to install the database table after the block has already been installed. When developing within a localized environment load the database by uninstalling the module and then reinstalling it. In normal circumstances where the block or module has been in production use you would need to do this with proper update code. &lt;br /&gt;
Now you should be able to test your code. You can view the data was stored in the proper table by viewing the table block_simplehtml via phpadmin.&lt;br /&gt;
&lt;br /&gt;
=Refining the User Interface=&lt;br /&gt;
After successfully submitting data to the database via the form it is now time to begin displaying that data so that users can interact with the data and view what has been submitted. Both steps will be contained within simplehtml/block_simplehtml.php. &lt;br /&gt;
&lt;br /&gt;
==Add Links to Each Page of the Block==&lt;br /&gt;
To retrieve the relevant rows we will call $DB-&amp;gt;get_records(), which accepts two parameters::&lt;br /&gt;
#The table name&lt;br /&gt;
#An array with the name of the column or field to be queried and the value of the queried field we want to match.&lt;br /&gt;
&lt;br /&gt;
Add the following code:&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
global $COURSE, $DB; //$COURSE should already be present&lt;br /&gt;
&lt;br /&gt;
...&lt;br /&gt;
&lt;br /&gt;
if (!empty($this-&amp;gt;config-&amp;gt;text)) {&lt;br /&gt;
    $this-&amp;gt;content-&amp;gt;text = $this-&amp;gt;config-&amp;gt;text;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
// This is the new code.&lt;br /&gt;
if ($simplehtmlpages = $DB-&amp;gt;get_records(&#039;block_simplehtml&#039;, array(&#039;blockid&#039; =&amp;gt; $this-&amp;gt;instance-&amp;gt;id))) {&lt;br /&gt;
    $this-&amp;gt;content-&amp;gt;text .= html_writer::start_tag(&#039;ul&#039;);&lt;br /&gt;
    foreach ($simplehtmlpages as $simplehtmlpage) {&lt;br /&gt;
        $pageurl = new moodle_url(&#039;/blocks/simplehtml/view.php&#039;, array(&#039;blockid&#039; =&amp;gt; $this-&amp;gt;instance-&amp;gt;id, &#039;courseid&#039; =&amp;gt; $COURSE-&amp;gt;id, &#039;id&#039; =&amp;gt; $simplehtmlpage-&amp;gt;id, &#039;viewpage&#039; =&amp;gt; &#039;1&#039;));&lt;br /&gt;
        $this-&amp;gt;content-&amp;gt;text .= html_writer::start_tag(&#039;li&#039;);&lt;br /&gt;
        $this-&amp;gt;content-&amp;gt;text .= html_writer::link($pageurl, $simplehtmlpage-&amp;gt;pagetitle);&lt;br /&gt;
        $this-&amp;gt;content-&amp;gt;text .= html_writer::end_tag(&#039;li&#039;);&lt;br /&gt;
    }&lt;br /&gt;
    $this-&amp;gt;content-&amp;gt;text .= html_writer::end_tag(&#039;ul&#039;);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It is important to remember that the property $this-&amp;gt;content-&amp;gt;text is ignored by list blocks. Therefore, for this example ensure that the block_simplehtml class extends block_base and not block_list.&lt;br /&gt;
&lt;br /&gt;
==Refactor Display Method==&lt;br /&gt;
To avoid any code duplication and make it easy to reuse this functionality create a function in &#039;&#039;&#039;lib.php&#039;&#039;&#039; to handle the page display. A preloaded simplehtml page is passed in as a single parameter, and an optional parameter will control whether the data is returned or directly printed out. Most Moodle functions that print information can be passed a true value as the last parameter. This is the function&#039;s return value, which tells the function to return the HTML and not print or echo it to the user. For development, set the return value to false so that the data is printed out.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
function block_simplehtml_print_page($simplehtml, $return = false) {}&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
Now consider what the function needs to do in order to display all of the necessary information from our page.&lt;br /&gt;
&lt;br /&gt;
;Page Title:Print this out as a centered header for the HTML PAGE&lt;br /&gt;
&lt;br /&gt;
;Display Text:Print this out in whatever format the user specified, centered in a box on the page&lt;br /&gt;
&lt;br /&gt;
;Filename:Display a link to the file in the course file directory so the user has the option to download it. This will be centered in the same box as the display text.&lt;br /&gt;
&lt;br /&gt;
;Display Picture:Display the picture with the description on the right of the picture in a box if the user has chosen for the picture to display&lt;br /&gt;
&lt;br /&gt;
;Display date:Display the date under the page title in a smaller font&lt;br /&gt;
&lt;br /&gt;
===Add Page Title===&lt;br /&gt;
To display the page title use the $OUTPUT class. Add the following to block_simplehtml_print_page() in lib.php&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
global $OUTPUT, $COURSE;&lt;br /&gt;
$display = $OUTPUT-&amp;gt;heading($simplehtml-&amp;gt;pagetitle);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
After we have displayed the title, let&#039;s add a box to put around the rest of the elements that we will display.&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
 $display .= $OUTPUT-&amp;gt;box_start();&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
This is the opening tag for the box, we will have to enter similar code later, to encapsulate the elements.&lt;br /&gt;
===Display the Date===&lt;br /&gt;
The requirements for date display call for displaying the date in a smaller font under the page title. Moodle has a userdate() function that has several advantages over PHP&#039;s date() function. It displays the date in the user&#039;s preferred format and adjusts the date for any timezone difference.&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
if($simplehtml-&amp;gt;displaydate) {&lt;br /&gt;
    $display .= userdate($simplehtml-&amp;gt;displaydate);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
Notice that since the user had an option of choosing a date or not that you must check to ensure that it was set before trying to output it. Take a look at the displayed page: click on one of your page links from the block. There&#039;s no output. Add some additional code that handles the value of $return. Add the following at the end of the function definition: &lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
if($return) {&lt;br /&gt;
    return $display;&lt;br /&gt;
} else {&lt;br /&gt;
    echo $display;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
As mentioned earlier, the requirements for the date field were to be centered under the page title and smaller. This can be controlled with a stylesheet.&lt;br /&gt;
&lt;br /&gt;
First, put a div tag around the date, and give it a class to target with CSS later. Change the date output lines:&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$display .= html_writer::start_tag(&#039;div&#039;, array(&#039;class&#039; =&amp;gt; &#039;simplehtml displaydate&#039;));&lt;br /&gt;
$display .= userdate($simplehtml-&amp;gt;displaydate);&lt;br /&gt;
$display .= html_writer::end_tag(&#039;div&#039;);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
There are two options for adding the stylesheet:&lt;br /&gt;
&lt;br /&gt;
#Add the CSS to the theme&#039;s CSS files in the theme directory&lt;br /&gt;
#Create a styles.css file in the block and add the CSS there&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Choosing the second option, adding a styles.css file, allows more flexibility and avoids needing to create multiple entries if the site is using more than one theme. Create styles.css and add this CSS:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
.simplehtml .displaydate {&lt;br /&gt;
    font-size: .8em;&lt;br /&gt;
    text-align: center;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
===Display Text===&lt;br /&gt;
Now the display text needs to be added. &lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$display .= clean_text($simplehtml-&amp;gt;displaytext);&lt;br /&gt;
&lt;br /&gt;
//close the box&lt;br /&gt;
$display .= $OUTPUT-&amp;gt;box_end();&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Display the Picture===&lt;br /&gt;
To selectively display the picture with its description text located underneath it:&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
if ($simplehtml-&amp;gt;displaypicture) {&lt;br /&gt;
    $display .= $OUTPUT-&amp;gt;box_start();&lt;br /&gt;
    $images = block_simplehtml_images();&lt;br /&gt;
    $display .= $images[$simplehtml-&amp;gt;picture];&lt;br /&gt;
    $display .= html_writer::start_tag(&#039;p&#039;);&lt;br /&gt;
    $display .= clean_text($simplehtml-&amp;gt;description);&lt;br /&gt;
    $display .= html_writer::end_tag(&#039;p&#039;);&lt;br /&gt;
    $display .= $OUTPUT-&amp;gt;box_end();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
===Final Alterations===&lt;br /&gt;
To have this all come together and work we need to make a few alterations to view.php&lt;br /&gt;
First we will add another optional parameter:&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$id = optional_param(&#039;id&#039;, 0, PARAM_INT);&lt;br /&gt;
$viewpage = optional_param(&#039;viewpage&#039;, false, PARAM_BOOL);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
And then we check to see which page to display depending on which link was selected.&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
&lt;br /&gt;
...&lt;br /&gt;
&lt;br /&gt;
echo $OUTPUT-&amp;gt;header();&lt;br /&gt;
if ($viewpage) {&lt;br /&gt;
    $simplehtmlpage = $DB-&amp;gt;get_record(&#039;block_simplehtml&#039;, array(&#039;id&#039; =&amp;gt; $id));&lt;br /&gt;
    block_simplehtml_print_page($simplehtmlpage);&lt;br /&gt;
} else {&lt;br /&gt;
    $simplehtml-&amp;gt;display();&lt;br /&gt;
}&lt;br /&gt;
echo $OUTPUT-&amp;gt;footer();&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
Try the simpleHTML block out and view the different pages that you have created.&lt;br /&gt;
&lt;br /&gt;
=Add editing capability=&lt;br /&gt;
At the moment we have no way to edit the pages that we have created. Our block really does need a way to edit the existing data. The edit feature will use an image to link to the view.php instead of text. This image will only appear when the instructor turns editing on.&lt;br /&gt;
&lt;br /&gt;
Moodle stores pictures and icons in the pix directory under the base moodle directory. You can also use pictures that are custom to a theme. These are stored within the theme&#039;s pix directory. For this example, use the icons in the pix directory for moodle. The image should be encapsulated in an HTML link to simplehtml.php. The url should pass the block instance id, block id, and course id to simplehtml.php.&lt;br /&gt;
&lt;br /&gt;
Edit the &#039;&#039;&#039;block_simplehtml.php&#039;&#039;&#039; file as follows:&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
global $COURSE, $DB, $PAGE; //We are adding $PAGE here&lt;br /&gt;
&lt;br /&gt;
...&lt;br /&gt;
&lt;br /&gt;
// Check to see if we are in editing mode&lt;br /&gt;
$canmanage = $PAGE-&amp;gt;user_is_editing($this-&amp;gt;instance-&amp;gt;id);&lt;br /&gt;
&lt;br /&gt;
if ($simplehtmlpages = $DB-&amp;gt;get_records(&#039;block_simplehtml&#039;, array(&#039;blockid&#039; =&amp;gt; $this-&amp;gt;instance-&amp;gt;id))) {&lt;br /&gt;
    $this-&amp;gt;content-&amp;gt;text .= html_writer::start_tag(&#039;ul&#039;);&lt;br /&gt;
    foreach ($simplehtmlpages as $simplehtmlpage) {&lt;br /&gt;
        if ($canmanage) {&lt;br /&gt;
            $pageparam = array(&#039;blockid&#039; =&amp;gt; $this-&amp;gt;instance-&amp;gt;id, &lt;br /&gt;
                  &#039;courseid&#039; =&amp;gt; $COURSE-&amp;gt;id, &lt;br /&gt;
                  &#039;id&#039; =&amp;gt; $simplehtmlpage-&amp;gt;id);&lt;br /&gt;
            $editurl = new moodle_url(&#039;/blocks/simplehtml/view.php&#039;, $pageparam);&lt;br /&gt;
            $editpicurl = new moodle_url(&#039;/pix/t/edit.gif&#039;);&lt;br /&gt;
            $edit = html_writer::link($editurl, html_writer::tag(&#039;img&#039;, &#039;&#039;, array(&#039;src&#039; =&amp;gt; $editpicurl, &#039;alt&#039; =&amp;gt; get_string(&#039;edit&#039;))));&lt;br /&gt;
        } else {&lt;br /&gt;
            $edit = &#039;&#039;;&lt;br /&gt;
        }&lt;br /&gt;
        $pageurl = new moodle_url(&#039;/blocks/simplehtml/view.php&#039;, array(&#039;blockid&#039; =&amp;gt; $this-&amp;gt;instance-&amp;gt;id, &#039;courseid&#039; =&amp;gt; $COURSE-&amp;gt;id, &#039;id&#039; =&amp;gt; $simplehtmlpage-&amp;gt;id, &#039;viewpage&#039; =&amp;gt; true));&lt;br /&gt;
        $this-&amp;gt;content-&amp;gt;text .= html_writer::start_tag(&#039;li&#039;);&lt;br /&gt;
        $this-&amp;gt;content-&amp;gt;text .= html_writer::link($pageurl, $simplehtmlpage-&amp;gt;pagetitle);&lt;br /&gt;
        $this-&amp;gt;content-&amp;gt;text .= $edit;&lt;br /&gt;
        $this-&amp;gt;content-&amp;gt;text .= html_writer::end_tag(&#039;li&#039;);&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
...&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
Notice that there&#039;s a link to the same file view.php that handled the page adding. Make a few adjustments to view.php so that pages can also be updated.&lt;br /&gt;
&lt;br /&gt;
First, modify the form to have a new hidden field called id to store the id of the record in the database to know which page to update. Add the following to &#039;&#039;&#039;simplehtml_form.php&#039;&#039;&#039; :&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$mform-&amp;gt;addElement(&#039;hidden&#039;,&#039;id&#039;,&#039;0&#039;);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
Second, we alter the way the submit is handled in &#039;&#039;&#039;view.php&#039;&#039;&#039;&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
&lt;br /&gt;
...&lt;br /&gt;
&lt;br /&gt;
$toform[&#039;blockid&#039;] = $blockid;&lt;br /&gt;
$toform[&#039;courseid&#039;] = $courseid;&lt;br /&gt;
$toform[&#039;id&#039;] = $id;&lt;br /&gt;
&lt;br /&gt;
...&lt;br /&gt;
&lt;br /&gt;
// We need to add code to appropriately act on and store the submitted data&lt;br /&gt;
if ($fromform-&amp;gt;id != 0) {&lt;br /&gt;
    if (!$DB-&amp;gt;update_record(&#039;block_simplehtml&#039;, $fromform)) {&lt;br /&gt;
        print_error(&#039;updateerror&#039;, &#039;block_simplehtml&#039;);&lt;br /&gt;
    }&lt;br /&gt;
} else {&lt;br /&gt;
    if (!$DB-&amp;gt;insert_record(&#039;block_simplehtml&#039;, $fromform)) {&lt;br /&gt;
        print_error(&#039;inserterror&#039;, &#039;block_simplehtml&#039;);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
...&lt;br /&gt;
&lt;br /&gt;
// form didn&#039;t validate or this is the first display&lt;br /&gt;
$site = get_site();&lt;br /&gt;
echo $OUTPUT-&amp;gt;header();&lt;br /&gt;
if ($id) {&lt;br /&gt;
    $simplehtmlpage = $DB-&amp;gt;get_record(&#039;block_simplehtml&#039;, array(&#039;id&#039; =&amp;gt; $id));&lt;br /&gt;
    if($viewpage) {&lt;br /&gt;
        block_simplehtml_print_page($simplehtmlpage);&lt;br /&gt;
    } else {&lt;br /&gt;
        $simplehtml-&amp;gt;set_data($simplehtmlpage);&lt;br /&gt;
        $simplehtml-&amp;gt;display();&lt;br /&gt;
    }&lt;br /&gt;
} else {&lt;br /&gt;
    $simplehtml-&amp;gt;display();&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
...&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
=Page Deletion=&lt;br /&gt;
After being able to add a page and edit a page, what else would someone need to do with our html pages? Delete! Deleting is a simple operation; requiring a few simple steps::&lt;br /&gt;
&lt;br /&gt;
#Add a link to a new delete.php file&lt;br /&gt;
#Create the delete.php file&lt;br /&gt;
#Print a verification form to the screen in case the user made a mistake&lt;br /&gt;
#Use delete_record() to delete a record from the simplehtml table given an id and a confirmation.&lt;br /&gt;
==Add a link to delete a simpleHTML page==&lt;br /&gt;
Begin by editing &#039;&#039;&#039;block_simplehtml.php&#039;&#039;&#039; and creating a link just after the edit link.&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
&lt;br /&gt;
...&lt;br /&gt;
&lt;br /&gt;
    //delete&lt;br /&gt;
    $deleteparam = array(&#039;id&#039; =&amp;gt; $simplehtmlpage-&amp;gt;id, &#039;courseid&#039; =&amp;gt; $COURSE-&amp;gt;id);&lt;br /&gt;
    $deleteurl = new moodle_url(&#039;/blocks/simplehtml/delete.php&#039;, $deleteparam);&lt;br /&gt;
    $deletepicurl = new moodle_url(&#039;/pix/t/delete.gif&#039;);&lt;br /&gt;
    $delete = html_writer::link($deleteurl, html_writer::tag(&#039;img&#039;, &#039;&#039;, array(&#039;src&#039; =&amp;gt; $deletepicurl, &#039;alt&#039; =&amp;gt; get_string(&#039;delete&#039;))));&lt;br /&gt;
} else {&lt;br /&gt;
    $edit = &#039;&#039;;&lt;br /&gt;
    $delete = &#039;&#039;;&lt;br /&gt;
}&lt;br /&gt;
$pageurl = new moodle_url(&#039;/blocks/simplehtml/view.php&#039;, array(&#039;blockid&#039; =&amp;gt; $this-&amp;gt;instance-&amp;gt;id, &#039;courseid&#039; =&amp;gt; $COURSE-&amp;gt;id, &#039;id&#039; =&amp;gt; $simplehtmlpage-&amp;gt;id, &#039;viewpage&#039; =&amp;gt; true));&lt;br /&gt;
$this-&amp;gt;content-&amp;gt;text .= html_writer::start_tag(&#039;li&#039;);&lt;br /&gt;
$this-&amp;gt;content-&amp;gt;text .= html_writer::link($pageurl, $simplehtmlpage-&amp;gt;pagetitle);&lt;br /&gt;
$this-&amp;gt;content-&amp;gt;text .= $edit;&lt;br /&gt;
$this-&amp;gt;content-&amp;gt;text .= $delete;&lt;br /&gt;
&lt;br /&gt;
...&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
==Create delete.php==&lt;br /&gt;
Refresh the course page and you should now see a black X icon next to each page after the edit icon (when editing is turned on). The purpose of delete.php is to print out a notice to the user with a verification that the user wants to delete the simplehtml page. The notice will either return the user to the course if they say No, or delete the page and return the user to the course if they say Yes. Moodle has a predefined core function in weblib.php that will create the Yes-No form for you and send the user on to the correct locations based on the answer to the question. The function is called notice_yesno(). Before using this, setup the basic file structure for delete.php (it&#039;s similar to what has been used for most of the other files like view.php and simplehtml.php).&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
require_once(&#039;../../config.php&#039;);&lt;br /&gt;
 &lt;br /&gt;
$courseid = required_param(&#039;courseid&#039;, PARAM_INT);&lt;br /&gt;
$id = optional_param(&#039;id&#039;, 0, PARAM_INT);&lt;br /&gt;
$confirm = optional_param(&#039;confirm&#039;, 0, PARAM_INT);&lt;br /&gt;
 &lt;br /&gt;
if (!$course = $DB-&amp;gt;get_record(&#039;course&#039;, array(&#039;id&#039; =&amp;gt; $courseid))) {&lt;br /&gt;
    print_error(&#039;invalidcourse&#039;, &#039;block_simplehtml&#039;, $courseid);&lt;br /&gt;
}&lt;br /&gt;
 &lt;br /&gt;
require_login($course);&lt;br /&gt;
 &lt;br /&gt;
if(! $simplehtmlpage = $DB-&amp;gt;get_record(&#039;block_simplehtml&#039;, array(&#039;id&#039; =&amp;gt; $id))) {&lt;br /&gt;
    print_error(&#039;nopage&#039;, &#039;block_simplehtml&#039;, &#039;&#039;, $id);&lt;br /&gt;
}&lt;br /&gt;
 &lt;br /&gt;
$site = get_site();&lt;br /&gt;
$PAGE-&amp;gt;set_url(&#039;/blocks/simplehtml/view.php&#039;, array(&#039;id&#039; =&amp;gt; $id, &#039;courseid&#039; =&amp;gt; $courseid));&lt;br /&gt;
$heading = $site-&amp;gt;fullname . &#039; :: &#039; . $course-&amp;gt;shortname . &#039; :: &#039; . $simplehtmlpage-&amp;gt;pagetitle;&lt;br /&gt;
$PAGE-&amp;gt;set_heading($heading);&lt;br /&gt;
echo $OUTPUT-&amp;gt;header();&lt;br /&gt;
echo $OUTPUT-&amp;gt;footer();&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
This common code:&lt;br /&gt;
&lt;br /&gt;
*Checks the courseid corresponds to a valid course&lt;br /&gt;
*Checks that the user is logged in&lt;br /&gt;
*Checks that the simplehtml page id corresponds to an existing page id&lt;br /&gt;
*Prints out the header and footer for the page&lt;br /&gt;
&lt;br /&gt;
Notice that this is similar to what has been used so far, but there another optional parameter &#039;confirm&#039; has been added.&lt;br /&gt;
&lt;br /&gt;
This variable will be set when the user clicks the Yes or No button on the form. This means that a test needs to be added to test for the return value; if it is set then the database record containing the simple page id should be deleted. Add the following code after the all to the $PAGE-&amp;gt;set_heading($heading); function:&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
if (!$confirm) {&lt;br /&gt;
    $optionsno = new moodle_url(&#039;/course/view.php&#039;, array(&#039;id&#039; =&amp;gt; $courseid));&lt;br /&gt;
    $optionsyes = new moodle_url(&#039;/blocks/simplehtml/delete.php&#039;, array(&#039;id&#039; =&amp;gt; $id, &#039;courseid&#039; =&amp;gt; $courseid, &#039;confirm&#039; =&amp;gt; 1, &#039;sesskey&#039; =&amp;gt; sesskey()));&lt;br /&gt;
    echo $OUTPUT-&amp;gt;confirm(get_string(&#039;deletepage&#039;, &#039;block_simplehtml&#039;, $simplehtmlpage-&amp;gt;pagetitle), $optionsyes, $optionsno);&lt;br /&gt;
} else {&lt;br /&gt;
    if (confirm_sesskey()) {&lt;br /&gt;
        if (!$DB-&amp;gt;delete_records(&#039;block_simplehtml&#039;, array(&#039;id&#039; =&amp;gt; $id))) {&lt;br /&gt;
            print_error(&#039;deleteerror&#039;, &#039;block_simplehtml&#039;);&lt;br /&gt;
        }&lt;br /&gt;
    } else {&lt;br /&gt;
        print_error(&#039;sessionerror&#039;, &#039;block_simplehtml&#039;);&lt;br /&gt;
    }&lt;br /&gt;
    $url = new moodle_url(&#039;/course/view.php&#039;, array(&#039;id&#039; =&amp;gt; $courseid));&lt;br /&gt;
    redirect($url);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
In the if statement above, the two variables optionsno and optionsyes are set. These are used to pass variables from the form to get or post when the user selects &amp;quot;yes&amp;quot; or &amp;quot;no.&amp;quot; They are passed to the $OUTPUT-&amp;gt;confirm() function as the third and fourth parameters. If the user clicks &amp;quot;no&amp;quot; they are sent to the course page, which means the courseid needs to be added to the form. If the user clicks &amp;quot;yes&amp;quot; the database record containing the simplehtml page id is deleted and the user is forwarded to the course. The page id, courseid, confirm, and the session key need to be passed to the form. The session key is passed to prevent the possibility of a cross-site scripting attach or users submitting valid form data without using Moodle.&lt;br /&gt;
&lt;br /&gt;
==Final Clean up==&lt;br /&gt;
The block is almost finished! The one thing that has not been done is the cleanup of all data associated with the block on deletion. This is accomplished by adding a function named instance_delete() to &#039;&#039;&#039;block_simplehtml.php&#039;&#039;&#039;. In this function call delete records uses the blockid to pass in the $this-&amp;gt;instance-&amp;gt;id variable. The function looks like this: &lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
public function instance_delete() {&lt;br /&gt;
    global $DB;&lt;br /&gt;
    $DB-&amp;gt;delete_records(&#039;block_simplehtml&#039;, array(&#039;blockid&#039; =&amp;gt; $this-&amp;gt;instance-&amp;gt;id));&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
=Defining Roles for our Block=&lt;br /&gt;
We are going to create two capabilities for this block:&lt;br /&gt;
#View simplehtml page(s) which will be block/simplehtml:viewpages&lt;br /&gt;
#Modify/add simplehtml page(s) which will be block/simplehtml:managepages&lt;br /&gt;
We need to create an &#039;&#039;&#039;access.php&#039;&#039;&#039; file in the &#039;&#039;&#039;blocks/simplehtml/db directory&#039;&#039;&#039;. In that file add the simplehtml capability code:&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
defined(&#039;MOODLE_INTERNAL&#039;) || die();&lt;br /&gt;
&lt;br /&gt;
$capabilities = array(&lt;br /&gt;
    &lt;br /&gt;
    &#039;block/simplehtml:viewpages&#039; =&amp;gt; array(&lt;br /&gt;
        &lt;br /&gt;
        &#039;captype&#039; =&amp;gt; &#039;read&#039;,&lt;br /&gt;
        &#039;contextlevel&#039; =&amp;gt; CONTEXT_COURSE,&lt;br /&gt;
        &#039;legacy&#039; =&amp;gt; array(&lt;br /&gt;
            &#039;guest&#039; =&amp;gt; CAP_PREVENT,&lt;br /&gt;
            &#039;student&#039; =&amp;gt; CAP_ALLOW,&lt;br /&gt;
            &#039;teacher&#039; =&amp;gt; CAP_ALLOW,&lt;br /&gt;
            &#039;editingteacher&#039; =&amp;gt; CAP_ALLOW,&lt;br /&gt;
            &#039;coursecreator&#039; =&amp;gt; CAP_ALLOW,&lt;br /&gt;
            &#039;manager&#039; =&amp;gt; CAP_ALLOW&lt;br /&gt;
        )&lt;br /&gt;
    ),&lt;br /&gt;
    &lt;br /&gt;
    &#039;block/simplehtml:managepages&#039; =&amp;gt; array(&lt;br /&gt;
        &lt;br /&gt;
        &#039;captype&#039; =&amp;gt; &#039;read&#039;,&lt;br /&gt;
        &#039;contextlevel&#039; =&amp;gt; CONTEXT_COURSE,&lt;br /&gt;
        &#039;legacy&#039; =&amp;gt; array(&lt;br /&gt;
            &#039;guest&#039; =&amp;gt; CAP_PREVENT,&lt;br /&gt;
            &#039;student&#039; =&amp;gt; CAP_PREVENT,&lt;br /&gt;
            &#039;teacher&#039; =&amp;gt; CAP_PREVENT,&lt;br /&gt;
            &#039;editingteacher&#039; =&amp;gt; CAP_ALLOW,&lt;br /&gt;
            &#039;coursecreator&#039; =&amp;gt; CAP_ALLOW,&lt;br /&gt;
            &#039;manager&#039; =&amp;gt; CAP_ALLOW&lt;br /&gt;
        )&lt;br /&gt;
    )&lt;br /&gt;
);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
Now bump the version number up in &#039;&#039;&#039;blocks/simplehtml/version.php&#039;&#039;&#039;. Increment the last digit of $plugin-&amp;gt;version.&lt;br /&gt;
&lt;br /&gt;
Next go to the notifications link in the Site Administration block. This should update the simplehtml block. Verify that capabilities have been added by going to Users &amp;gt; Permissions &amp;gt; Define roles and selecting Manager. Search for simplehtml. &lt;br /&gt;
&lt;br /&gt;
What does the simplehtml:viewpages mean? The presence of a string surrounded by double square brackets implies that there is a string referenced in code that has not been defined in an appropriate language file. Add the following to &#039;&#039;&#039;lang/en/block_simplehtml.php&#039;&#039;&#039;:&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$string[&#039;simplehtml:viewpages&#039;] = &#039;View Simple HTML Pages&#039;;&lt;br /&gt;
$string[&#039;simplehtml:managepages&#039;] = &#039;Manage Simple HTML Pages&#039;; &lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
==Add check to the block for the capability==&lt;br /&gt;
With the two new capabilities created, it&#039;s time to use them and add a link to the form in the block. The link to the creation page is in the footer, so it&#039;s critical that the person viewing this link has the capability to manage a simplehtml page. Modify the get_content() function in blocks/simplehtml/block_simplehtml.php to check for the correct capabilities.To check for the capabilities, use the has_capability() function found in lib/access.php. Alter &#039;&#039;&#039;block_simplehtml.php&#039;&#039;&#039; to include checks for these capabilities.&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$context = context_course::instance($COURSE-&amp;gt;id);&lt;br /&gt;
&lt;br /&gt;
if (has_capability(&#039;block/simplehtml:managepages&#039;, $context)) {&lt;br /&gt;
    $url = new moodle_url(&#039;/blocks/simplehtml/view.php&#039;, array(&#039;blockid&#039; =&amp;gt; $this-&amp;gt;instance-&amp;gt;id, &#039;courseid&#039; =&amp;gt; $COURSE-&amp;gt;id));&lt;br /&gt;
    $this-&amp;gt;content-&amp;gt;footer = html_writer::link($url, get_string(&#039;addpage&#039;, &#039;block_simplehtml&#039;));&lt;br /&gt;
} else {&lt;br /&gt;
    $this-&amp;gt;content-&amp;gt;footer = &#039;&#039;;&lt;br /&gt;
}&lt;br /&gt;
        &lt;br /&gt;
// Check to see if we are in editing mode and that we can manage pages.&lt;br /&gt;
$canmanage = has_capability(&#039;block/simplehtml:managepages&#039;, $context) &amp;amp;&amp;amp; $PAGE-&amp;gt;user_is_editing($this-&amp;gt;instance-&amp;gt;id);&lt;br /&gt;
$canview = has_capability(&#039;block/simplehtml:viewpages&#039;, $context);&lt;br /&gt;
&lt;br /&gt;
...&lt;br /&gt;
&lt;br /&gt;
if ($canview) {&lt;br /&gt;
    $this-&amp;gt;content-&amp;gt;text .= html_writer::link($pageurl, $simplehtmlpage-&amp;gt;pagetitle);&lt;br /&gt;
} else {&lt;br /&gt;
    $this-&amp;gt;content-&amp;gt;text .= html_writer::tag(&#039;div&#039;, $simplehtmlpage-&amp;gt;pagetitle);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
Refresh the Moodle course to which you have added the simplehtml block. As an administrator or teacher you should see the &#039;addpage&#039; link; as a student you should not see the link. If you login as a guest you should also not that you can no longer view the pages.&lt;br /&gt;
&lt;br /&gt;
==Add Role to the simplehtml Form==&lt;br /&gt;
Currently any logged-in user can use the simplehtml form. In development this is not as big of a concern, but before moving into production always ensure that users have access to only those portions of the application that they should. Add the following line in &#039;&#039;&#039;view.php&#039;&#039;&#039; after &amp;lt;tt&amp;gt;require_login($course);&amp;lt;/tt&amp;gt;.&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
require_capability(&#039;block/simplehtml:managepages&#039;, context_course::instance($courseid));&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
This ensures the user cannot access this page without having the capability &#039;block/simplehtml:managepages&#039;.&lt;br /&gt;
&lt;br /&gt;
==Add Role to Delete==&lt;br /&gt;
To restrict deletion to those who have the managepages capability, add the following line to delete.php after require_login($course);&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
require_capability(&#039;block/simplehtml:managepages&#039;, context_course::instance($courseid));&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;/div&gt;</summary>
		<author><name>Mohessaid</name></author>
	</entry>
	<entry>
		<id>https://docs.moodle.org/dev/index.php?title=Blocks&amp;diff=53774</id>
		<title>Blocks</title>
		<link rel="alternate" type="text/html" href="https://docs.moodle.org/dev/index.php?title=Blocks&amp;diff=53774"/>
		<updated>2018-03-06T13:21:27Z</updated>

		<summary type="html">&lt;p&gt;Mohessaid: Fixed the name of the field following what was mentioned in the note above about adding &amp;#039;config_&amp;#039; to form elements names.&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&#039;&#039;&#039; A Step-by-step Guide To Creating Blocks &#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Original Author: Jon Papaioannou ([mailto:pj@moodle.org pj@moodle.org])&lt;br /&gt;
&lt;br /&gt;
Updated to Moodle 2.0 and above by: Greg J Preece ([mailto:greg.preece@blackboard.com greg.preece@blackboard.com])&lt;br /&gt;
&lt;br /&gt;
{{Moodle 2.0}}&lt;br /&gt;
&lt;br /&gt;
The present document serves as a guide to developers who want to create their own blocks for use in Moodle. It applies to the 2.0 development version of Moodle (and any newer) &#039;&#039;&#039;only&#039;&#039;&#039;, as the blocks API changed significantly enough to warrant new documentation. Those wishing to read the old tutorial for Moodles 1.5 to 1.9 can find it under [[Blocks/Blocks for 1.5 to 1.9| Blocks for 1.5 to 1.9]].&lt;br /&gt;
&lt;br /&gt;
The guide is written as an interactive course which aims to develop a configurable, multi-purpose block that displays arbitrary HTML. It&#039;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. &lt;br /&gt;
&lt;br /&gt;
Experienced developers and those who just want a &#039;&#039;&#039;programmer&#039;s reference&#039;&#039;&#039; text should refer to [[Blocks/Appendix_A| Appendix A]] because the main guide has a rather low concentration of pure information in the text.&lt;br /&gt;
&lt;br /&gt;
== Basic Concepts ==&lt;br /&gt;
&lt;br /&gt;
Through this guide, we will be following the creation of an &amp;quot;HTML&amp;quot; block from scratch in order to demonstrate most of the block features at our disposal. Our block will be named &amp;quot;SimpleHTML&amp;quot;. 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 &amp;quot;simplehtml&amp;quot; in any case where such a name is required. &lt;br /&gt;
&lt;br /&gt;
Whenever we refer to a file or directory name which contains &amp;quot;simplehtml&amp;quot;, it&#039;s important to remember that &#039;&#039;only&#039;&#039; the &amp;quot;simplehtml&amp;quot; part is up to us to change; the rest is standardised and essential for Moodle to work correctly.&lt;br /&gt;
&lt;br /&gt;
Whenever a file&#039;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.&lt;br /&gt;
&lt;br /&gt;
== Ready, Set, Go! ==&lt;br /&gt;
&lt;br /&gt;
To define a &amp;quot;block&amp;quot; in Moodle, in the most basic case we need to provide just four PHP files. Remember, in this example we are creating a block called &#039;simplehtml&#039;, replace &#039;simplehtml&#039; with the name of your custom block. The four files should be located in blocks/simplehtml and are:&lt;br /&gt;
&lt;br /&gt;
=== block_simplehtml.php ===&lt;br /&gt;
&lt;br /&gt;
This file will hold the class definition for the block, and is used both to manage it as a plugin and to render it onscreen.&lt;br /&gt;
&lt;br /&gt;
We start by creating the main object file, &#039;block_simplehtml.php&#039;. We then begin coding the block:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
class block_simplehtml extends block_base {&lt;br /&gt;
    public function init() {&lt;br /&gt;
        $this-&amp;gt;title = get_string(&#039;simplehtml&#039;, &#039;block_simplehtml&#039;);&lt;br /&gt;
    }&lt;br /&gt;
    // The PHP tag and the curly bracket for the class definition &lt;br /&gt;
    // will only be closed after there is another function added in the next section.&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The first line is our block class definition; it must be named exactly in the manner shown. Again, only the &amp;quot;simplehtml&amp;quot; part can (and indeed must) change; everything else is standardised.&lt;br /&gt;
&lt;br /&gt;
Our class is then given a small method: [[Blocks/Appendix_A#init.28.29| init()]]. This is essential for all blocks, and its purpose is to give values to any class member variables that need instantiating. &lt;br /&gt;
&lt;br /&gt;
In this very basic example, we only want to set [[Blocks/Appendix_A#.24this-.3Etitle| $this-&amp;gt;title]], which is the title displayed in the header of our block. We can set it to whatever we like; in this case it&#039;s set to read the actual title from the language file mentioned below, which is then distributed along with the block. I&#039;ll skip ahead a bit here and say that if you want your block to display &#039;&#039;&#039;no&#039;&#039;&#039; title at all, then you should set this to any descriptive value you want (but &#039;&#039;&#039;not&#039;&#039;&#039; make it an empty string). We will later see [[Blocks#Eye_Candy|how to disable the title&#039;s display]].&lt;br /&gt;
&lt;br /&gt;
=== db/access.php ===&lt;br /&gt;
&lt;br /&gt;
This file will hold the new capabilities created by the block.&lt;br /&gt;
&lt;br /&gt;
Moodle 2.4 onwards introduced the capabilities addinstance and myaddinstance for core blocks. They were introduced so that it was possible to control the use of individual blocks. These capabilities should also be added to your custom block, so in this case to the file blocks/simplehtml/db/access.php. If your block is not going to be used in the &#039;My Moodle page&#039; (ie, your applicable_formats function (discussed later) has &#039;my&#039; set to false.) then the myaddinstance capability does not need to be given to any user, but it must still be defined here otherwise you will get errors on certain pages. The following is the capabilities array and how it should look for any new blocks.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
    $capabilities = array(&lt;br /&gt;
&lt;br /&gt;
    &#039;block/simplehtml:myaddinstance&#039; =&amp;gt; array(&lt;br /&gt;
        &#039;captype&#039; =&amp;gt; &#039;write&#039;,&lt;br /&gt;
        &#039;contextlevel&#039; =&amp;gt; CONTEXT_SYSTEM,&lt;br /&gt;
        &#039;archetypes&#039; =&amp;gt; array(&lt;br /&gt;
            &#039;user&#039; =&amp;gt; CAP_ALLOW&lt;br /&gt;
        ),&lt;br /&gt;
&lt;br /&gt;
        &#039;clonepermissionsfrom&#039; =&amp;gt; &#039;moodle/my:manageblocks&#039;&lt;br /&gt;
    ),&lt;br /&gt;
&lt;br /&gt;
    &#039;block/simplehtml:addinstance&#039; =&amp;gt; array(&lt;br /&gt;
        &#039;riskbitmask&#039; =&amp;gt; RISK_SPAM | RISK_XSS,&lt;br /&gt;
&lt;br /&gt;
        &#039;captype&#039; =&amp;gt; &#039;write&#039;,&lt;br /&gt;
        &#039;contextlevel&#039; =&amp;gt; CONTEXT_BLOCK,&lt;br /&gt;
        &#039;archetypes&#039; =&amp;gt; array(&lt;br /&gt;
            &#039;editingteacher&#039; =&amp;gt; CAP_ALLOW,&lt;br /&gt;
            &#039;manager&#039; =&amp;gt; CAP_ALLOW&lt;br /&gt;
        ),&lt;br /&gt;
&lt;br /&gt;
        &#039;clonepermissionsfrom&#039; =&amp;gt; &#039;moodle/site:manageblocks&#039;&lt;br /&gt;
    ),&lt;br /&gt;
);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== lang/en/block_simplehtml.php ===&lt;br /&gt;
&lt;br /&gt;
This is the English language file for your block. If you are not an English speaker, you can replace &#039;en&#039; with your appropriate language code. All language files for blocks go under the /lang subfolder of the block&#039;s installation folder.&lt;br /&gt;
&lt;br /&gt;
Moodle 2.0 and above require a name for our plugin to show in the upgrading page. We set this value, along with the capabilities we created and any other language strings we wish to use within the block, in a language package as previously mentioned (the same file where we put our string for the plugin title).&lt;br /&gt;
&lt;br /&gt;
The capabilities added above need descriptions for pages that allow setting of capabilities. These should also be added to the language file.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
$string[&#039;pluginname&#039;] = &#039;Simple HTML block&#039;;&lt;br /&gt;
$string[&#039;simplehtml&#039;] = &#039;Simple HTML&#039;;&lt;br /&gt;
$string[&#039;simplehtml:addinstance&#039;] = &#039;Add a new simple HTML block&#039;;&lt;br /&gt;
$string[&#039;simplehtml:myaddinstance&#039;] = &#039;Add a new simple HTML block to the My Moodle page&#039;;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== version.php ===&lt;br /&gt;
&lt;br /&gt;
This file will hold version information for the plugin, along &#039;&#039;&#039;with other advanced parameters&#039;&#039;&#039; (not covered here - see [[version.php]] if you want &#039;&#039;&#039;more details&#039;&#039;&#039;).&lt;br /&gt;
&lt;br /&gt;
Prior to Moodle 2.0, version details for blocks were stored as class fields; as of Moodle 2.0 these are stored in a file called version.php, stored under &#039;&#039;/blocks/simplehtml/&#039;&#039;&#039;version.php&#039;&#039;&#039;&#039;&#039;. The version file is very simple indeed, containing only a few field definitions, depending on your needs. Here is an example:&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
$plugin-&amp;gt;component = &#039;block_simplehtml&#039;;  // Recommended since 2.0.2 (MDL-26035). Required since 3.0 (MDL-48494)&lt;br /&gt;
$plugin-&amp;gt;version = 2011062800;  // YYYYMMDDHH (year, month, day, 24-hr time)&lt;br /&gt;
$plugin-&amp;gt;requires = 2010112400; // YYYYMMDDHH (This is the release version for Moodle 2.0)&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This file contains object field definitions that denote the full [[Frankenstyle|frankenstyle]] component name in the form of &#039;&#039;plugintype_pluginname&#039;&#039; and the version number of the block, along with the minimum version of Moodle that must be installed in order to use it. Please note that the object being used here is &#039;&#039;always&#039;&#039; called &#039;&#039;&#039;$plugin&#039;&#039;&#039;, and that you do not need to create this object yourself within the version file. Note also we don&#039;t include a closing &amp;quot;?&amp;gt;&amp;quot; tag. This is intentional, and a [[Coding_style#PHP_tags | workaround for whitespace issues]].&lt;br /&gt;
&lt;br /&gt;
The exact Moodle version of a release can be found in [[Releases]].&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
{{Top}}&lt;br /&gt;
&lt;br /&gt;
== I Just Hear Static ==&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;  &lt;br /&gt;
  public function get_content() {&lt;br /&gt;
    if ($this-&amp;gt;content !== null) {&lt;br /&gt;
      return $this-&amp;gt;content;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    $this-&amp;gt;content         =  new stdClass;&lt;br /&gt;
    $this-&amp;gt;content-&amp;gt;text   = &#039;The content of our SimpleHTML block!&#039;;&lt;br /&gt;
    $this-&amp;gt;content-&amp;gt;footer = &#039;Footer here...&#039;;&lt;br /&gt;
 &lt;br /&gt;
    return $this-&amp;gt;content;&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Add your block to the front page!&#039;&#039;&#039;&lt;br /&gt;
Don&#039;t forget (especially if you&#039;re a new Moodle user) to add your block to the front page. Turn Editing On, and add your block to the page.&lt;br /&gt;
&lt;br /&gt;
It can&#039;t get any simpler than that, can it? Let&#039;s dissect this method to see what&#039;s going on...&lt;br /&gt;
&lt;br /&gt;
First of all, there is a check that returns the current value of [[Blocks/Appendix_A#.24this-.3Econtent| $this-&amp;gt;content]] if it&#039;s not NULL; otherwise we proceed with &amp;quot;computing&amp;quot; it. Since the computation is potentially a time-consuming operation and it &#039;&#039;&#039;will&#039;&#039;&#039; be called several times for each block (Moodle works that way internally), we take a precaution and include this time-saver.&lt;br /&gt;
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&#039;t much to say. Just keep in mind that we can use HTML both in the text &#039;&#039;&#039;and&#039;&#039;&#039; in the footer, if we want to.&lt;br /&gt;
&lt;br /&gt;
It&#039;s worth mentioning that this is not the only type of content a block can output. You can also create lists and hierarchical trees, which are better suited for certain types of output, such as menus. These different content types have an impact on the content object and how it is constructed. For more information, see [[Blocks/Appendix A#.24this-.3Econtent_type|Appendix A]]&lt;br /&gt;
&lt;br /&gt;
At this point our block should be capable of being automatically installed in Moodle and added to courses; visit your administration page to install it (Click &amp;quot;Notifications&amp;quot; under the Site Administration Block) and after seeing it in action come back to continue our tutorial.&lt;br /&gt;
&lt;br /&gt;
== Configure That Out ==&lt;br /&gt;
&lt;br /&gt;
The current version of our block doesn&#039;t really do much; it just displays a fixed message, which is not very useful. What we&#039;d really like to do is allow the teachers to customize what goes into the block. This, in block-speak, is called &amp;quot;instance configuration&amp;quot;. Basic instance configuration is automatic in Moodle 2.0; if you put any page with blocks on it into &amp;quot;editing mode&amp;quot;, you will notice that each block has an edit button in its title bar. Clicking on this will take you to the block configuration form. The settings that Moodle adds to this form by default relate to the block&#039;s appearance and position on Moodle pages. &lt;br /&gt;
&lt;br /&gt;
We can extend this configuration form, and add custom preferences fields, so that users can better tailor our block to a given task or page. To extend the configuration form, create the file &amp;lt;span class=&amp;quot;filename&amp;quot;&amp;gt;/blocks/simplehtml/&#039;&#039;&#039;edit_form.php&#039;&#039;&#039;&amp;lt;/span&amp;gt;, and fill it with the following code:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
&lt;br /&gt;
class block_simplehtml_edit_form extends block_edit_form {&lt;br /&gt;
        &lt;br /&gt;
    protected function specific_definition($mform) {&lt;br /&gt;
        &lt;br /&gt;
        // Section header title according to language file.&lt;br /&gt;
        $mform-&amp;gt;addElement(&#039;header&#039;, &#039;config_header&#039;, get_string(&#039;blocksettings&#039;, &#039;block&#039;));&lt;br /&gt;
&lt;br /&gt;
        // A sample string variable with a default value.&lt;br /&gt;
        $mform-&amp;gt;addElement(&#039;text&#039;, &#039;config_text&#039;, get_string(&#039;blockstring&#039;, &#039;block_simplehtml&#039;));&lt;br /&gt;
        $mform-&amp;gt;setDefault(&#039;config_text&#039;, &#039;default value&#039;);&lt;br /&gt;
        $mform-&amp;gt;setType(&#039;config_text&#039;, PARAM_RAW);        &lt;br /&gt;
&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
The first line declares a class that inherits &#039;&#039;&#039;from block_edit_form&#039;&#039;&#039;, and this allows Moodle to identify the code to execute in the configuration page. The &#039;&#039;&#039;specific_definition()&#039;&#039;&#039; method is where your form elements are defined, and these take the same format as with the standard [[lib/formslib.php_Form_Definition|Moodle form library]].  Within our specific_definition method, we have created a header, and an input field which will accept text to be used within the block. &lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;NOTE:&#039;&#039;&#039; You might want extend language file for your block (lang/en/block_simplehtml.php) and add a value for &amp;quot;blockstring&amp;quot; defined in a code above.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;IMPORTANT:&#039;&#039;&#039; All your field names need to start with &amp;quot;config_&amp;quot;, otherwise they will not be saved and will not be available within the block via [[Blocks/Appendix_A#.24this-.3Econfig| $this-&amp;gt;config]]. &lt;br /&gt;
&lt;br /&gt;
So once our instance configuration form has been saved, we can use the inputted text within the block like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
if (! empty($this-&amp;gt;config-&amp;gt;text)) {&lt;br /&gt;
    $this-&amp;gt;content-&amp;gt;text = $this-&amp;gt;config-&amp;gt;text;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Note that [[Blocks/Appendix_A#.24this-.3Econfig| $this-&amp;gt;config]] is available in all block methods &#039;&#039;except&#039;&#039; [[Blocks/Appendix_A#init.28.29|init()]]. This is because [[Blocks/Appendix_A#init.28.29|init()]] is called immediately as the block is being created, with the purpose of setting things up, so [[Blocks/Appendix_A#.24this-.3Econfig| $this-&amp;gt;config]] has not yet been instantiated.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Note about Checkbox:&#039;&#039;&#039; You cannot use the &#039;checkbox&#039; element in the form (once set it will stay set). You must use advcheckbox instead. &lt;br /&gt;
&lt;br /&gt;
{{Top}}&lt;br /&gt;
&lt;br /&gt;
== The Specialists ==&lt;br /&gt;
&lt;br /&gt;
Implementing instance configuration for the block&#039;s contents was good enough to whet our appetite, but who wants to stop there? Why not customize the block&#039;s title, too?&lt;br /&gt;
&lt;br /&gt;
Why not, indeed. Well, our first attempt to achieve this is natural enough: let&#039;s add another field to &#039;&#039;/blocks/simplehtml/&#039;&#039;&#039;edit_form.php&#039;&#039;&#039;&#039;&#039;. Here goes:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
    // A sample string variable with a default value.&lt;br /&gt;
    $mform-&amp;gt;addElement(&#039;text&#039;, &#039;config_title&#039;, get_string(&#039;blocktitle&#039;, &#039;block_simplehtml&#039;));&lt;br /&gt;
    $mform-&amp;gt;setDefault(&#039;config_title&#039;, &#039;default value&#039;);&lt;br /&gt;
    $mform-&amp;gt;setType(&#039;config_title&#039;, PARAM_TEXT);        &lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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&#039;s not being displayed. All we get is just the simple &amp;quot;SimpleHTML&amp;quot; title.&lt;br /&gt;
&lt;br /&gt;
That&#039;s not too weird, if we think back a bit. Do you remember that [[Blocks/Appendix_A#init.28.29|init()]] method, where we set [[Blocks/Appendix_A#.24this-.3Etitle|$this-&amp;gt;title]]? We didn&#039;t actually change its value from then, and [[Blocks/Appendix_A#.24this-.3Etitle|$this-&amp;gt;title]] is definitely not the same as &#039;&#039;&#039;$this-&amp;gt;config-&amp;gt;title&#039;&#039;&#039; (to Moodle, at least). What we need is a way to update [[Blocks/Appendix_A#.24this-.3Etitle|$this-&amp;gt;title]] with the value in the instance configuration. But as we said a bit earlier, we can use [[Blocks/Appendix_A#.24this-.3Econfig| $this-&amp;gt;config]] in all methods &#039;&#039;except&#039;&#039; [[Blocks/Appendix_A#init.28.29|init()]]! So what can we do?&lt;br /&gt;
&lt;br /&gt;
Let&#039;s pull out another ace from our sleeve, and add this small method to our block class:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
public function specialization() {&lt;br /&gt;
    if (isset($this-&amp;gt;config)) {&lt;br /&gt;
        if (empty($this-&amp;gt;config-&amp;gt;title)) {&lt;br /&gt;
            $this-&amp;gt;title = get_string(&#039;defaulttitle&#039;, &#039;block_simplehtml&#039;);            &lt;br /&gt;
        } else {&lt;br /&gt;
            $this-&amp;gt;title = $this-&amp;gt;config-&amp;gt;title;&lt;br /&gt;
        }&lt;br /&gt;
&lt;br /&gt;
        if (empty($this-&amp;gt;config-&amp;gt;text)) {&lt;br /&gt;
            $this-&amp;gt;config-&amp;gt;text = get_string(&#039;defaulttext&#039;, &#039;block_simplehtml&#039;);&lt;br /&gt;
        }    &lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Aha, here&#039;s what we wanted to do all along! But what&#039;s going on with the [[Blocks/Appendix_A#specialization.28.29| specialization()]] method?&lt;br /&gt;
&lt;br /&gt;
This &amp;quot;magic&amp;quot; method has actually a very nice property: it&#039;s &#039;&#039;guaranteed&#039;&#039; to be automatically called by Moodle as soon as our instance configuration is loaded and available (that is, immediately after [[Blocks/Appendix_A#init.28.29|init()]] is called). That means before the block&#039;s content is computed for the first time, and indeed before &#039;&#039;anything&#039;&#039; else is done with the block. Thus, providing a [[Blocks/Appendix_A#specialization.28.29| specialization()]] method is the natural choice for any configuration data that needs to be acted upon or made available &amp;quot;as soon as possible&amp;quot;, as in this case.&lt;br /&gt;
&lt;br /&gt;
{{Top}}&lt;br /&gt;
&lt;br /&gt;
== Now You See Me, Now You Don&#039;t ==&lt;br /&gt;
&lt;br /&gt;
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&#039;t have anything useful to say. An example here would be the &amp;quot;Recent Activity&amp;quot; block, in the case where no recent activity in fact exists. &lt;br /&gt;
&lt;br /&gt;
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 &amp;quot;disappear&amp;quot; if it&#039;s not needed to display it.&lt;br /&gt;
&lt;br /&gt;
This is indeed possible, and the way to do it is to make sure that after the [[Blocks/Appendix_A#get_content.28.29| get_content()]] method is called, the block has no content to display. This means that all fields in $this-&amp;gt;content should be equal to the empty string (&amp;lt;nowiki&amp;gt;&#039;&#039;&amp;lt;/nowiki&amp;gt;). In the case of our HTML-based block, these fields are $this-&amp;gt;content-&amp;gt;text and $this-&amp;gt;content-&amp;gt;footer. Moodle performs this check by calling the block&#039;s [[Blocks/Appendix_A#is_empty.28.29| is_empty()]] method, and if the block is indeed empty then it is not displayed at all.&lt;br /&gt;
&lt;br /&gt;
Note that the exact value of the block&#039;s title and the presence or absence of a [[Blocks/Appendix_A#hide_header.28.29| hide_header()]] method do &#039;&#039;not&#039;&#039; affect this behavior. A block is considered empty if it has no content, irrespective of anything else.&lt;br /&gt;
&lt;br /&gt;
{{Top}}&lt;br /&gt;
&lt;br /&gt;
== We Are Legion ==&lt;br /&gt;
&lt;br /&gt;
Right now our block is fully configurable, both in title and content. It&#039;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:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
public function instance_allow_multiple() {&lt;br /&gt;
  return true;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
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!&lt;br /&gt;
&lt;br /&gt;
Please note that even if a block itself allows multiple instances in the same page, the administrator still has the option of disallowing such behavior. This setting can be set separately for each block from the Administration / Configuration / Blocks page.&lt;br /&gt;
&lt;br /&gt;
{{Top}}&lt;br /&gt;
&lt;br /&gt;
== The Effects of Globalization ==&lt;br /&gt;
&lt;br /&gt;
Configuring each block instance with its own personal data is cool enough, but sometimes administrators need some way to &amp;quot;touch&amp;quot; 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&#039;t that hard to come up with. &lt;br /&gt;
&lt;br /&gt;
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&#039;s contents, only allowing pure text in. Granted, such a feature wouldn&#039;t win us any awards for naming our block &amp;quot;SimpleHTML&amp;quot; but some tormented administrator somewhere might actually find it useful.&lt;br /&gt;
&lt;br /&gt;
This kind of configuration is called &amp;quot;global configuration&amp;quot; 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&#039;s contents. To enable global configuration for the block, we create a new file, &#039;&#039;/blocks/simplehtml/&#039;&#039;&#039;settings.php&#039;&#039;&#039;&#039;&#039;, and populate it with form field definitions for each setting, which Moodle will use to generate and handle a global settings form.  This is quite similar in concept to how we generated the instance configuration form earlier, but the actual code used to generate the form and fields is somewhat different.&lt;br /&gt;
&lt;br /&gt;
Place the following in your settings.php file:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
&amp;lt;?php&lt;br /&gt;
$settings-&amp;gt;add(new admin_setting_heading(&lt;br /&gt;
            &#039;headerconfig&#039;,&lt;br /&gt;
            get_string(&#039;headerconfig&#039;, &#039;block_simplehtml&#039;),&lt;br /&gt;
            get_string(&#039;descconfig&#039;, &#039;block_simplehtml&#039;)&lt;br /&gt;
        ));&lt;br /&gt;
&lt;br /&gt;
$settings-&amp;gt;add(new admin_setting_configcheckbox(&lt;br /&gt;
            &#039;simplehtml/Allow_HTML&#039;,&lt;br /&gt;
            get_string(&#039;labelallowhtml&#039;, &#039;block_simplehtml&#039;),&lt;br /&gt;
            get_string(&#039;descallowhtml&#039;, &#039;block_simplehtml&#039;),&lt;br /&gt;
            &#039;0&#039;&lt;br /&gt;
        ));    &lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
As you can see, to generate a global configuration form, we simply create admin setting objects and add them to an array. This array is then stepped over to create the settings form, and the inputted data is automatically saved to the database. Full details of the setting types available and how to add them can be found under [[Admin_settings#Individual_settings]].&lt;br /&gt;
&lt;br /&gt;
We&#039;ve now created a header and checkbox form element to accept configuration details from the site admin. You should pay extra attention to the name of our checkbox element, &#039;&#039;&#039; &#039;simplehtml/Allow_HTML&#039; &#039;&#039;&#039;, as it specifies not only the name of the configuration option, but also how it should be stored. If you simply specify a name for the config option, it will be stored in the global $CFG object, and in the &#039;&#039;&amp;lt;prefix&amp;gt;_config&#039;&#039; database table. This will make your config variable available immediately via $CFG without requiring an additional database call, but will also increase the size of the $CFG object. In addition, we must prefix the variable with the name of our block, otherwise we run the risk of our config variable sharing its name with a similar variable in another plugin, or within Moodle itself.&lt;br /&gt;
&lt;br /&gt;
The preferred method of storing your block&#039;s configuration data is to prefix each config variable name in your settings.php file with your block&#039;s name, followed by a slash ( / ), and the name of the configuration variable, as we have done above. If you write your settings.php file in this way, then your variables will be stored in the &#039;&#039;&amp;lt;prefix&amp;gt;_config_plugin&#039;&#039; table, under your block&#039;s name. Your config data will still be available via a &#039;&#039;&#039;get_config()&#039;&#039;&#039; call, and name collision will be impossible between plugins.&lt;br /&gt;
&lt;br /&gt;
Finally, if you&#039;re wondering why there are two language tags specified for each element, the first tag is for the element&#039;s label or primary text, and the second tag is for its description. And that&#039;s it. Pretty easy, huh?&lt;br /&gt;
&lt;br /&gt;
=== Enabling Global Configuration ===&lt;br /&gt;
{{Moodle 2.4}}Since version 2.4, the following line must be added to the /blocks/simplehtml/block_simplehtml.php file in order to enable global configuration:&lt;br /&gt;
&amp;lt;code&amp;gt;&lt;br /&gt;
    function has_config() {return true;}&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
This line tells Moodle that the block has a settings.php file.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;NOTE FOR UPGRADERS&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
You&#039;ll notice that the settings.php file and parsed element names replaces Moodle&#039;s old storage method, wherein it would send all the configuration data to your block&#039;s [[Blocks/Appendix_A#config_save.28.29|config_save()]] method, and allow you to override how the data is saved. The [[Blocks/Appendix_A#config_save.28.29|config_save()]] method is no longer used in Moodle 2.x; however the [[Blocks/Appendix_A#instance_config_save.28.29|instance_config_save()]] method is very much alive and well, as you will see shortly.&lt;br /&gt;
&lt;br /&gt;
{{Top}}&lt;br /&gt;
&lt;br /&gt;
=== Accessing Global Config Data  ===&lt;br /&gt;
&lt;br /&gt;
Now that we have global data defined for the plugin, we need to know how to access it within our code.  If you saved your config variables in the global namespace, you can access them from the global $CFG object, like so:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$allowHTML = $CFG-&amp;gt;Allow_HTML;&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If, as recommended, you saved your config variables in a custom namespace for your block, then you can access them via a call to &#039;&#039;&#039;get_config()&#039;&#039;&#039;:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$allowHTML = get_config(&#039;simplehtml&#039;, &#039;Allow_HTML&#039;);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
{{Top}}&lt;br /&gt;
&lt;br /&gt;
=== Rolling It All Together ===&lt;br /&gt;
&lt;br /&gt;
OK, so we now have an instance configuration form that allows users to enter custom content text for a block, and a global configuration option that dictates whether or not that user should be allowed to enter HTML tags as part of the content. Now we just need to tie the two together. But if Moodle takes care of the form processing for our instance configuration in edit_form.php, how can we capture it and remove the HTML tags where required?&lt;br /&gt;
&lt;br /&gt;
Well, fortunately, there is a way this can be done.  By overriding the [[Blocks/Appendix_A#instance_config_save.28.29| instance_config_save()]] method in our block class, we can modify the way in which instance configuration data is stored after input. The default implementation is as follows:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
public function instance_config_save($data, $nolongerused = false) {&lt;br /&gt;
  $data = stripslashes_recursive($data);&lt;br /&gt;
  $this-&amp;gt;config = $data;&lt;br /&gt;
  return set_field(&#039;block_instance&#039;, &lt;br /&gt;
                   &#039;configdata&#039;,&lt;br /&gt;
                    base64_encode(serialize($data)),&lt;br /&gt;
                   &#039;id&#039;, &lt;br /&gt;
                   $this-&amp;gt;instance-&amp;gt;id);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This may look intimidating at first (what&#039;s all this stripslashes_recursive() and base64_encode() and serialize() stuff?) but do not despair; we won&#039;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:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
public function instance_config_save($data,$nolongerused =false) {&lt;br /&gt;
  if(get_config(&#039;simplehtml&#039;, &#039;Allow_HTML&#039;) == &#039;1&#039;) {&lt;br /&gt;
    $data-&amp;gt;text = strip_tags($data-&amp;gt;text);&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
  // And now forward to the default implementation defined in the parent class&lt;br /&gt;
  return parent::instance_config_save($data,$nolongerused);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
(This example assumes you are using a custom namespace for the block.)&lt;br /&gt;
&lt;br /&gt;
At last! Now the administrator has absolute power of life and death over what type of content is allowed in our &amp;quot;SimpleHTML&amp;quot; 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 &amp;quot;off&amp;quot;, this will only prevent subsequent content changes from including HTML. Blocks which already had HTML in their content would continue to display it!&lt;br /&gt;
&lt;br /&gt;
Following that train of thought, the next stop is realizing that we wouldn&#039;t have this problem if we had chosen the lazy approach a while back, because in that case we would &amp;quot;sanitize&amp;quot; each block&#039;s content just before it was displayed. &lt;br /&gt;
&lt;br /&gt;
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 &amp;quot;HTML off&amp;quot;; but even then, turning the setting back to &amp;quot;HTML on&amp;quot; won&#039;t bring back the tags we stripped away. On the other hand, the lazy approach might be slower, but it&#039;s more versatile; we can choose whether to strip or keep the HTML before displaying the content, and we won&#039;t lose it at all if the admin toggles the setting off and on again. Isn&#039;t the life of a developer simple and wonderful?&lt;br /&gt;
&lt;br /&gt;
=== Exercise === &lt;br /&gt;
We will let this part of the tutorial come to a close with the obligatory exercise for the reader: &lt;br /&gt;
In order to have the SimpleHTML block work &amp;quot;correctly&amp;quot;, find out how to strengthen the eager approach to strip out all tags from the existing configuration of all instances of our block, &#039;&#039;&#039;or&#039;&#039;&#039; go back and implement the lazy approach instead. &lt;br /&gt;
(Hint: Do that in the [[Blocks/Appendix_A#get_content.28.29| get_content()]] method.)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
{{Top}}&lt;br /&gt;
&lt;br /&gt;
== Eye Candy ==&lt;br /&gt;
&lt;br /&gt;
Our block is just about complete functionally, so now let&#039;s take a look at some of the tricks we can use to make its behavior customized in a few more useful ways.&lt;br /&gt;
&lt;br /&gt;
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&#039;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:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
public function hide_header() {&lt;br /&gt;
  return true;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
One more note here: we cannot just set an empty title inside the block&#039;s [[Blocks/Appendix_A#init.28.29| init()]] method; it&#039;s necessary for each block to have a unique, non-empty title after [[Blocks/Appendix_A#init.28.29| init()]] is called so that Moodle can use those titles to differentiate between all of the installed blocks.&lt;br /&gt;
&lt;br /&gt;
Next, we can affect some properties of the actual HTML that will be used to print our block. Each block is fully contained within a &amp;amp;lt;div&amp;amp;gt; or &amp;amp;lt;table&amp;amp;gt; elements, inside which all the HTML for that block is printed. We can instruct Moodle to add HTML attributes with specific values to that container. This is generally done to give us freedom to customize the end result using CSS (this is in fact done by default as we&#039;ll see below).&lt;br /&gt;
&lt;br /&gt;
The default behavior of this feature in our case will modify our block&#039;s &amp;quot;class&amp;quot; HTML attribute by appending the value &amp;quot;block_simplehtml&amp;quot; (the prefix &amp;quot;block_&amp;quot; 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&#039;s visual style (for example, &amp;quot;.block_simplehtml { border: 1px black solid}&amp;quot;).&lt;br /&gt;
&lt;br /&gt;
To change the default behavior, we will need to define a method which returns an associative array of attribute names and values. For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
public function html_attributes() {&lt;br /&gt;
    $attributes = parent::html_attributes(); // Get default values&lt;br /&gt;
    $attributes[&#039;class&#039;] .= &#039; block_&#039;. $this-&amp;gt;name(); // Append our class to class attribute&lt;br /&gt;
    return $attributes;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This results in the block having all its normal HTML attributes, as inherited from the base block class, plus our additional class name. We can now use this class name to change the style of the block, add JavaScript events to it via YUI, and so on. And for one final elegant touch,  we have not set the class to the hard-coded value &amp;quot;block_simplehtml&amp;quot;, but instead used the [[Blocks/Appendix_A#name.28.29| name()]] method to make it dynamically match our block&#039;s name.&lt;br /&gt;
&lt;br /&gt;
{{Top}}&lt;br /&gt;
&lt;br /&gt;
== Authorized Personnel Only ==&lt;br /&gt;
&lt;br /&gt;
Some blocks are useful in some circumstances, but not in others. An example of this would be the &amp;quot;Social Activities&amp;quot; block, which is useful in courses with the &amp;quot;social&amp;quot; course format, but not courses with the &amp;quot;weeks&amp;quot; format. What we need to be able to do is limit our block&#039;s availability, so that it can only be selected on pages where its content or abilities are appropriate.&lt;br /&gt;
&lt;br /&gt;
Moodle allows us to declare which page formats a block is available on, and enforces these restrictions as set by the block&#039;s developer at all times. The information is given to Moodle as a standard associative array, with each key corresponding to a page format and defining a boolean value (true/false) that declares whether the block should be allowed to appear in that page format.&lt;br /&gt;
&lt;br /&gt;
Notice the deliberate use of the term &#039;&#039;page&#039;&#039; instead of &#039;&#039;course&#039;&#039; 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.&lt;br /&gt;
&lt;br /&gt;
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 &amp;lt;span class=&amp;quot;filename&amp;quot;&amp;gt;/course/view.php&amp;lt;/span&amp;gt; (this is evident from the browser&#039;s address line). Thus, the format name of that page is &#039;&#039;&#039;course-view&#039;&#039;&#039;. It follows easily that the format name for a quiz view page is &#039;&#039;&#039;mod-quiz-view&#039;&#039;&#039;. This rule of thumb does have a few exceptions, however:&lt;br /&gt;
&lt;br /&gt;
# The format name for the front page of Moodle is &#039;&#039;&#039;site-index&#039;&#039;&#039;.&lt;br /&gt;
# The format name for courses is actually not just &#039;&#039;&#039;course-view&#039;&#039;&#039;&amp;lt;nowiki&amp;gt;; it is &amp;lt;/nowiki&amp;gt;&#039;&#039;&#039;course-view-weeks&#039;&#039;&#039;, &#039;&#039;&#039;course-view-topics&#039;&#039;&#039;, etc.&lt;br /&gt;
# Even though there is no such page, the format name &#039;&#039;&#039;all&#039;&#039;&#039; can be used as a catch-all option.&lt;br /&gt;
&lt;br /&gt;
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 &amp;quot;is this block allowed into this page or not?&amp;quot;:&lt;br /&gt;
&lt;br /&gt;
# Prefixes of a format name will match that format name; for example, &#039;&#039;&#039;mod&#039;&#039;&#039; will match all the activity modules. &#039;&#039;&#039;course-view&#039;&#039;&#039; will match any course, regardless of the course format. And finally, &#039;&#039;&#039;site&#039;&#039;&#039; will also match the front page (remember that its full format name is &#039;&#039;&#039;site-index&#039;&#039;&#039;).&lt;br /&gt;
# 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, &#039;&#039;&#039;mod&#039;&#039;&#039;, &#039;&#039;&#039;mod-quiz&#039;&#039;&#039; and &#039;&#039;&#039;mod-quiz-view&#039;&#039;&#039; all match the quiz view page. But if all three are present, &#039;&#039;&#039;mod-quiz-view&#039;&#039;&#039; will take precedence over the other two because it is a better match.&lt;br /&gt;
# The character &#039;&#039;&#039;&amp;lt;nowiki&amp;gt;*&amp;lt;/nowiki&amp;gt;&#039;&#039;&#039; can be used in place of any word. For example, &#039;&#039;&#039;mod&#039;&#039;&#039; and &#039;&#039;&#039;mod-*&#039;&#039;&#039; are equivalent. At the time of this document&#039;s writing, there is no actual reason to utilize this &amp;quot;wildcard matching&amp;quot; feature, but it exists for future usage.&lt;br /&gt;
# The order that the format names appear does not make any difference.&lt;br /&gt;
All of the above are enough to make the situation sound complex, so let&#039;s look at some specific examples. First of all, to have our block appear &#039;&#039;&#039;only&#039;&#039;&#039; in the site front page, we would use:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt; &lt;br /&gt;
public function applicable_formats() {&lt;br /&gt;
  return array(&#039;site-index&#039; =&amp;gt; true);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Since &#039;&#039;&#039;all&#039;&#039;&#039; is missing, the block is disallowed from appearing in &#039;&#039;any&#039;&#039; course format; but then &#039;&#039;&#039;site&#039;&#039;&#039; is set to TRUE, so it&#039;s explicitly allowed to appear in the site front page (remember that &#039;&#039;&#039;site&#039;&#039;&#039; matches &#039;&#039;&#039;site-index&#039;&#039;&#039; because it&#039;s a prefix).&lt;br /&gt;
&lt;br /&gt;
For another example, if we wanted to allow the block to appear in all course formats &#039;&#039;except&#039;&#039; social, and also to &#039;&#039;not&#039;&#039; be allowed anywhere but in courses, we would use:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt; &lt;br /&gt;
public function applicable_formats() {&lt;br /&gt;
  return array(&lt;br /&gt;
           &#039;course-view&#039; =&amp;gt; true, &lt;br /&gt;
    &#039;course-view-social&#039; =&amp;gt; false);&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This time, we first allow the block to appear in all courses and then we explicitly disallow the social format.&lt;br /&gt;
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, &#039;&#039;except&#039;&#039; quiz. This would be:&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
public function applicable_formats() {&lt;br /&gt;
  return array(&lt;br /&gt;
           &#039;site-index&#039; =&amp;gt; true,&lt;br /&gt;
          &#039;course-view&#039; =&amp;gt; true, &lt;br /&gt;
   &#039;course-view-social&#039; =&amp;gt; false,&lt;br /&gt;
                  &#039;mod&#039; =&amp;gt; true, &lt;br /&gt;
             &#039;mod-quiz&#039; =&amp;gt; false&lt;br /&gt;
  );&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
It is not difficult to realize that the above accomplishes the objective if we remember that there is a &amp;quot;best match&amp;quot; policy to determine the end result.&lt;br /&gt;
&lt;br /&gt;
{{Top}}&lt;br /&gt;
&lt;br /&gt;
== Background Processing ==&lt;br /&gt;
&lt;br /&gt;
If you want to do some background processing in your block - use the [[Task API]] to create a background task that can be scheduled to run at regular intervals and can be displayed and configured by an administrator (this is the same regardless of the plugin type).&lt;br /&gt;
&lt;br /&gt;
{{Top}}&lt;br /&gt;
&lt;br /&gt;
== Additional Content Types == &lt;br /&gt;
&lt;br /&gt;
=== Lists ===&lt;br /&gt;
&lt;br /&gt;
In this final part of the guide we will briefly discuss several additional capabilities of Moodle&#039;s block system, namely the ability to create blocks that display different kinds of content to the user. The first of these creates a list of options and displays them to the user.  This list is displayed with one item per line, and an optional image (icon) next to the item. An example of such a &#039;&#039;list block&#039;&#039; is the standard Moodle &amp;quot;admin&amp;quot; block, which illustrates all the points discussed in this section.&lt;br /&gt;
&lt;br /&gt;
As we have seen so far, blocks use two properties of [[Blocks/Appendix_A#.24this-.3Econtent| $this-&amp;gt;content]]: &amp;quot;text&amp;quot; and &amp;quot;footer&amp;quot;. 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-&amp;gt;content-&amp;gt;footer in the exact same way, but they ignore $this-&amp;gt;content-&amp;gt;text.&lt;br /&gt;
&lt;br /&gt;
Instead, Moodle expects such blocks to set two other properties when the [[Blocks/Appendix_A#get_content.28.29| get_content()]] method is called: $this-&amp;gt;content-&amp;gt;items and $this-&amp;gt;content-&amp;gt;icons. $this-&amp;gt;content-&amp;gt;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-&amp;gt;content-&amp;gt;icons should also be a numerically indexed array, with exactly as many items as $this-&amp;gt;content-&amp;gt;items has. Each of these items should be a fully qualified HTML &amp;lt;img&amp;gt; tag, with &amp;quot;src&amp;quot;, &amp;quot;height&amp;quot;, &amp;quot;width&amp;quot; and &amp;quot;alt&amp;quot; attributes. Obviously, it makes sense to keep the images small and of a uniform size. We would recommend standard 16x16 images for this purpose.&lt;br /&gt;
&lt;br /&gt;
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 &#039;&#039;&#039;block_base&#039;&#039;&#039;, our block will extend class &#039;&#039;&#039;block_list&#039;&#039;&#039;. For example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt; &lt;br /&gt;
class block_my_menu extends block_list {&lt;br /&gt;
     // The init() method does not need to change at all&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In addition to making this change, we must of course also modify the [[Blocks/Appendix_A#get_content.28.29| get_content()]] method to construct the [[Blocks/Appendix_A#.24this-.3Econtent| $this-&amp;gt;content]] variable as discussed above:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt; &lt;br /&gt;
public function get_content() {&lt;br /&gt;
  if ($this-&amp;gt;content !== null) {&lt;br /&gt;
    return $this-&amp;gt;content;&lt;br /&gt;
  }&lt;br /&gt;
 &lt;br /&gt;
  $this-&amp;gt;content         = new stdClass;&lt;br /&gt;
  $this-&amp;gt;content-&amp;gt;items  = array();&lt;br /&gt;
  $this-&amp;gt;content-&amp;gt;icons  = array();&lt;br /&gt;
  $this-&amp;gt;content-&amp;gt;footer = &#039;Footer here...&#039;;&lt;br /&gt;
 &lt;br /&gt;
  $this-&amp;gt;content-&amp;gt;items[] = html_writer::tag(&#039;a&#039;, &#039;Menu Option 1&#039;, array(&#039;href&#039; =&amp;gt; &#039;some_file.php&#039;));&lt;br /&gt;
  $this-&amp;gt;content-&amp;gt;icons[] = html_writer::empty_tag(&#039;img&#039;, array(&#039;src&#039; =&amp;gt; &#039;images/icons/1.gif&#039;, &#039;class&#039; =&amp;gt; &#039;icon&#039;));&lt;br /&gt;
&lt;br /&gt;
  // Add more list items here&lt;br /&gt;
 &lt;br /&gt;
  return $this-&amp;gt;content;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
To summarise, if we want to create a list block instead of a text block, we just need to change the block class declaration and the [[Blocks/Appendix_A#get_content.28.29| get_content()]] method. Adding the mandatory [[Blocks/Appendix_A#init.28.29| init()]] method as discussed earlier will then give us our first list block in no time!&lt;br /&gt;
&lt;br /&gt;
=== Trees ===&lt;br /&gt;
&lt;br /&gt;
As of 23rd December 2011, this functionality remains inoperable in all Moodle 2.x versions. It appears that classes are missing from the code base. This has been added to the tracker at the URL below. Please upvote this issue if you require this functionality.&lt;br /&gt;
&lt;br /&gt;
[http://tracker.moodle.org/browse/MDL-28289 Visit this issue on the tracker @ MDL28289]&lt;br /&gt;
&lt;br /&gt;
{{Top}}&lt;br /&gt;
&lt;br /&gt;
== Database support ==&lt;br /&gt;
In case we need to have a database table that holds some specific information used within our block, we will need to create the file &#039;&#039;/blocks/simplehtml/&#039;&#039;&#039;install.xml&#039;&#039;&#039;&#039;&#039; with the table schema contained within it.&lt;br /&gt;
&lt;br /&gt;
To create the install.xml file, use the [[XMLDB editor]]. See [[Database_FAQ#XMLDB|Database FAQ &amp;gt; XMLDB]] for further details.&lt;br /&gt;
&lt;br /&gt;
Up-to-date documentation on upgrading our block, as well as providing new capabilities and events to the system, can be found under [https://docs.moodle.org/dev/Installing_and_upgrading_plugin_database_tables#install.php Installing and Upgrading Plugin Database Tables]&lt;br /&gt;
&lt;br /&gt;
== See also ==&lt;br /&gt;
* [[Blocks Advanced]] A continuation of this tutorial.&lt;br /&gt;
* [http://dev.moodle.org/mod/resource/view.php?id=48 Unit 7 of the Introduction to Moodle Programming course] is a follow up to this course. (But you should follow the forum discussions of that course closely as there are still some bugs and inconsistencies.)&lt;br /&gt;
* Daniel Neis Araujo&#039;s [https://github.com/danielneis/moodle-block_newblock NEWBLOCK template].&lt;br /&gt;
&lt;br /&gt;
== Appendices ==&lt;br /&gt;
&lt;br /&gt;
The appendices have been moved to separate pages:&lt;br /&gt;
&lt;br /&gt;
* Appendix A: [[Blocks/Appendix A|&#039;&#039;block_base&#039;&#039; Reference]] &lt;br /&gt;
&lt;br /&gt;
{{Top}}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:Blocks]]&lt;br /&gt;
[[Category:Tutorial]]&lt;br /&gt;
&lt;br /&gt;
[[es:Desarrollo de bloques]]&lt;br /&gt;
[[ja:開発:ブロック]]&lt;br /&gt;
[[:en:Blocks|Blocks]]&lt;br /&gt;
&lt;br /&gt;
[[Category:Plugins]]&lt;/div&gt;</summary>
		<author><name>Mohessaid</name></author>
	</entry>
	<entry>
		<id>https://docs.moodle.org/dev/index.php?title=Admin_settings&amp;diff=53166</id>
		<title>Admin settings</title>
		<link rel="alternate" type="text/html" href="https://docs.moodle.org/dev/index.php?title=Admin_settings&amp;diff=53166"/>
		<updated>2017-11-04T12:08:49Z</updated>

		<summary type="html">&lt;p&gt;Mohessaid: Omit the redundant &amp;#039;The&amp;#039; from the sentence.&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Moodle&#039;s configuration is stored in a mixture of the config, config_plugins, and a few other tables. These settings are edited through the administration screens, which can be accessed by going to the .../admin/index.php URL on your moodle site, or using the Administration block that appears to administrators of the Moodle front page. This page explains how the code for displaying and editing of these settings works.&lt;br /&gt;
&lt;br /&gt;
==Where to find the code==&lt;br /&gt;
&lt;br /&gt;
This is explained further below, but in summary:&lt;br /&gt;
* The library code is all in lib/adminlib.php.&lt;br /&gt;
* The definition of all the parts of the admin tree is in admin/settings/* some of which call out to plugins to see if they have settings they want to add.&lt;br /&gt;
* The editing and saving of settings is managed by admin/settings.php, admin/upgradesettings.php, and admin/search.php.&lt;br /&gt;
* The administration blocks that appear on the front page and on most of the admin screens is in blocks/admin_tree and blocks/admin_bookmarks.&lt;br /&gt;
&lt;br /&gt;
In my experience most of this code is pretty easy to understand and work with, so here I will focus on giving an overview. For details, see the code.&lt;br /&gt;
&lt;br /&gt;
==The building blocks==&lt;br /&gt;
&lt;br /&gt;
All the settings are arranged into a tree structure. This tree structure is represented in memory as a tree of PHP objects.&lt;br /&gt;
&lt;br /&gt;
At the root of the tree is an &#039;&#039;&#039;admin_root&#039;&#039;&#039; object.&lt;br /&gt;
&lt;br /&gt;
That has children that are &#039;&#039;&#039;admin_category&#039;&#039;&#039;s.&lt;br /&gt;
&lt;br /&gt;
Admin categories contain other categories, &#039;&#039;&#039;admin_settingpage&#039;&#039;&#039;s, and &#039;&#039;&#039;admin_externalpage&#039;&#039;&#039;s.&lt;br /&gt;
&lt;br /&gt;
Settings pages contain individual &#039;&#039;&#039;admin_setting&#039;&#039;&#039;s.&lt;br /&gt;
&lt;br /&gt;
admin_setting is a base class with lots of subclasses like &#039;&#039;&#039;admin_setting_configtext&#039;&#039;&#039;, &#039;&#039;&#039;admin_setting_configcheckbox&#039;&#039;&#039;, and so on. If you need to, you can create new subclasses.&lt;br /&gt;
&lt;br /&gt;
External pages are for things that do not fit into the normal settings structure. For example the global assign roles page, or the page for managing activity modules.&lt;br /&gt;
&lt;br /&gt;
==How the tree is built==&lt;br /&gt;
&lt;br /&gt;
When Moodle needs the admin tree, it calls admin_get_root in lib/adminlib.php, which&lt;br /&gt;
# creates a global $ADMIN object which is an instance of admin_root.&lt;br /&gt;
# does require_once admin/settings/top.php, which adds the top level categories to $ADMIN.&lt;br /&gt;
# does require_once on all the other files in admin/settings to add more specific settings pages and the settings themselves. Some of these settings files additionally make calls out to various types of plugins. For example&lt;br /&gt;
#* admin/settings/plugins.php gives activity modules, blocks, question types, ... a chance to add admin settings.&lt;br /&gt;
# adds the admin reports to the tree.&lt;br /&gt;
&lt;br /&gt;
As an optimisation, before building each bit of the tree, some capability checks are performed, and bits of the tree are skipped if the current user does not have permission to access them.&lt;br /&gt;
&lt;br /&gt;
Exactly how different types of plugin should add their settings to the tree should be documented in the [[Developer_documentation#Make_a_new_plugin|instructions for writing that sort of plugin]].&lt;br /&gt;
&lt;br /&gt;
==Individual settings==&lt;br /&gt;
&lt;br /&gt;
Let us look at a simple example: [https://github.com/moodle/moodle/blob/master/mod/forum/settings.php mod/forum/settings.php]. This is included by admin/settings/plugins.php, which has already created $settings, which is an admin_settingpage that we can add to. The file contains lots of lines that look a bit like:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
 $settings-&amp;gt;add(new admin_setting_configcheckbox(&#039;forum_replytouser&#039;, get_string(&#039;replytouser&#039;, &#039;forum&#039;),&lt;br /&gt;
                    get_string(&#039;replytouser_desc&#039;, &#039;forum&#039;), 1));&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
What this means is that to our settings page, we are adding a checkbox setting. To understand this in more detail, we need to know what arguments the constructor for an admin_setting takes. The definition of the constructor is:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
 function admin_setting($name, $visiblename, $description, $defaultsetting) {&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
So, $name here is &#039;forum_replytouser&#039;. This means that this setting is stored in the database in the row of the config table where name=&#039;forum_replytouser&#039;, and is accessible as $CFG-&amp;gt;forum_replytouser.&lt;br /&gt;
&lt;br /&gt;
$visiblename is get_string(&#039;replytouser&#039;, &#039;forum&#039;), this is the label that is put in front of setting on the admin screen.&lt;br /&gt;
&lt;br /&gt;
$description is get_string(&#039;replytouser_desc&#039;, &#039;forum&#039;), this is a short bit of text displayed underneath the setting to explain it further.&lt;br /&gt;
&lt;br /&gt;
$defaultsetting is the default value for this setting. This value is used when Moodle is installed. For simple settings like checkboxes and text fields, this is a simple value. For some more complicated settings, this is an array.&lt;br /&gt;
&lt;br /&gt;
Let as now look at a more complicated example, from mod/quiz/settingstree.php:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
 $quizsettings-&amp;gt;add(new admin_setting_text_with_advanced(&#039;quiz/timelimit&#039;,&lt;br /&gt;
         get_string(&#039;timelimit&#039;, &#039;quiz&#039;), get_string(&#039;timelimit_desc&#039;, &#039;quiz&#039;),&lt;br /&gt;
         array(&#039;value&#039; =&amp;gt; &#039;0&#039;, &#039;fix&#039; =&amp;gt; false), PARAM_INT));&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This shows two new things:&lt;br /&gt;
&lt;br /&gt;
$name here is &#039;quiz/timelimit&#039;. This is more complicated than a simple setting name. It means that this setting is stored in the config_plugins table, in the row where plugin=&#039;quiz&#039; and name=&#039;timelimit&#039;. It is not accessible through $CFG, to get it you can use get_config(&#039;quiz&#039;, &#039;timelimit&#039;). &#039;&#039;Note:&#039;&#039; the naming convention used here is slightly outdated; new activity modules should use &#039;mod_mymodule/setting&#039; instead of &#039;mymodule/setting&#039; as identifier.&lt;br /&gt;
&lt;br /&gt;
And this example shows a $defaultsetting that is an array.&lt;br /&gt;
&lt;br /&gt;
Normally, if you want a particular sort of setting, the easiest way is to look around the admin screens of your Moodle site, and find a setting like the one you want. Then go and copy the code and edit it. Therefore, we do not include a complete list of setting types here.&lt;br /&gt;
&lt;br /&gt;
== Locked and advanced settings for activity modules ==&lt;br /&gt;
Admin settings are often used to define the defaults for activity settings. There is a simple way to enable admins make activity settings as &amp;quot;locked&amp;quot; (cannot be changed from the default) or &amp;quot;advanced&amp;quot; (deprecated, used before the change to &amp;quot;short forms&amp;quot;).&lt;br /&gt;
&lt;br /&gt;
When creating the admin setting (e.g. in mod/assign/settings.php), create the setting like this:&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
   $name = new lang_string(&#039;teamsubmission&#039;, &#039;mod_assign&#039;);&lt;br /&gt;
    $description = new lang_string(&#039;teamsubmission_help&#039;, &#039;mod_assign&#039;);&lt;br /&gt;
    $setting = new admin_setting_configcheckbox(&#039;assign/teamsubmission&#039;,&lt;br /&gt;
                                                    $name,&lt;br /&gt;
                                                    $description,&lt;br /&gt;
                                                    0);&lt;br /&gt;
    $setting-&amp;gt;set_advanced(true);&lt;br /&gt;
    $setting-&amp;gt;set_lockable(true);&lt;br /&gt;
    $settings-&amp;gt;add($setting);&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
To add &amp;quot;locked&amp;quot; and &amp;quot;advanced&amp;quot; check boxes to the admin setting.&lt;br /&gt;
&lt;br /&gt;
And finally, when creating the activity form (e.g. in mod/assign/mod_form.php), call this:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;code php&amp;gt;&lt;br /&gt;
$this-&amp;gt;apply_admin_defaults();&lt;br /&gt;
&amp;lt;/code&amp;gt;&lt;br /&gt;
&lt;br /&gt;
at the end of the constructor to automatically set the default and lock the form element if required.&lt;br /&gt;
&lt;br /&gt;
Note: Locking an admin setting **will not force the value on existing settings*. Activity settings that are locked will need to be manually updated if they differ from the locked default value.&lt;br /&gt;
&lt;br /&gt;
==External pages==&lt;br /&gt;
&lt;br /&gt;
admin_externalpages represent screens of settings that do not fall into the standard pattern of admin_settings. The admin_externalpage object in the settings tree holds the URL of a PHP page that controls various settings.&lt;br /&gt;
&lt;br /&gt;
In that PHP page, near the start you need to call the function admin_externalpage_setup($pagename). Although earlier versions of Moodle required you to then use admin_externalpage_print_header() and admin_externalpage_print_footer() functions instead of the usual print_header and print_footer functions, this is no longer necessary as of Moodle 2.0 - just use $OUTPUT-&amp;gt;header() and $OUTPUT-&amp;gt;footer() as per usual (don&#039;t forget to echo them). This ensures that your page appears with the administration blocks and appropriate navigation.&lt;br /&gt;
&lt;br /&gt;
Note that if your external page relies on additional optional or required params, you may need to use the optional arguments to admin_externalpage_print_header to ensure that the Blocks editing on/off button works.&lt;br /&gt;
&lt;br /&gt;
Note that there are some subclasses of admin_externalpage, for example admin_page_managemods. In a lot of cases, these subclasses only exist to override the search method so this page can be found by appropriate searches.&lt;br /&gt;
&lt;br /&gt;
Once again, to understand this in more depth, your best approach is to look at how some of the external pages in Moodle work.&lt;br /&gt;
&lt;br /&gt;
==See also==&lt;br /&gt;
&lt;br /&gt;
* [[Modules|adding settings for activity modules]]&lt;br /&gt;
* [[Admin_reports#How_your_report_gets_included_in_the_admin_tree|adding admin reports to the tree]]&lt;br /&gt;
* [[Repository_plugins#APIs_for_Administration|configuration of repository plugins]]&lt;br /&gt;
* [[Filters#Adding_a_settings_screen|configuration for filter]]&lt;br /&gt;
* [[Developer_documentation|Other developer documentation]]&lt;/div&gt;</summary>
		<author><name>Mohessaid</name></author>
	</entry>
	<entry>
		<id>https://docs.moodle.org/dev/index.php?title=Upgrade_API&amp;diff=52609</id>
		<title>Upgrade API</title>
		<link rel="alternate" type="text/html" href="https://docs.moodle.org/dev/index.php?title=Upgrade_API&amp;diff=52609"/>
		<updated>2017-06-19T06:30:06Z</updated>

		<summary type="html">&lt;p&gt;Mohessaid: Correct a sentence &amp;quot;we will suppose you that you&amp;quot; --&amp;gt; &amp;quot;we will suppose that you&amp;quot;&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;The Upgrade API is how your module installs and upgrades itself, by keeping track of its own version.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Introduction==&lt;br /&gt;
By implementing this API in your plugin, Moodle will automatically create your database tables for you when you visit the Admin notifications page (.../admin/index.php). &lt;br /&gt;
&lt;br /&gt;
This process is controlled by three files within your plugin (there are other optional files you can use for various things. These are covered at the end of this document):&lt;br /&gt;
;[[version.php]] : This records the version of the plugin code (&#039;&#039;&#039;Please note:&#039;&#039;&#039; In Moodle installations below v2.0, this is not required for blocks, which use the version number returned by the block&#039;s init() method - see [[Blocks#Ready.2C_Set.2C_Go.21|the blocks development page]]). You must increase version in version.php after any change in /db/ folder, any change in javascript code, any new auto-loaded class, any new setting and also after any change in language pack because new version triggers upgrade upgrade procedure and resets all caches.&lt;br /&gt;
;db/install.xml : This is used when someone installs your plugin for the first time.&lt;br /&gt;
;db/upgrade.php : This is used when someone who had an older version of your plugin installed upgrades to the latest version.&lt;br /&gt;
&lt;br /&gt;
In addition, Moodle also stores in the database the currently installed version of each plugin.&lt;br /&gt;
&lt;br /&gt;
In Moodle 1.x, this is stored in the mdl_config table, in a row with the name &#039;&#039;plugintype&#039;&#039;_&#039;&#039;pluginname&#039;&#039;_version. For example qtype_myqtype_version. The exception to this rule are modules and blocks. Installed module version numbers are stored in the mdl_modules table. Block version numbers are in mdl_block.&lt;br /&gt;
&lt;br /&gt;
In Moodle 2.x, plugin version numbers are stored in the mdl_config_plugins table, with &#039;&#039;plugintype&#039;&#039;_&#039;&#039;pluginname&#039;&#039; in the plugin column, and &#039;version&#039; in the name column - with the same exception for modules and blocks.&lt;br /&gt;
&lt;br /&gt;
==A specific example==&lt;br /&gt;
&lt;br /&gt;
For the rest of this document, I will use a particular example, because it should make the explanation easier. You should be able to see how to generalise it.&lt;br /&gt;
&lt;br /&gt;
We will suppose that you are making a new question type myqtype. This is plugin type qtype, and the code will be in the question/type/myqtype folder. The currently installed version number will be stored in the (&#039;qtype_myqtype&#039;, &#039;version&#039;) row of the mdl_config_plugins table.&lt;br /&gt;
&lt;br /&gt;
In addition, we will just consider the first two releases of the plugin. The first release will have version number 2008080100, and will just use one database table mdl_myqtype_options, with two columns col1 and col2. Then we will suppose that the second release is 2008080200, and that requires an extra column, newcol, to be added to the mdl_myqtype_options table.&lt;br /&gt;
&lt;br /&gt;
==The files you need for the first release==&lt;br /&gt;
&lt;br /&gt;
In what follows, the bits of code you need to replace are &#039;&#039;&#039;in bold&#039;&#039;&#039;.&lt;br /&gt;
&lt;br /&gt;
;version.php&lt;br /&gt;
 $plugin-&amp;gt;version  = 2008080100; // Today&#039;s date in YYYYMMDD format, plus two additional digits&lt;br /&gt;
 $plugin-&amp;gt;requires = &#039;&#039;&#039;XXXXXXXXXX; // Moodle version - copy from $version in the top-level version.php file.&#039;&#039;&#039;&lt;br /&gt;
:Version numbers normally consist of the day&#039;s date in YYYYMMDD format, followed by two additional digits to allow for multiple versions in the same day, e.g. Sept 15, 2010 could have versions 2010091500, 2010091501, 2010091502, etc.&lt;br /&gt;
&lt;br /&gt;
;db/install.xml&lt;br /&gt;
:This file, which you should [[XMLDB editor|create with the XMLDB editor]], should contain the definition for your mdl_myqtype_options table, with the two columns col1 and col2.&lt;br /&gt;
&lt;br /&gt;
At this stage, you do not need a db/upgrade.php file.&lt;br /&gt;
&lt;br /&gt;
==The files you need for the second release==&lt;br /&gt;
&lt;br /&gt;
;version.php&lt;br /&gt;
 $plugin-&amp;gt;version  = 2008080200;&lt;br /&gt;
 $plugin-&amp;gt;requires = &#039;&#039;&#039;XXXXXXXXXX; // Copy the current value from the top-level version.php file.&#039;&#039;&#039;&lt;br /&gt;
;db/install.xml : This file should now contain the updated definition for your mdl_myqtype_options table, with three columns col1, col2 and newcol. You modify this file using the XMLDB editor.&lt;br /&gt;
;db/upgrade.php&lt;br /&gt;
:This file should contain the code that people need to run to upgrade from version 2008080100 of your plugin. That is, the code to add a column newcol to the mdl_myqtype_options table. You don&#039;t have to write this code yourself as the XMLDB editor will generate it for you. The upgrade.php file should contain a single function xmldb_qtype_myqtype_upgrade that looks a bit like:&lt;br /&gt;
 function xmldb_qtype_myqtype_upgrade($oldversion) {&lt;br /&gt;
     global $DB;&lt;br /&gt;
     $dbman = $DB-&amp;gt;get_manager();&lt;br /&gt;
 &lt;br /&gt;
     /// Add a new column newcol to the mdl_myqtype_options&lt;br /&gt;
     if ($oldversion &amp;lt; 2015031200) {&lt;br /&gt;
         &#039;&#039;&#039;// Code to add the column, generated by the &#039;View PHP Code&#039; option of the XMLDB editor.&#039;&#039;&#039;&lt;br /&gt;
     }&lt;br /&gt;
 &lt;br /&gt;
     return true;&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;Hint: If you are modifying or adding a field/table, get the XMLDB editor to generate the PHP update code for you &#039;&#039;&#039;after&#039;&#039;&#039; making the changes in the editor. If you are deleting one, you need to generate the PHP code &#039;&#039;&#039;before&#039;&#039;&#039; making the change - or you won&#039;t be able to select the field/table to write the code for, because it no longer exists.&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
==What happens when a user installs or upgrades your plugin==&lt;br /&gt;
&lt;br /&gt;
The process is triggered when an administrator goes to the Admin notifications page (.../admin/index.php). The code that does the work is the upgrade_plugins function in lib/adminlib.php and reading this code is the best way to find out exactly what happens. In pseudo-code, what it does is:&lt;br /&gt;
&lt;br /&gt;
 For each plugin of this type (e.g. all qtype plugins) {&lt;br /&gt;
     // For the body of this loop, suppose the current plugin being processed is myqtype.&lt;br /&gt;
 &lt;br /&gt;
     Check that question/type/myqtype/version.php, .../db/upgrade.php and .../db/install.xml exist.&lt;br /&gt;
 &lt;br /&gt;
     if (get_config(&#039;qtype_myqtype&#039;, &#039;version&#039;) exists, and is less than the number in version.php) {&lt;br /&gt;
         Call the upgrade function xmldb_qtype_myqtype_upgrade from upgrade.php,&lt;br /&gt;
                 passing the old version number that says what is currently installed&lt;br /&gt;
         set_config(&#039;version&#039;, &#039;&#039;latest number from version.php&#039;&#039;, &#039;qtype_myqtype&#039;)&lt;br /&gt;
                 to record what is currently installed&lt;br /&gt;
 &lt;br /&gt;
     } else if (get_config(&#039;qtype_myqtype&#039;, &#039;version&#039;) does not exist) {&lt;br /&gt;
         Create the tables from the definitions in install.xml&lt;br /&gt;
         set_config(&#039;version&#039;, &#039;&#039;latest number from version.php&#039;&#039;, &#039;qtype_myqtype&#039;)&lt;br /&gt;
                 to record what is currently installed&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Of course, it is a bit more complex that than. However, the code in the upgrade_plugins is quite clear, and I encourage you to go and have a look at it so you can see all the details of how it works.&lt;br /&gt;
&lt;br /&gt;
Let us now look at some worked examples:&lt;br /&gt;
&lt;br /&gt;
===User installs version 2008080100 of myqtype===&lt;br /&gt;
&lt;br /&gt;
To start with, the mdl_myqtype_options does not exist, and there will not be a (&#039;qtype_myqtype&#039;, &#039;version&#039;) row in the mdl_config_plugins table.&lt;br /&gt;
&lt;br /&gt;
# The user will unzip myqtype.zip into the question/type folder.&lt;br /&gt;
# The user will visit the Admin notifications page.&lt;br /&gt;
# This will trigger Moodle to search for plugings to upgrade. It will find that the code for the qtype_myqtype plugin is now present, but there is no trace of it in the database, so it will install the plugin from the install.xml file.&lt;br /&gt;
&lt;br /&gt;
At the end of this process, the mdl_myqtype_options table will exist with the two columns col1 and col2; and the (&#039;qtype_myqtype&#039;, &#039;version&#039;) row in the mdl_config_plugins table will contain 2008080100.&lt;br /&gt;
&lt;br /&gt;
===User upgrades from version 2008080100 to version 2008080200 of myqtype===&lt;br /&gt;
&lt;br /&gt;
To start with, the mdl_myqtype_options table will exist with the two columns col1 and col2; and the (&#039;qtype_myqtype&#039;, &#039;version&#039;) row in the mdl_config_plugins table will contain 2008080100.&lt;br /&gt;
&lt;br /&gt;
# The user will delete the old question/type/myqtype folder.&lt;br /&gt;
# The user will unzip the new myqtype.zip into the question/type folder.&lt;br /&gt;
# The user will visit the Admin notifications page.&lt;br /&gt;
# This will trigger Moodle to search for plugings to upgrade. It will find that the code for version 2008080200 the qtype_myqtype plugin is now present, but the installed version of the the database tables (&#039;qtype_myqtype&#039;, &#039;version&#039;) is 2008080100. Therefore, it will call xmldb_qtype_myqtype_upgrade from upgrade.php, passing 2008080100 as the $oldversion argument.&lt;br /&gt;
&lt;br /&gt;
At the end of this process, the mdl_myqtype_options table will now have three columns col1, col2 and newcol; and the (&#039;qtype_myqtype&#039;, &#039;version&#039;) row in the mdl_config_plugins table will contain 2008080200.&lt;br /&gt;
&lt;br /&gt;
===User installs version 2008080200 of myqtype into a clean Moodle install===&lt;br /&gt;
&lt;br /&gt;
To start with, the mdl_myqtype_options does not exist, and there will not be a (&#039;qtype_myqtype&#039;, &#039;version&#039;) row in the mdl_config_plugins table.&lt;br /&gt;
&lt;br /&gt;
# The user will unzip the 2008080200 version of myqtype.zip into the question/type folder.&lt;br /&gt;
# The user will visit the Admin notifications page.&lt;br /&gt;
# This will trigger Moodle to search for plugings to upgrade. It will find that the code for the qtype_myqtype plugin is now present, but there is no trace of it in the database, so it will install the plugin from the install.xml file.&lt;br /&gt;
&lt;br /&gt;
At the end of this process, the mdl_myqtype_options table will exist with three columns col1, col2 and newcol; and the (&#039;qtype_myqtype&#039;, &#039;version&#039;) row in the mdl_config_plugins table will contain 2008080200.&lt;br /&gt;
&lt;br /&gt;
== Upgrade code restrictions ==&lt;br /&gt;
&lt;br /&gt;
Within an upgrade, there are restrictions on the functions your code should call, because the system has not been fully updated.&lt;br /&gt;
&lt;br /&gt;
* All upgrade code can use the basic database API ($DB-&amp;gt;... functions).&lt;br /&gt;
* In a &#039;&#039;&#039;plugin&#039;&#039;&#039;, upgrade code should not call &#039;&#039;&#039;any plugin functions&#039;&#039;&#039;. (For example, if your plugin has a function that changes frog settings to &#039;green&#039;, and you need to do this during upgrade, then you should not call this function; instead, manually update the database rows so that the frog settings become green.) However, &#039;&#039;&#039;you should call core functions&#039;&#039;&#039; rather than making core changes in database.&lt;br /&gt;
* In &#039;&#039;&#039;core&#039;&#039;&#039;, upgrade code should not even call &#039;&#039;&#039;any core functions&#039;&#039;&#039; (For example, if you need to add a calendar event, this should be done by inserting into a database table rather than calling a function to add the event.) Certain functions marked with a comment such as set_config and get_config are excepted.&lt;br /&gt;
&lt;br /&gt;
The reason for this is the state of the system during upgrade.&lt;br /&gt;
&lt;br /&gt;
During core upgrade the state is as follows:&lt;br /&gt;
&lt;br /&gt;
* Core data: &#039;&#039;&#039;Old&#039;&#039;&#039;. &lt;br /&gt;
* Plugin data: &#039;&#039;&#039;Old&#039;&#039;&#039;.&lt;br /&gt;
&lt;br /&gt;
Core functions expect core data to be in the Current state, so it is not safe to call them, unless the following is present in the function&#039;s docblock: &amp;quot;NOTE: this function is called from lib/db/upgrade.php&amp;quot;.&lt;br /&gt;
&lt;br /&gt;
During plugin upgrade the state is as follows:&lt;br /&gt;
&lt;br /&gt;
* Core data: &#039;&#039;&#039;Current&#039;&#039;&#039;. (Because core upgrade runs before plugin upgrade.)&lt;br /&gt;
* Plugin data: &#039;&#039;&#039;Old&#039;&#039;&#039;.&lt;br /&gt;
&lt;br /&gt;
Core functions are now safe to call because the core data is in Current state. But plugin functions, which expect data to be in the Current state, are not safe.&lt;br /&gt;
&lt;br /&gt;
==Summary==&lt;br /&gt;
&lt;br /&gt;
The first time a user installs any version of your plugin, the install.xml file will be used to create all the required database tables. Therefore install.xml should always contain the definition of the up-to-date database structure. Moodle recognises this situation because there is a version.php file on disc, but there is no (&#039;&#039;plugintype&#039;&#039;_&#039;&#039;pluginname&#039;&#039;, version) value in the mdl_config_plugins table.&lt;br /&gt;
&lt;br /&gt;
If the user already had a version of your plugin installed, and then upgrades to a newer version, Moodle will detect this because the version.php file will contain a newer version number than the (&#039;&#039;plugintype&#039;&#039;_&#039;&#039;pluginname&#039;&#039;, version) value in the mdl_config_plugins table. In this case, Moodle will run the code in the upgrade.php file, passing in the old version number, so that the correct bits of upgrade can be run, as controlled by the if ($oldversion &amp;lt; XXXXXXXXXX) blocks of code.&lt;br /&gt;
&lt;br /&gt;
The contents of the install.xml and upgrade.php files should be generated using the XMLDB editor.&lt;br /&gt;
&lt;br /&gt;
==Other things that can be in the db folder==&lt;br /&gt;
&lt;br /&gt;
Of these, only install.php relates to creating the necessary database structure. The other files are mainly about providing the other meta-data that is required when the plugin is installed. I have tried to link to other documentation that goes into detail where possible.&lt;br /&gt;
&lt;br /&gt;
===install.php===&lt;br /&gt;
&lt;br /&gt;
(Moodle 2.0 and later)&lt;br /&gt;
&lt;br /&gt;
If you define a function like xmldb_qtype_myqtype_install(), this PHP code will be executed when your plugin is installed. This is an opportunity to do things that you cannot do with install.xml. It&#039;s executed immediately after the DB schema associated with the component (install.xml) is created.&lt;br /&gt;
&lt;br /&gt;
(Moodle 1.9)&lt;br /&gt;
&lt;br /&gt;
An install function can be defined in lib.php in the root directory of your module. The install function must have the name qtype_install() and takes no arguments (n.b. this is called from lib/adminlib.php after install.xml is parsed)&lt;br /&gt;
&lt;br /&gt;
===uninstall.php===&lt;br /&gt;
&lt;br /&gt;
(Moodle 2.0 and later)&lt;br /&gt;
&lt;br /&gt;
Balancing the previous feature, it&#039;s also possible to define one function like xmldb_qtype_myqtype_uninstall(), that will be executed when your plugin is uninstalled, before dropping its DB schema.&lt;br /&gt;
&lt;br /&gt;
===access.php===&lt;br /&gt;
&lt;br /&gt;
(Moodle 1.7 and later)&lt;br /&gt;
&lt;br /&gt;
Use to define the [[Roles#Capabilities|capabilities]] that this plugin handles with the [[Access API]]. You must increase version in version.php after adding new capabilities.&lt;br /&gt;
&lt;br /&gt;
===events.php===&lt;br /&gt;
&lt;br /&gt;
(Moodle 1.9(?) and later)&lt;br /&gt;
&lt;br /&gt;
Used to define the events this plugin sends to the [[Events_API|Events API]]. You must increase version in version.php after modifying or adding new events.&lt;br /&gt;
&lt;br /&gt;
===log.php===&lt;br /&gt;
&lt;br /&gt;
(Moodle 2.0 and later)&lt;br /&gt;
&lt;br /&gt;
Used to describe the type of log entries that this plugin creates. See the [[Logging API#Mod/*/db/log.php Files| log.php section]] of the [[Logging API]] for more information. You must increase version in version.php after any change.&lt;br /&gt;
&lt;br /&gt;
===messages.php===&lt;br /&gt;
&lt;br /&gt;
(Moodle 2.0 and later)&lt;br /&gt;
&lt;br /&gt;
Used to define the messages this plugin sends through the [[Message API|Messaging API]]. You must increase version in version.php after any change.&lt;br /&gt;
&lt;br /&gt;
===services.php===&lt;br /&gt;
&lt;br /&gt;
(Moodle 2.0 and later)&lt;br /&gt;
&lt;br /&gt;
Used to define the functions and services this plugin publishes through the [[Web services API]]. Usually all those functions are part of the [[External functions API]]. You must increase version in version.php after any change.&lt;br /&gt;
&lt;br /&gt;
===upgradelib.php===&lt;br /&gt;
&lt;br /&gt;
Optional file where upgrade code can be grouped under some &#039;&#039;&#039;helper functions&#039;&#039;&#039; to be used in the upgrade.php file. If needed, this file must be &#039;&#039;&#039;manually required&#039;&#039;&#039; once from upgrade.php. Its main goal is to keep the upgrade.php scripts reduced and clear (this cannot contain any function themselves apart from the xmldb_xxx_upgrade() one).&lt;br /&gt;
&lt;br /&gt;
It&#039;s &#039;&#039;&#039;important&#039;&#039;&#039; to note that the upgradelib.php files should always be performing any task using raw - low level - database access exclusively, &#039;&#039;&#039;avoiding any use of the Moodle APIs&#039;&#039;&#039;.&lt;br /&gt;
&lt;br /&gt;
===mod/.../db/subplugins.php===&lt;br /&gt;
&lt;br /&gt;
(Moodle 2.0 and later)&lt;br /&gt;
&lt;br /&gt;
This only applies to activity modules, not other types of plugin. It is a way to allow an activity module to have its own sorts of plugins. For example workshop allocation schemes, or quiz reports.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==Language packs==&lt;br /&gt;
&lt;br /&gt;
Do not forget to increase version number after modifying lang/en/type_yourplugin.php language file. See [[Languages/AMOS]] section AMOS script for more information.&lt;br /&gt;
&lt;br /&gt;
==Upgrade API Cheatsheet==&lt;br /&gt;
&lt;br /&gt;
The Upgrade API is &#039;&#039;&#039;related with a lot&#039;&#039;&#039; of different files and APIs (access, event, log, webservice...) as far as it&#039;s the API used to install/upgrade all those artifacts. The previous sections have tried to list all those dependencies when possible. &lt;br /&gt;
&lt;br /&gt;
Also, the Upgrade API &#039;&#039;&#039;does a very intensive use&#039;&#039;&#039; of other APIs ([[Data definition API|ddl]], [[Data manipulation API|dml]]) and tools (the XMLDB editor...) in order to proceed with the modifications of the Moodle system.&lt;br /&gt;
&lt;br /&gt;
Once stated the above, we could summarise the API as the &#039;&#039;&#039;collection of a few files and functions&#039;&#039;&#039;, here they are:&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;The files&#039;&#039;&#039;: For each component we can have, under its &amp;quot;db&amp;quot; directory.&lt;br /&gt;
* &#039;&#039;&#039;version.php&#039;&#039;&#039;: Where the $version is specified and, if bumped, the upgrade machinery will be launched and all caches reset. Bump up version after changing /db/, /lang/, theme or JavaScript.&lt;br /&gt;
* &#039;&#039;&#039;install.xml&#039;&#039;&#039;: XMLDB definition of the DB schema. generated with the XMLDB Editor.&lt;br /&gt;
* &#039;&#039;&#039;install.php&#039;&#039;&#039;: Post-install file executed once the schema has been created.&lt;br /&gt;
* &#039;&#039;&#039;uninstall.php&#039;&#039;&#039;: Pre-uninstall file executed before the schema is dropped.&lt;br /&gt;
* &#039;&#039;&#039;upgrade.php&#039;&#039;&#039;: Ordered list of upgrade steps, each one performing a well-defined task. &lt;br /&gt;
* &#039;&#039;&#039;upgradelib.php&#039;&#039;&#039;: Library files composed of helper functions to be used by upgrade.php.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;The functions&#039;&#039;&#039;: With different names for different components, but available to all them:&lt;br /&gt;
* &#039;&#039;&#039;xmldb_[main|[[Frankenstyle|frankenstyle]]]_install()&#039;&#039;&#039;: to be used in install.php files.&lt;br /&gt;
* &#039;&#039;&#039;xmldb_[main|frankenstyle]_uninstall()&#039;&#039;&#039;: to be used in uninstall.php files.&lt;br /&gt;
* &#039;&#039;&#039;xmldb_[main|frankenstyle]_upgrade()&#039;&#039;&#039;: to be used in upgrade.php files.&lt;br /&gt;
* &#039;&#039;&#039;upgrade_set_timeout()&#039;&#039;&#039;: to be used within the upgrade steps in upgrade.php files, in order to grant more time to the step.&lt;br /&gt;
* &#039;&#039;&#039;upgrade_[main|mod|block|plugin]_savepoint()&#039;&#039;&#039;: to consider one upgrade step completed and reset timeouts. Avoids double executions.&lt;br /&gt;
&lt;br /&gt;
Of course, for practical examples of the use of this API it&#039;s &#039;&#039;&#039;highly recommended to examine and understand current code&#039;&#039;&#039;. Everything is out there.&lt;br /&gt;
&lt;br /&gt;
==Database upgrades and stable branches==&lt;br /&gt;
&lt;br /&gt;
The simple rule is, never make any database changes on a stable branch. You only need to read this section in the rare situations where a database change on the stable branch is unavoidable.&lt;br /&gt;
&lt;br /&gt;
&#039;&#039;&#039;Warning!!! advanced material follows.&#039;&#039;&#039;&lt;br /&gt;
&lt;br /&gt;
Suppose, in order to fix a bug, you need to make a database change in Moodle 1.9.3+ (which must also be merged into HEAD). The root of the problem is that people may upgrade their Moodle in three different ways, which &lt;br /&gt;
&lt;br /&gt;
* Upgrade from &amp;lt;=1.9.3 to 1.9.4 - this executes the ugprade script on the 1.9 branch.&lt;br /&gt;
* Upgrade from &amp;lt;=1.9.3 directly to &amp;gt;=2.0 - this executes the upgrade script on the HEAD branch.&lt;br /&gt;
* Upgrade from 1.9.4 to &amp;gt;=2.0 - in this case, you must ensure that the upgrade on HEAD is not executed.&lt;br /&gt;
&lt;br /&gt;
The normal way to do this is ensure that your database upgrade is idempotent. That is, it does not matter if you do it twice. So for example, instead of doing&lt;br /&gt;
&lt;br /&gt;
        $dbman-&amp;gt;create_table($table);&lt;br /&gt;
&lt;br /&gt;
you should do&lt;br /&gt;
&lt;br /&gt;
        if (!$dbman-&amp;gt;table_exists($table)) {&lt;br /&gt;
            $dbman-&amp;gt;create_table($table);&lt;br /&gt;
        }&lt;br /&gt;
&lt;br /&gt;
You should also think about what version numbers to put in your version.php file on each branch. Above all, test carefully.&lt;br /&gt;
&lt;br /&gt;
==See also==&lt;br /&gt;
&lt;br /&gt;
* [[Core APIs]]&lt;br /&gt;
* [[XMLDB_Documentation|XMLDB_Documentation]]&lt;br /&gt;
* [[Coding|Coding guidelines]]&lt;br /&gt;
* [[DDL functions|DDL functions]]&lt;br /&gt;
* [[XMLDB defining an XML structure|install.xml file documentation]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Category:XMLDB]]&lt;br /&gt;
[[Category:Plugins]]&lt;br /&gt;
[[Category:API]]&lt;br /&gt;
&lt;br /&gt;
[[es: API de Actualización]]&lt;/div&gt;</summary>
		<author><name>Mohessaid</name></author>
	</entry>
</feed>