Create a Custom Joomla 2.5 Module

Written by Brad Traversy on 22 May 2012.


There are tons of Joomla tutorials all around the web, but most of them are simple beginner tutorials (including our own). I decided to create a tutorial for beginner developers on how to create a custom Joomla module. I don't mean a "Custom HTML" module, I mean an actual database driven and dynamic module. The module we will create will interact with the database and give us a list of registered users on the site. Lets get started...

Creating the folder and file structure

There is a strict file/folder structure when creating any kind of Joomla extension. Create the files and folders below using your favorite code editor or IDE. If you don't have this, use Notepa.. Create the main folder which will be called  "mod_siteusers". Then create the files/folders below.

Important: In order for the module to work, the mod_siteusers folder needs to be in your Joomla sites "Modules" folder BUT do not put it there yet because we need to create everything first then pack it in a zip file to install via Joomla admin area.

mod_siteusers

  • -mod_siteusers.xml
  • -mod_siteusers.php
  • -helper.php
  • -index.html
  • -en-GB.mod_siteusers.ini
  • --tmpl (folder)
  • --tmpl/default.php
  • --tmpl/ordered_list.php
  • --tmpl/index.html

Lets go through each file one by one...please read the comments in the code as well

mod_siteusers.xml

This file holds all of the modules metadata, information and parameters. The file structure must be exact.

<?xml version="1.0" encoding="utf-8"?>
<extension type="module" version="1.6.0" client="site" method="install">
	<name>Site Users</name> 
	<author>Brad Traversy</author> 
	<creationDate>2012</creationDate> 
	<copyright>All rights reserved by Tech Guy Web Solutions.</copyright> 
	<license>GPL 2.0</license> 
	<authorEmail>This email address is being protected from spambots. You need JavaScript enabled to view it.
 </authorEmail> 
	<authorUrl>www.techguywebsolutions.com</authorUrl> 
	<version>1.0.0</version> 
	<description>Provides a listing of registered users</description>
    <!-- Listing of all files that should be installed for the module to function -->
	<files>
        <!-- The "module" attribute signifies that this is the main controller file -->
		<filename module="mod_siteusers">mod_siteusers.php</filename>
		<filename>index.html</filename>
		<filename>helper.php</filename>
		<filename>tmpl/default.php</filename>
                <filename>tmpl/ordered_list.php</filename>
		<filename>tmpl/index.html</filename>
	</files>
 
    <languages>
        <!-- Any language files included with the module -->
        <language tag="en-GB">en-GB.mod_siteusers.ini</language>
    </languages>
 
    <!-- Optional parameters -->
	<config>
            <fields name="params">
                <fieldset name="basic">
                    <field 
                        name="moduleclass_sfx" 
                        type="text" 
                        default="" 
                        label="LABEL_CLASS_SUFFIX" 
                        description="DESC_MOD_SUFFIX">
                    </field>
                     <field 
                        name="@spacer" 
                        type="spacer" 
                        default="" 
                        label="" 
                        description="">
                    </field>
                     <field 
                        name="usercount" 
                        type="text" 
                        default="5" 
                        label="LABEL_USER_COUNT" 
                        description="DESC_USER_COUNT">
                    </field>
                     <field 
                        name="layout" 
                        type="list" 
                        default="default" 
                        label="LABEL_USER_LAYOUT" 
                        description="DESC_USER_LAYOUT">
                       <option
				value="default">Unordered List</option>
			<option
			value="ordered_list">Ordered List</option>
                    </field>
                </fieldset>
            </fields>
    </config>
</extension>

Feel free to change the personal info. One thing you should look at here is the "<field> tags. These are the parameters that are on the right hand side when viewing your module in modlue manager. Here we have 4. The first is the "module class suffix" which all modules have. The suffix the user adds here will be attached to the modules css class so you can style individual modules. The second is just a simple "spacer". The third is the number of users you wish to display in the module and finally, the fourth is the layout option. You can have multiple layouts for one module. Each layout should go in the tmpl folder. Our 2 options here is the default, which is an unordered list with the "Website Users" description at the top. The ordered_list layout uses a numbered list and no description at the top. The changes are very subtle but I just wanted to show you a simple example.

Another thing you might be looking at is the uppercase constants like "LABEL_USER_COUNT". These are used with the language file that will be included later.

mod_siteusers.php

This file acts as a controller directing the functions and files

<?php
//don't allow other scripts to grab and execute our file
defined('_JEXEC') or die('Direct Access to this location is not allowed.');

//This is the parameter we get from our xml file above
$userCount = $params->get('usercount');

// Include the syndicate functions only once
require_once dirname(__FILE__).'/helper.php';

//Returns the path of the layout file
require JModuleHelper::getLayoutPath('mod_siteusers', $params->get('layout', 'default'));
?>

helper.php

This is the main workhorse model that handles the business logic

<?php
//No access
defined( '_JEXEC' ) or die;

//Add database instance
$db = JFactory::getDBO();

//Pass in query - Limit by the usercount param
$query = "SELECT name FROM #__users LIMIT {$userCount}";

//Run it
$db->setQuery($query);

//Load it as an object into the variable "$rows"
$rows = $db->loadObjectList();
?>

This file runs the query and selects the user "names" from the #__users table and limits the number of returned rows to whatever the user sets as the "user count" param from module manager. This query will then be loaded using the "loadObjectsList method and put in the $rows variable which we can now loop through in our default.php layout file below.

index.html

<html><body bgcolor="#FFFFFF"></body></html>

This html file is strictly used to prevent users from accessing the module files directly

tmpl/default.php

<ul>
    <?php foreach ($rows as $row){ ?>
       <li>
            <?php echo JText::sprintf('USER_LABEL', $row->name); ?>
        </li>
  <?php } ?>
</ul>

The default.php file is the modules "default view". It is in charge of displaying the module to the user. It is essentially html with php includes and loops. This file performs a foreach loop to diaplay the $rows array which is the array of users.

tmpl/ordered_list.php

<?php defined( '_JEXEC' ) or die( 'Restricted access' ); ?>
<ol>
    <?php foreach ($rows as $row){ ?>
        <li>
            <?php echo JText::sprintf('USER_LABEL', $row->name); ?>
        </li>
  <?php } ?>
</ol>

This is the "ordered list" layout. As stated above, the only difference is that it uses a numbered list and has no description parameter.

tmpl/index.html

<html><body bgcolor="#FFFFFF"></body></html>

Same as above, it is used to prevent users from accessing the module files directly

en-GB.mod_siteusers.ini

This is the language file which should have the following...

LABEL_USER_COUNT="User Count"
DESC_USER_COUNT="The number of users to display"
LABEL_CLASS_SUFFIX ="Module Class Suffix"
DESC_MOD_SUFFIX ="Add a module css class suffix"
DESC_MODULE="Website Users"
USER_LABEL="%s"

Now that all of your files are created, add the entire "mod_siteusers" folder to a zip file using whatever zip program you use (winzip, winrar, 7zip, etc).

Congrats! Your first Joomla module is complete. Lets try it out!

Login to your Joomla admin area and goto the extension manager. From the "install" seciton, browse and upload the zip file. You should get a "Successful Install" message.

um2

Now go to the "Module Manager" and you should see your module. click on the title. Now you should see the properties of the module. You should see all your parameters on the right hand side. You can change the number of users to be displayed as well as the layout. Now make sure it is published and use the desired module position in your template.

428_um3

Visit your frontend and you should see a list of your website users.

um1

This module is not very pretty. Ill leave that up to you. This is just a very simple module. You can use this framework to show anything from the database such as articles and more. You can also choose to display users email addresses, username, etc and could add links to the list items. The possibilities are endless!

You can download the code above here

About The Author

Brad Traversy is a web developer/designer from Boston Massachusetts. He specializes in web development using open source content management systems such as Joomla, Drupal and Wordpress.

HEADER  

Futuros7
 
I read one of your helpful information regarding the error message "error uploading this file to the server". I am a beginner in the Joomla world and was trying to upload a 2.5 template. I tried your instructions twice but did not work, space disk is 40m. Do you have any tutorial step by step that I can follow? Thanks!
moses bwalya
 
Hai there brad my module requires me to display values from the DB in a text box and the module has got two combo boxes which the user selects their destination1 and destination2 to retrieve their desired output..Now my problem is to work around this??????
kins
 
thanks mister Brad
usefull.
i have a question, you know how i can include the editor (tinymce) in the backend of module? for write some html?
i did a copy of default "custom Html" module of joomla, and change the name entirely, zip and installed again, but the editor is not showing in the backend, really do not know what causes the editor to appear. mistery =)
regards
and thanks a lot
Antonio G.
 
Perfect!
Well explained and especially working!
Many thanks.
ajaysinghrana
 
I am new to joomla and you made it so easy for me to learn how to create a module..but i had a problem in this line to display in default.php..
JText::sprintf('USER_LABEL', $row->name)
but when i echo it like this echo "$row->name"; ... it was working fine..
shoeb
 
thanks sir
Patrick
 
Super!. Thanks Brad.

I want to use the same module twice on same page with different params. I can't get it to work.
farzad
 
thanks :)
jbaptiste
 
How to learn quickly what we need ^^

thanks :)
Phil
 
Big thanks to you Brad.
I was look for a "how to do" site. Found your article in the first google results and 30 min after my first 'homemade' module was online.
Just a further question.
How do I update the module? I have made some custom change in php and zip the pack again but when installing by joomla, it says the module already exist.
How to do update replacement files?
Latest News