Monday 4 February 2013

Create a Module for Joomla 2.5

Create a Custom Joomla 2.5 Module

In this tutorial we will create a "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.

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   (The main folder name, Place the below files inside this folder)
-mod_siteusers.xml
-mod_siteusers.php
-helper.php
-index.html
--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>PatrioSys</author> 
<creationDate>2013</creationDate> 
<copyright>All rights reserved by PatrioSys.</copyright> 
<license>GPL 2.0</license> 
<authorEmail>
 info@softmanic.com</authorEmail> 
<authorUrl>www.softmanic.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

//No access
define('_JEXEC') or die('Direct Access to this Location is not allowed.');


//This is the parameter we get from the XML file 

$userCount= $params->get('usercount');


//Include syndicate function only once

require_once dirname(__FILE__).'/helper.php';



//Require 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

define('_JEXEC') or die;



//Add database instance

$db= JFactory::getDBO();



//Pass query Limit by usercount parameter (Check XML)

$query="SELECT name FROM #__users LIMIT {userCount}";



//Run The query

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
<?php define('_JEXEC') or die('Restricted access'); ?>
<p><?php echo JText::_('DESC_MODULE'); ?></p>
<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..

To select more than one field just add them to your query after "email" or use an asterisk(*) to select ALL fields on that table.

SELECT email,field2,fi eld3 FROM #__users LIMIT....
OR
SELECT * FROM #__users LIMIT
Ex: $row->name,$row->email,$row->field2 ..........

tmpl/ordered_list.php
<?php define('_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

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 go to the extension manager. From the "install" section  browse and upload the zip file. You should get a "Successful Install" message.
Extension Manager in Joomla 2.5

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.

















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

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 this list items.

2 comments:

  1. Nice introduction at all ...

    ... but I've some enhancement-suggestions: ;)

    * Formatting issues:
    - what's about this "more compressed" format?

    <field name="layout" type="list" default="default"
    label="LABEL_USER_LAYOUT"
    description="DESC_USER_LAYOUT">

    (I hate too much indent-space and indent-irregularities
    during a series of items ;)
    (And I prefer spaces for indenting ...
    tabs of inserted code-snippets nearly always mess up
    "beautiful formatted" code ;)

    * Using lang-Labels without language-file?
    - LABEL_USER_LAYOUT
    - DESC_USER_LAYOUT
    - Doesn't their usage need an extra file like
    en-GB.mod_<_your_modules_name_>.ini
    to work?

    * For a "Database Driven and Dynamic Module" I'd expected
    also to maintain some own DB-Tables ...
    ... especially as example for:
    - How to create DB-Objects during module-installation
    - How to manage their deletion during modules DE-installation
    - Should mean .sql-script including for the package ?
    - Or dynamically PHP-code?
    - Example for PHP -insert / -update / -delete functionality
    - Perhaps including a simple lookup-table

    Jaybear

    PS: I like your mostly human-friendly Captchas!

    ReplyDelete
    Replies
    1. Oops ... HTML-formatting and leading spaces ...
      This was meant as my formatting-example:

      <field name="layout" type="list" default="default"
        label="LABEL_USER_LAYOUT"
        description="DESC_USER_LAYOUT">

      (two spaces for each level - just fine for fixed fonts in most editors ;)

      Jaybear

      Delete