Second Module - Adding Parameters and Using the Database

  • PDF

Our second module tutorial will display the number of articles in a category. We will select the category in the administrator using a parameter shown in the module manager.

To create this module we will start with the HelloWorld module and extend it to include a parameter and access the Joomla! database in you PHP code.

We will rename the module mod_categorycount.  So we will have to rename out directory from mod_helloworld to mod_categorycount; and then rename and edit our descriptor file (mod_categorycount.xml).  After we edit this file it will look like this:

<?xml version="1.0" encoding="utf-8"?>
<extension type="module" version="2.5.0" client="site" method="upgrade">
 <name>Count Categories</name>
 <author>James H. Murphy</author>
 <creationDate>06/08/2012</creationDate>
 <copyright></copyright>
 <license>GNU</license>
 <authorEmail>info@trionia.com</authorEmail>
 <authorUrl>www.trionia.com</authorUrl>
 <version></version>
 <description>Count Category Module</description>
 <files>
 <filename module="mod_categorycount">mod_categorycount.php</filename>
 </files>
</extension>

Now our next step is to add a category form field to our xml file.  The link below shows how to setup the category parameter:

http://docs.joomla.org/Category_form_field_type

The new lines to ad to your XML file will look like this:

<config>
  <fields name="params">
    <fieldset name="advanced">
      <field name="selectedCategory" type="category"
         label="Select a Category" extension="com_content"
         description="This module will display the number of articles from the selected category."
       />
    </fieldset>
   </fields>
 </config>

To access the parameter in your module code you can use this syntax:

$categoryId = $params->get('selectedCategory');

The pseudo-code for the mod_categorycount.php file is:

<?php
//no direct access
defined('_JEXEC') or die('Direct Access to this location is not allowed.');
// Access the parameter for your category id
// Create the Database Object
// Create and execute you query to count articles in #__content for the category id
// Get the count result
// Write out the number of articles in the category
?>

To create the query and for selecting the number of articles.  The best references are at these links:

Database Schema - an ERD diagram of the Joomla! database.

Database Methods - a link to the Joomla! database methods documentation.  (You may want to book mark this link.)