Note:

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

Creating a theme settings page: Difference between revisions

From MoodleDocs
Line 609: Line 609:
The screenshot below shows you what you should see at this point:
The screenshot below shows you what you should see at this point:


[[Image:Theme.settings.page.03.png|715px|thumb|left|The settings page we just created]]<br style="clear:right;>
[[Image:Theme.settings.page.03.png|715px|thumb|left|The settings page we just created]]<br style="clear:left;>


==Using the settings in CSS==
==Using the settings in CSS==

Revision as of 05:07, 10 June 2010

Under construction. Please don't make any changes at this point I will remove this notice when I am done --Sam Hemelryk

This document looks at how to create and settings page for your theme and how to make use of those settings both within your CSS and within your layout files.

This is a pretty advanced topic and will require that you have at least an intermediate knowledge of PHP, CSS, and development in general.

Our end goal. The settings page.

Before we begin

There is a huge body of knowledge that we must cover in following through this document and as such I think the best way to write this is as a tutorial for which my intentions are to replicate the standard theme but with a settings page that allows the admin to set background and font colours, set a logo to use with the page, and probably several other minor settings to change the way in which the theme is displayed.

As part of this process I will of course have to create the base of my new theme which will be largely a copy/paste of the current standard theme. I expect that anyone working through this tutorial has previously read the tutorial I wrote on creating your first theme. If you haven't go read it now because I'm not going to go into much detail until we get to the actual process of customising the theme and introducing the settings page.

So before we finally get this started please work check that you can tick of the everything on the following requirements check-list.

  • Have a Moodle installation that has already been installed and configured and is ready to use
  • Have full read/write access to that installation.
  • Be prepared to delete that installation at the end of this... we will destroy it!
  • Have a development environment prepared and ready to use. This includes:
    • Your favourite editor installed, running, and pointed at the themes directory of your installation.
    • You browser open and your site visible.
    • A bottomless coffee pot... decaf won't help you with this one.
  • Have turned on theme designer mode, if you don't know what this is please read the creating your first theme tutorial.
  • Have turned on allowthemechangeonurl. This setting allows you to change themes on the URL and is very handy when developing themes.
  • And finally an insane ambition to create a customisable theme.

Our goals for this tutorial

The following is just a list goals that I hope to achieve during this tutorial. They are laid out here so that I can easily refer back to them and so that you can easily find them.

  1. Create a new theme called demystified based on the standard theme within Moodle 2.0 but defines it own layout files.
  2. Make some minor changes to that theme to allow us to more easily see what is going on.
  3. Create a settings page for the demystified theme
  4. Add several settings to our settings page
  5. Use some of those settings to alter our CSS
  6. Use the rest of those settings within our layout file.
  7. Discuss the good, the bad, and limits of what we have just created.

So I can see you are all very excited about this point and that you would love to know what settings we are going to create; So here they are:

A setting to ...

  • change the background colour (CSS).
  • set the path to an image that we will use as a logo on all pages (Layout files).
  • override the width of the block regions (CSS).
  • allow a note to be added to the footer of all pages (Layout files).
  • allow custom CSS to be written to do anything the user wants.

Creating the demystified theme

Before we start here I want to remind you that I am going to look at this only briefly as I am making the assumption that you have read the creating your first theme tutorial.

Well lets get into it....

The first thing we need to do is create a directory for our theme which we will call demystified.

So within your Moodle directory create the following folder moodle/theme/demystified. At the same time you can also create the following files and folders which we will get to soon.

  • The file moodle/theme/demystified/config.php for our config information.
  • The directory moodle/theme/demystified/layout for our layout files.
  • The directory moodle/theme/demystified/style for our css files.
  • The file moodle/theme/demystified/style/core.css which will contain our special CSS.

Next we will copy the layout files from the base theme to our new theme demystified. We are basing our theme on the base theme however because we want to make changes to our layout files we will need to create out own. In this case coping them from the base them is fine... so copy all of the layout files from moodle/theme/base/layout to moodle/theme/demystified/layout.

There should be three files that you just copied:

  1. embedded.php
  2. frontpage.php
  3. general.php

Now we need to populate demystified/config.php with the settings for our new theme. They are as follows: $THEME->name = 'demystified'; Simply sets the name of our theme.

$THEME->parents = array('standard','base'); This theme is extending both the standard theme and the base theme. Remember when extending a theme you also need to extend its parents or things might not work correctly.

$THEME->sheets = array('core'); This tells our theme that we want to use the file demystified/style/core.css with this theme.

$THEME->layouts = array(

   // Most backwards compatible layout without the blocks - this is the layout used by default
   'base' => array(
       'file' => 'general.php',
       'regions' => array(),
   ),
   // Standard layout with blocks, this is recommended for most pages with general information
   'standard' => array(
       'file' => 'general.php',
       'regions' => array('side-pre', 'side-post'),
       'defaultregion' => 'side-post',
   ),
   // Main course page
   'course' => array(
       'file' => 'general.php',
       'regions' => array('side-pre', 'side-post'),
       'defaultregion' => 'side-post',
       'options' => array('langmenu'=>true),
   ),
   'coursecategory' => array(
       'file' => 'general.php',
       'regions' => array('side-pre', 'side-post'),
       'defaultregion' => 'side-post',
   ),
   // part of course, typical for modules - default page layout if $cm specified in require_login()
   'incourse' => array(
       'file' => 'general.php',
       'regions' => array('side-pre', 'side-post'),
       'defaultregion' => 'side-post',
   ),
   // The site home page.
   'frontpage' => array(
       'file' => 'frontpage.php',
       'regions' => array('side-pre', 'side-post'),
       'defaultregion' => 'side-post',
   ),
   // Server administration scripts.
   'admin' => array(
       'file' => 'general.php',
       'regions' => array('side-pre'),
       'defaultregion' => 'side-pre',
   ),
   // My dashboard page
   'mydashboard' => array(
       'file' => 'general.php',
       'regions' => array('side-pre', 'side-post'),
       'defaultregion' => 'side-post',
       'options' => array('langmenu'=>true),
   ),
   // My public page
   'mypublic' => array(
       'file' => 'general.php',
       'regions' => array('side-pre', 'side-post'),
       'defaultregion' => 'side-post',
   ),
   'login' => array(
       'file' => 'general.php',
       'regions' => array(),
       'options' => array('langmenu'=>true),
   ),
   // Pages that appear in pop-up windows - no navigation, no blocks, no header.
   'popup' => array(
       'file' => 'general.php',
       'regions' => array(),
       'options' => array('nofooter'=>true, 'nonavbar'=>true, 'nocustommenu'=>true),
   ),
   // No blocks and minimal footer - used for legacy frame layouts only!
   'frametop' => array(
       'file' => 'general.php',
       'regions' => array(),
       'options' => array('nofooter'=>true),
   ),
   // Embeded pages, like iframe/object embeded in moodleform - it needs as much space as possible
   'embedded' => array(
       'file' => 'embedded.php',
       'regions' => array(),
       'options' => array('nofooter'=>true, 'nonavbar'=>true, 'nocustommenu'=>true),
   ),
   // Used during upgrade and install, and for the 'This site is undergoing maintenance' message.
   // This must not have any blocks, and it is good idea if it does not have links to
   // other places - for example there should not be a home link in the footer...
   'maintenance' => array(
       'file' => 'general.php',
       'regions' => array(),
       'options' => array('noblocks'=>true, 'nofooter'=>true, 'nonavbar'=>true, 'nocustommenu'=>true),
   ),

);

Now that all looks very complicated however its really not too bad as it is just copied from the base theme's config.php file. We can do this because we copied the layout files from the base theme to begin with and for the time being there are no changes that we wish to make. Simply open up theme/base/config.php and copy the layouts from there.

And that is it. The config.php file for our demystified theme is complete. The full source is shown below:

<?php

// This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>.

/**

* The demystified theme config file
*
* This theme was created to document the process of adding a settings page to a theme
*
* @copyright 2010 Sam Hemelryk
* @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/

// The name of our theme $THEME->name = 'demystified';

// The other themes this theme extends $THEME->parents = array('standard','base');

// The CSS files this theme uses (located in the style directory) $THEME->sheets = array('core');

// The layout definitions for this theme $THEME->layouts = array(

   // Most backwards compatible layout without the blocks - this is the layout used by default
   'base' => array(
       'file' => 'general.php',
       'regions' => array(),
   ),
   // Standard layout with blocks, this is recommended for most pages with general information
   'standard' => array(
       'file' => 'general.php',
       'regions' => array('side-pre', 'side-post'),
       'defaultregion' => 'side-post',
   ),
   // Main course page
   'course' => array(
       'file' => 'general.php',
       'regions' => array('side-pre', 'side-post'),
       'defaultregion' => 'side-post',
       'options' => array('langmenu'=>true),
   ),
   'coursecategory' => array(
       'file' => 'general.php',
       'regions' => array('side-pre', 'side-post'),
       'defaultregion' => 'side-post',
   ),
   // part of course, typical for modules - default page layout if $cm specified in require_login()
   'incourse' => array(
       'file' => 'general.php',
       'regions' => array('side-pre', 'side-post'),
       'defaultregion' => 'side-post',
   ),
   // The site home page.
   'frontpage' => array(
       'file' => 'frontpage.php',
       'regions' => array('side-pre', 'side-post'),
       'defaultregion' => 'side-post',
   ),
   // Server administration scripts.
   'admin' => array(
       'file' => 'general.php',
       'regions' => array('side-pre'),
       'defaultregion' => 'side-pre',
   ),
   // My dashboard page
   'mydashboard' => array(
       'file' => 'general.php',
       'regions' => array('side-pre', 'side-post'),
       'defaultregion' => 'side-post',
       'options' => array('langmenu'=>true),
   ),
   // My public page
   'mypublic' => array(
       'file' => 'general.php',
       'regions' => array('side-pre', 'side-post'),
       'defaultregion' => 'side-post',
   ),
   'login' => array(
       'file' => 'general.php',
       'regions' => array(),
       'options' => array('langmenu'=>true),
   ),
   // Pages that appear in pop-up windows - no navigation, no blocks, no header.
   'popup' => array(
       'file' => 'general.php',
       'regions' => array(),
       'options' => array('nofooter'=>true, 'nonavbar'=>true, 'nocustommenu'=>true),
   ),
   // No blocks and minimal footer - used for legacy frame layouts only!
   'frametop' => array(
       'file' => 'general.php',
       'regions' => array(),
       'options' => array('nofooter'=>true),
   ),
   // Embeded pages, like iframe/object embeded in moodleform - it needs as much space as possible
   'embedded' => array(
       'file' => 'embedded.php',
       'regions' => array(),
       'options' => array('nofooter'=>true, 'nonavbar'=>true, 'nocustommenu'=>true),
   ),
   // Used during upgrade and install, and for the 'This site is undergoing maintenance' message.
   // This must not have any blocks, and it is good idea if it does not have links to
   // other places - for example there should not be a home link in the footer...
   'maintenance' => array(
       'file' => 'general.php',
       'regions' => array(),
       'options' => array('noblocks'=>true, 'nofooter'=>true, 'nonavbar'=>true, 'nocustommenu'=>true),
   ),

);

The screenshot below shows the both the directory structure we have now created and a screenshot of the theme presently.

Theme.settings.page.01.png

To view the theme so far open you browser and enter the URL of your site followed by '?theme=demystified'. You should see the theme that we just created which will look exactly like the base standard theme.

The final thing that we want to do is add a little bit of CSS to the demystified theme that will both visually set this theme apart from the standard theme and second build a the base on which our settings can later build.

I added the following snippet of CSS to the file demystified/style/core.css. html {background-color:#DDD;} body {margin:30px;padding:0;border:1px solid #333;border-width:0 10px 0 10px;background-color:#333;} body #page {background-color:#FFF;position:relative;top:-10px;} .block .header {background-image:none;background-color:#0C5CAC;border:1px solid #0C5CAC;color:#FFF;} .block {border-color:#4BA7FF;background-color:#DDEEFF;} .block .content {background-color:#F1F8FF;} a:link, a:visited {color:#0C5CAC;} a:hover {color:#C77500;}

  1. page #page-header {background-color:#0C5CAC;margin:0;padding:0;width:100%;color:#fff;}
  2. page #page-header a:link, #page #page-header a:visited {color:#FFAC02}
  3. page #page-header .navbar, #page #page-header .navbar a:link, #page #page-header .navbar a:visited {color:#0C5CAC;}

The CSS that we have just added to our theme sets a couple of colours on the front page. Presently this is the only CSS I will add, I know it isn't complete by any means but it achieves it's purpose as the screenshot below illustrates.

The newly styles demystified theme

And with that I will move on to the real purpose of this tutorial, creating the settings page

Setting up the settings page

With the demystified theme set up in its early stage it is time to create the settings page. This is where the real PHP fun begins.

For those of you who happen to be familiar with development of modules, blocks or other plugin types you have probably encountered settings pages before and this is not going to be any different.

However for those who haven't which I imagine is most of you this is going to be quite a challenge. I will try to walk through this step by step however if at any point you get stuck don't hesitate to ask in the forums as I imagine you will get a speedy response.

How settings pages work in Moodle

Settings pages can be used by nearly every plugin type of which themes is of course one. The way in which it all works isn't too tricky to understand.

All of the settings for Moodle can be configured through the admin interfaces when logged in. I am sure that everyone here has seen those admin pages and has changed a setting or two before so you will all know what I am talking about. Well the settings page for theme is no different. It will be shown in the admin pages tree under Appearance > Themes and all we have to do is tell Moodle what settings there are.

This is done by creating a settings.php file within out theme into which we will add code that tells Moodle about the settings we want to add/use.

When telling Moodle about each setting we are simply creating a new admin_setting instance of the type we want and the properties we want and then adding it to our settings page.

There is really not much more too it at this level. Things can get very complex very fast so the best thing we can do now is start creating our settings.php file for the demystified theme and see where it leads us.

Creating the settings page

So as mentioned before we need a settings.php file which we will create now. To begin with create the file theme/demystified/settings.php and open it in your favourite editor so its ready to go.

Before we start adding code lets just remember the settings that we want to create:

  • change the background colour (CSS).
  • set the path to an image that we will use as a logo on all pages (Layout files).
  • override the width of the block regions (CSS).
  • allow a note to be added to the footer of all pages (Layout files).
  • allow custom CSS to be written to do anything the user wants.

Alright.

Now thinking about this the first setting is as basic as it gets, all we need is a text box that the user can type an image into.

The second is to allow a logo to be used in the header of each page. What we want here is a path but should it be a physical path e.g. C:/path/to/image.png or should it be a web path e.g. http://mysite.com/path/to/image.png? For the purpose of this tutorial I am going to go with a web path because it is going to be easier to code and will hopefully be a little easier to understand to begin with.

The third settings is very straight forward, we will just have a plain text box into which a width can be typed that will be used to determine the width of the block regions.

The forth and the fifth settings are also pretty straight forward, they we use a textarea into which the user can enter what ever they want and we will do something useful with it.

Now that we have an understanding about the settings we wish to define pull up your editor and lets start coding....

<?php

/**

* Settings for the demystified theme
*/

$temp = new admin_settingpage('theme_demystified', get_string('configtitle','theme_demystified')); This is the first bit of code we must enter, the first line is of course just the opening php tag, secondly we have a comment that describes this file, and then we get create a new admin_settingspage object.

This admin_settingspage object that we have just created is a representation of our settings page and is the what we add our new settings to. When creating it we give it two arguments, first the name of the page which is in this case theme_themename and the title for the page which we get with the get_string method.

At the moment I'm not going to worry about adding the string, we will get to that latter once we have defined all of our settings.

Background colour

With the page now created as $temp lets add our first setting: Background colour.

// Background colour setting $name = 'theme_demystified/backgroundcolor'; $title = get_string('backgroundcolor','theme_demystified'); $description = get_string('backgroundcolordesc', 'theme_demystified'); $default = '#DDD'; $setting = new admin_setting_configtext($name, $title, $description, $default, PARAM_CLEAN, 12); $temp->add($setting); Thankfully this isn't as difficult as it probably initially looks.

The first line of code is creating a variable for the name of the background colour setting. In this case it is theme_demystified/backgroundcolor.

The name is very important, for the setting to be usable we have to follow a strict naming convention. theme_themename/settingname where themename is the name of the theme the setting is for and settingname is the name for the setting by which we will also use it.

The second line of code creates a variable that contains the title of the setting. This is what the user sees to the right of the setting on the settings page and should be a short description of the setting. Here we are again using the get_string method so we will need to remember to add that string later on.

The third line of code sets the description. This should describe what the setting does or how it works and again we will use the get_string method.

The fourth line creates a variable that will be used as the default value for the setting. Because this setting is a colour we want an HTML colour to be the default value.

The fifth line is where we put it all together. Here we create a new admin_setting_configtext object. This object will represent the background colour setting.

When we create it we need to give it 6 different things.

  1. The name of the setting. In this case we have a variable $name.
  2. The title for this setting. We used the variable $title.
  3. The description of the setting $description.
  4. The default value for the setting. $default is the variable this.
  5. The type of value we want the user to enter. For this we have used PARAM_CLEAN which tells Moodle to get rid of any nasties from what the user enters.
  6. The size of the field. In our case 12 characters will be plenty.

The sixth and final line of code adds our newly created setting to the admin page we created earlier.

That is it we have successfully created and added our first setting, however there are several more to settings to do, and three are a couple of important things that you need to be aware of before we move on.

First: There are several different types of settings that you can create and add to a page and each one may differ in what they need you to give them. In this case it was name, title, description, default, type, and size. However other settings will likely require different things. Smart editors like Netbeans or Eclipse can tell you what is required, otherwise you will need to research it.

Second: Normally settings are declared on one line as follows: $temp->add(new admin_setting_configtext('theme_demystified/backgroundcolor', get_string('backgroundcolor','theme_demystified'), get_string('backgroundcolordesc', 'theme_demystified'), '#DDD', PARAM_CLEAN, 12)); While this is structurally identical as all we have done is move everything onto one line and do away with the variables it is a little harder to read when you are learning all of this.

The logo file

Time to create the second setting that will allow the user to enter a URL to an image they wish to use as the logo on their site. // Logo file setting $name = 'theme_demystified/logo'; $title = get_string('logo','theme_demystified'); $description = get_string('logodesc', 'theme_demystified'); $setting = new admin_setting_configtext($name, $title, $description, , PARAM_URL); $temp->add($setting); The first thing that you will notice about this setting that it is very similar to the first setting to set the background colour, infact all we have changed is the name, title, description, and default value. We have however changed the value type from PARAM_CLEAN to PARAM_URL, this makes sure the user enters a URL. You will also notice that for this one we don't set a size for the field as we have no idea how long the URL will be.

Block region width

The third setting should allow the user to set set a width for the block regions that will be used as columns. (We could have called it column width I suppose)

For this setting I want to do something a little different from the previous two, here I want to use a select box so that the user selects a width for the column from a list I provide. // Block region width $name = 'theme_demystified/regionwidth'; $title = get_string('regionwidth','theme_demystified'); $description = get_string('regionwidthdesc', 'theme_demystified'); $default = 200; $choices = array(150=>'150px', 170=>'170px', 200=>'200px', 240=>'240px', 290=>'290px', 350=>'350px', 420=>'420px'); $setting = new admin_setting_configselect($name, $title, $description, $default, $choices); $temp->add($setting); So looking at the code: The four three lines you will recognise. $name, $title, $description, and $default are all being set.

The fifth line of code however introduces something new. Of course in order to have a select box we have to have options, in this case we have an array of options stored in the variable $choices.

The lines after should look familiar again, the only difference being that instead of a admin_setting_configtext setting we have created a admin_setting_configselect for which we must give the choice for the select box as the fifth argument.

Woohoo, we've just created our first select box setting.

Foot note

Now to create the foot note setting. Here we want the user to be able to enter some arbitrary text that will be used in the footer of the page. For this I want the user to be able to enter some HTML so I will create an editor setting. // Foot note setting $name = 'theme_demystified/footnote'; $title = get_string('footnote','theme_demystified'); $description = get_string('footnotedesc', 'theme_demystified'); $setting = new admin_setting_confightmleditor($name, $title, $description, ); $temp->add($setting); How simple is that!

It is just about identical to the first two settings except that for this we have created a admin_setting_confightmleditor setting rather than a text setting.

Note: You can also set the columns and rows for the editor setting using the fifth and sixth arguments.

Custom CSS

The final setting is to allow the user to add some custom CSS to the theme that will be used on every page. I want this to be a plain textarea into which the user can enter CSS. // Custom CSS file $name = 'theme_demystified/customcss'; $title = get_string('customcss','theme_demystified'); $description = get_string('customcssdesc', 'theme_demystified'); $setting = new admin_setting_configtextarea($name, $title, $description, ); $temp->add($setting); Just like the editor or text settings. It's getting very easy now!

Finishing settings.php

With all of our settings defined and added to our page that we created right at the beginning it is time to finish it all off. // Add our page to the structure of the admin tree $ADMIN->add('themes', $temp); The above line of code is the final line for the page. It is adding the page that we have created $temp to the admin tree structure. In this case it is adding it to the themes branch.

The following is the completed source for our settings.php ..... for your copy/paste pleasure.

<?php

/**

* Settings for the demystified theme
*/

// Create our admin page $temp = new admin_settingpage('theme_demystified', get_string('configtitle','theme_demystified'));

// Background colour setting $name = 'theme_demystified/backgroundcolor'; $title = get_string('backgroundcolor','theme_demystified'); $description = get_string('backgroundcolordesc', 'theme_demystified'); $default = '#DDD'; $setting = new admin_setting_configtext($name, $title, $description, $default, PARAM_CLEAN, 12); $temp->add($setting);

// Logo file setting $name = 'theme_demystified/logo'; $title = get_string('logo','theme_demystified'); $description = get_string('logodesc', 'theme_demystified'); $setting = new admin_setting_configtext($name, $title, $description, , PARAM_URL); $temp->add($setting);

// Block region width $name = 'theme_demystified/regionwidth'; $title = get_string('regionwidth','theme_demystified'); $description = get_string('regionwidthdesc', 'theme_demystified'); $default = 200; $choices = array(150, 170, 200, 240, 290, 350, 420); $setting = new admin_setting_configselect($name, $title, $description, $default, $choices); $temp->add($setting);

// Foot note setting $name = 'theme_demystified/footnote'; $title = get_string('footnote','theme_demystified'); $description = get_string('footnotedesc', 'theme_demystified'); $setting = new admin_setting_confightmleditor($name, $title, $description, ); $temp->add($setting);

// Custom CSS file $name = 'theme_demystified/customcss'; $title = get_string('customcss','theme_demystified'); $description = get_string('customcssdesc', 'theme_demystified'); $setting = new admin_setting_configtextarea($name, $title, $description, ); $temp->add($setting);

// Add our page to the structure of the admin tree $ADMIN->add('themes', $temp);

Creating a language file and adding our strings

As I'm sure none of your have forgotten throughout the creation of the our settings.php page we used alot of strings that I mentioned we would set later on. Well not it is time to set those strings.

First up create the following directory and file for our language strings:

  • Directory theme/demystified/lang
  • Directory theme/demystified/lang/en
  • File theme/demystified/lang/theme_demystified.php

What we have created here is the required structure for Moodle to start looking for language strings.

First up Moodle searches locates the lang directory, once found it looks within a that directory for a directory that makes the character code for the language the user has selected, by default this is en for English, once that is found it looks for the appropriate language file in this case theme_demystified from which it will load all language strings for our theme.

If English isn't your first language simply replace the en directory with one that uses your chosen languages character code (two letters).

We can now add our language strings to theme/demystified/lang/theme_demystified.php. Copy and paste the following lines of PHP into this file. <?php

/**

* This file contains the strings used by the demystified theme
*/

$string['backgroundcolor'] = 'Background colour'; $string['backgroundcolordesc'] = 'This sets the background colour for the theme.'; $string['configtitle'] = 'Demystified theme'; $string['customcss'] = 'Custom CSS'; $string['customcssdesc'] = 'Any CSS you enter here will be added to every page allowing your to easily customise this theme.'; $string['footnote'] = 'Footnote'; $string['footnotedesc'] = 'The content from this textarea will be displayed in the footer of every page.'; $string['logo'] = 'Logo'; $string['logodesc'] = 'Enter the URL to an image to use as the logo for this site. Should be http://www.yoursite.com/path/to/logo.png'; $string['regionwidth'] = 'Column width'; $string['regionwidthdesc'] = 'This sets the width of the two block regions that form the left and right columns.';

In the above lines of code I have added an entry for each language string we used in the settings.php file. When adding language strings like this make sure you use single quotes and try to keep things alphabetical - it helps greatly when managing strings.

Now when we view the settings page there will not be any errors or strings missing.

Having a look at what we have created

Now that we have created our settings page (settings.php) and added all of the language strings it is time to have a look at things within your browser.

Open your browser and enter the URL to your installation. When you arrive your site login as an admin.

If you are not redirected to view new settings change your URL to http://www.yoursite.com/admin/ and your will see a screen to set the new theme settings we have just created. This lets us know that everything has worked correctly.

At any point now you are able to log in as admin and within the settings block browse to Site administration > Appearance > Themes > Demystified theme to change those settings.

The screenshot below shows you what you should see at this point:

The settings page we just created


Using the settings in CSS

With the settings page now created and operational it is time to make use of our new settings. The settings that we want to use within our CSS is as follows:

backgroundcolor
Will be used to set the background colour in CSS.
regionwidth
Will be the width of the column for CSS.
customcss
Will be some custom CSS to add to our stylesheet.

At this point those names are the names we used for our setting with the slash and everything before it having been removed.

Before we start tearing into some code it is important that we have a look at what we are going to do and how we are going to go about it.

How it all works within Moodle

The first thing to understand is that while Moodle allows you to create a settings page and automates it inclusion and management right into the admin interfaces there is no smart equivalent for using the settings. This is simply because there is no way to predict how people will want to use the settings.

However don't think of this as a disadvantage, in fact it is quite the contrary. Although we can't just use our settings we can take full control over how and where we use them. It means it will take a little more code but in the end that will work to our advantage as we can do anything we want.

Moodle does help us out a little but not in an obvious way. The first thing that Moodle does is look for a config variable csspostprocess that should be the name of a function which we want called to make any changes to the CSS after it has been prepared.

The second thing Moodle does is include a lib.php from the theme's directory if one exists (also for the themes the current theme extends.) which ensures that as long as we write our code within theme/demystified/lib.php it will be included and ready to be used.

The third and final thing Moodle does that will help us out here is ensure that by the time any of code is ready to execute the settings have been prepared and are ready to be used within a theme config object which is passed into our csspostprocess function.

Our plan

As you have already probably guessed we will need to create a function to make the changes to the CSS that we want. We will then set the theme config option $THEME->csspostprocess to the name of our function.

By doing this when Moodle builds the CSS file it will call our function afterwards with the CSS and the theme object that contains our setting.

Now we know that we will use the csspostprocess function but how are we going to change the CSS, we could get the function to add CSS, or we could get the function to replace something within the CSS. My personal preference is to replace something within the CSS, just like what is happening with images. If you want to use an image within CSS you would write [[pix:theme|imagename]].

For settings I am going to use [[setting:settingname]], this way it looks a bit like something you are already familiar with.

What we need to decide upon next is the best way in which to replace our settings tag with the settings that the user has set.

Here I two immediate options available to us:

  1. Make the csspostprocess function do all the work.
  2. Make the csspostprocess function call a separate function for each setting.

Solution 1 might sound like the simplest however it is going to result in a VERY complex function. Remember the user might have left settings blank or entered something that wouldn't be valid so we would need to make the sure there is some validation and a good default. Because of this I think that solution 2 is the better solution.

So we are going to need a css post process method and a function for each of the three settings we have that will do the replacements. // This is our css post process function function demystified_process_css($css, $theme) {}; // This replaces setting:backgroundcolor with the background colour function demystified_set_backgroundcolor($css, $backgroundcolor) {}; // This replaces setting:regionwidth with the correct region width function demystified_set_regionwidth() {$css, $regionwidth}; // This replaces setting:customcss with the custom css function demystified_set_customcss() {$css, $customcss};

What you should note about the above functions is that they all start with the theme's name. This is required to ensure that the functions are named uniquely as it is VERY unlikely that someone has already created these functions.

So with our plan set our lets start writing the code.

Writing the code

The very first thing that we need to do is create a lib.php for our theme into which our css processing functions are going to go. So please at this point create theme/demystified/lib.php and open it in your editor ready to go.

The first bit of code we have to write is the function that the function that will be called by Moodle to do the processing demystified_process_css. Before we start out please remember that the wonderful thing about coding is that there is any number of solutions to a problem. The solutions that you are seeing here in this tutorial are solutions that I have come up with to meet fulfil the needs of the tutorial without being so complex that they are hard to understand.

The function: demystified_process_css

function demystified_process_css($css, $theme) {

   if (!empty($theme->settings->backgroundcolor)) {
       $backgroundcolor = $theme->settings->backgroundcolor;
   } else {
       $backgroundcolor = null;
   }
   $css = demystified_set_backgroundcolor($css, $backgroundcolor);
   if (!empty($theme->settings->regionwidth)) {
       $regionwidth = $theme->settings->regionwidth;
   } else {
       $regionwidth = null;
   }
   $css = demystified_set_regionwidth($css, $regionwidth);
   if (!empty($theme->settings->customcss)) {
       $customcss = $theme->settings->customcss;
   } else {
       $customcss = null;
   }
   $css = demystified_set_customcss($css, $customcss);
   return $css;

}

So lets look at the things that make up this function:

function demystified_process_css($css, $theme) {

   //.....
   return $css

}

This of course is the function declaration.

The function gets given two variables, the first $css is a pile of CSS as one big string, and the second is the theme object that contains all of the configuration, options, and settings for our theme.

It then returns the $css variable, essentially returning the modified CSS.

   //...
   if (!empty($theme->settings->backgroundcolor)) {
       $backgroundcolor = $theme->settings->backgroundcolor;
   } else {
       $backgroundcolor = null;
   }
   $css = demystified_set_backgroundcolor($css, $backgroundcolor);
   //...

Here we are processing our first setting backgroundcolor. The first thing that we need to do is check whether it has been set and whether it has a value. If it has then we store that value in $backgroundcolor. It is doesn't have a value then we set $backgroundcolor to null. This ensures that $backgroundcolor is set because if it isn't then you are going to get a notice (if you have debugging on).

The final line of this block calls the function demystified_set_backgroundcolor. We haven't written this function yet but we will shortly. When we call it we give it the $css variable that contains all of the CSS and we give it the background color variable $background. Once this function is finished it returns the $css variable with all of the changes made much like how our css processing function works.

What you should also note about this code is this: $theme->settings->backgroundcolor As mentioned earlier $theme is an object that contains all of the configuration and settings for our theme. The $theme object has a $settings property which contains all of the settings for our theme, and finally the settings property contains a variable backgroundcolor that is the value the user entered for that setting. That is how we get a settings value.

   if (!empty($theme->settings->regionwidth)) {
       $regionwidth = $theme->settings->regionwidth;
   } else {
       $regionwidth = null;
   }
   $css = demystified_set_regionwidth($css, $regionwidth);
   if (!empty($theme->settings->customcss)) {
       $customcss = $theme->settings->customcss;
   } else {
       $customcss = null;
   }
   $css = demystified_set_customcss($css, $customcss);

These two routines are nearly identical to the routine above. For both the regionwidth and the backgroundcolor we make sure it has a value and then store it in a variable. We then call the relevant function to make the changes for that setting.

Now that we have the general processing function it is time to write the three functions we have used but not written, demystified_set_backgroundcolor, demystified_set_regionwidth, demystified_set_customcss.

The function: demystified_set_backgroundcolor

First up demystified_set_backgroundcolor.

/**

* Sets the background colour variable in CSS
*
* @param string $css
* @param mixed $backgroundcolor
* @return string
*/

function demystified_set_backgroundcolor($css, $backgroundcolor) {

   $tag = 'setting:backgroundcolor';
   $replacement = $backgroundcolor;
   if (is_null($replacement)) {
       $replacement = '#DDDDDD';
   }
   $css = str_replace($tag, $replacement, $css);
   return $css;

}

The function: demystified_set_regionwidth

Next we have the demystified_set_regionwidth function. /**

* Sets the region width variable in CSS
*
* @param string $css
* @param mixed $regionwidth
* @return string
*/

function demystified_set_regionwidth($css, $regionwidth) {

   $tag = 'setting:regionwidth';
   $doubletag = 'setting:regionwidthdouble';
   $replacement = $regionwidth;
   if (is_null($replacement)) {
       $replacement = 200;
   }
   $css = str_replace($tag, $replacement.'px', $css);
   $css = str_replace($doubletag, ($replacement*2).'px', $css);
   return $css;

}

The function: demystified_set_customcss

The final function that we need to write is the demystified_set_customcss function. /**

* Sets the custom css variable in CSS
*
* @param string $css
* @param mixed $customcss
* @return string
*/

function demystified_set_customcss($css, $customcss) {

   $tag = 'setting:customcss';
   $replacement = $customcss;
   if (is_null($replacement)) {
       $replacement = ;
   }
   $css = str_replace($tag, $replacement, $css);
   return $css;

}

And that is it no more PHP... Hallelujah I can hear you yelling. The final thing we need to do is tell our theme about the functions we have written and put the settings tags into the CSS.

Finishing it all off

So there are two things we have to do in order to complete this section and have our the settings page implemented and our settings being used.

First we need to tell our theme that we want to use the function demystified_process_css as the csspostprocess function. This is done very simply by adding the following line of PHP to our theme's config.php file (theme/demystified/config.php).

$THEME->csspostprocess = 'demystified_process_css';

With that done the only thing left is to add the settings tag into the CSS. Remember those settings tags are:

[[setting:backgroundcolor]]
We need to add this where ever we want the background colour setting to be used.
[[setting:regionwidth]]
We need to add this where ever we want to set the width of the block regions.
[[setting:customcss]]
We need to add this to the bottom of the CSS file that we want the custom CSS added to.

So lets make those changes in CSS now, open up you core.css file and replace the CSS with the CSS below: /** Background color is a setting **/ html {background-color:setting:backgroundcolor;} body {margin:30px;padding:0;border:1px solid #333;border-width:0 10px 0 10px;background-color:#333;} body #page {background-color:#FFF;position:relative;top:-10px;} .block .header {background-image:none;background-color:#0C5CAC;border:1px solid #0C5CAC;color:#FFF;} .block {border-color:#4BA7FF;background-color:#DDEEFF;} .block .content {background-color:#F1F8FF;} a:link, a:visited {color:#0C5CAC;} a:hover {color:#C77500;}

  1. page #page-header {background-color:#0C5CAC;margin:0;padding:0;width:100%;color:#fff;}
  2. page #page-header a:link, #page #page-header a:visited {color:#FFAC02}
  3. page #page-header .navbar, #page #page-header .navbar a:link, #page #page-header .navbar a:visited {color:#0C5CAC;}

/** Override the region width **/

  1. page-content #region-main-box {left:setting:regionwidth;}
  2. page-content #region-main-box #region-post-box {margin-left:-setting:regionwidthdouble;}
  3. page-content #region-main-box #region-post-box #region-pre {width:setting:regionwidth;left:setting:regionwidth;}
  4. page-content #region-main-box #region-post-box #region-post {width:setting:regionwidth;}
  5. page-content #region-main-box #region-post-box #region-main-wrap #region-main {margin-left:setting:regionwidthdouble;}

/** Custom CSS **/ setting:customcss

You will notice that [[setting:backgroundcolor]] has been used for the html tags background color: html {background-color:setting:backgroundcolor;}

We have also set the width of the block regions by adding [[setting:regionwidth]] as the width for region-pre and region-post as shown below:

  1. page-content #region-main-box {left:setting:regionwidth;}
  2. page-content #region-main-box #region-post-box {margin-left:-setting:regionwidthdouble;}
  3. page-content #region-main-box #region-post-box #region-pre {width:setting:regionwidth;left:setting:regionwidth;}
  4. page-content #region-main-box #region-post-box #region-post {width:setting:regionwidth;}
  5. page-content #region-main-box #region-post-box #region-main-wrap #region-main {margin-left:setting:regionwidthdouble;}

You'll notice here that we have to set several different width and margins using the regionwidth setting and make use of the special regionwidthdouble setting that we added.

The final thing that we did was add the [[setting:customcss]] to the bottom of the file to ensure that the custom CSS comes last (and therefore can override all other CSS).

And with that we are finished. The screenshot below shows how this now looks in the browser if I set the background colour setting to #FFA800 and made the column width 240px;

Our settings in action

Using the settings within our layout files

The monster that we have just created

Common pitfalls and useful notes

More information