Rvsjoen/tutorial/Developing an MVC Component/Part 06

From Joomla! Documentation

< User:Rvsjoen‎ | tutorial/Developing an MVC Component

Using a database

We would like to store our hello messages in the database, and to allow the admins to choose which message to show using a field in the menu item options. The first order of business is to create some SQL tables.

SQL install/uninstall

Let us start with creating some installation and uninstall scripts that will be executed when the component is installed or uninstalled. Afterwards we will update the installation manifest and tell it where these files are and what to do with them.

With your favorite editor, create the following files


DROP TABLE IF EXISTS `#__helloworld`;

CREATE TABLE `#__helloworld` (
  `id` int(11) NOT NULL auto_increment,
  `greeting` varchar(25) NOT NULL,
   PRIMARY KEY  (`id`)

INSERT INTO `#__helloworld` (`greeting`) VALUES
        ('Hello World!'),
        ('Good bye World!');


DROP TABLE IF EXISTS `#__helloworld`;

You may wonder why we are using #__ to prefix the table names, this is part of Joomla! builtin functionality and this string will be automatically replaced with the configured database prefix. In other words, hard-coding table names in these files is a bad idea. Stick to the program here.

Creating a table

We will also create a table class which we can use as a representation of a row in our helloworld table. This provides additional abstraction as compared to writing and executing the queries manually, this will become clearer in a second. Basically all we need to do is to create the table class, we put it in admin/tables simply because the tables folder in the administrator part of the components is the default place to look for table classes.

With your favorite editor, create the following file


// No direct access to this file
defined('_JEXEC') or die;


class HelloWorldTableHelloWorld extends JTable
        function __construct(&$db) 
                parent::__construct('#__helloworld', 'id', $db);

The call to the parent constructor is used to define which column is the primary key of the table. In our case this is the id column.

Updating the model

Next we need to tell the model how to use our shiny new table class.

With your favorite editor, modify the following file to look like this


 1 <?php
 2 // No direct access to this file
 3 defined('_JEXEC') or die('Restricted access');
 5 jimport('joomla.application.component.modelitem');
 7 class HelloWorldModelHelloWorld extends JModelItem
 8 {
 9         protected $item;
11         /**
12          * Get the message
13          * @return string The message to be displayed to the user
14          */
15         public function getItem() 
16         {
17                 if (!isset($this->item)) {
18                         $id = JRequest::getInt('id');
19                         // Get a TableHelloWorld instance
20                         $table = $this->getTable('HelloWorld', 'HelloWorldTable');
22                         // Load the message
23                         $table->load($id);
25                         // Assign the message
26                         $this->item = $table->greeting;
27                 }
28                 return $this->item;
29         }
30 }

As you can see in the code, first we instantiate the table class using $this->getTable('HelloWorld', 'HelloWorldTable'). The first parameter is the table name, and the second is the prefix and will result in the class name HelloWorldTable.

After we have an instance of the table, we can use it to retrieve a record with a specific id from the database using the load() function. The member variables of the table instance will be automatically populated with the columns in the table and this makes us able to access $table->greeting after loading the appropriate row.

Creating a form field

We also want the admin to be able to select which greeting the view should display by using the same manner as before, an option in the menu item. In order to make this possible we will create our own form field which shows a list of hello message currently in the table.

With your favorite editor, create the following file


 1 <?php
 2 // No direct access to this file
 3 defined('_JEXEC') or die;
 5 jimport('joomla.form.helper');
 7 JFormHelper::loadFieldClass('list');
 9 class JFormFieldHelloWorld extends JFormFieldList
10 {
11         protected $type = 'HelloWorld';
13         protected function getOptions()
14         {
15                 $db = JFactory::getDBO();
16                 $query = $db->getQuery(true);
17                 $query->select('id,greeting');
18                 $query->from('#__helloworld');
19                 $db->setQuery((string)$query);
20                 $messages = $db->loadObjectList();
21                 $options = array();
22                 if($messages){
23                         foreach($messages as $message){
24                                 $options[] = JHtml::_('select.option', $message->id, $message->greeting);
25                         }
26                 }
27                 $options = array_merge(parent::getOptions(), $options);
28                 return $options;
29         }
30 }
31 ?>

Using the form field in our form

In order for our newly created form field to be used in the options form, we need to tell the xml definition of our form to use the new type of field which is named helloworld

With your favorite editor, modify the following file to look like this


<?xml version="1.0" encoding="utf-8"?>
        <layout title="Hello World">
                <message>Hello World menu item description</message>
        <fields name="request"
                <fieldset name="request">
                                description="Select a greeting"

Two important things have happened in this file, first of all we have added a path to search for fields in, and secondly we have told our field to be of type helloworld and not list.

Installation manifest

In the manifest we have added the sql, tables and models folders to the administration file copy section. And as you also probably noticed we have added <install> and <uninstall> tags. These are used to specify which SQL files will be executed by the installer when the component is installed or uninstalled.


 1 <?xml version="1.0" encoding="utf-8"?>
 2 <extension type="component" version="2.5.0" method="upgrade">
 4         <name>Hello World!</name>
 5         <!-- The following elements are optional and free of formatting constraints -->
 6         <creationDate>June 2011</creationDate>
 7         <author>John Doe</author>
 8         <authorEmail></authorEmail>
 9         <authorUrl></authorUrl>
10         <copyright>Copyright Info</copyright>
11         <license>License Info</license>
12         <!--  The version string is stored in the components table -->
13         <version>0.0.6</version>
14         <!-- The description is optional and defaults to the name -->
15         <description>Description of the Hello World component ...</description>
17         <install>
18                 <sql>
19                         <file driver="mysql" charset="utf8">sql/install.mysql.utf8.sql</file>
20                 </sql>
21         </install>
22         <uninstall>
23                 <sql>
24                         <file driver="mysql" charset="utf8">sql/uninstall.mysql.utf8.sql</file>
25                 </sql>
26         </uninstall>
28         <!-- Note the folder attribute: This attribute describes the folder
29                 to copy FROM in the package to install therefore files copied
30                 in this section are copied from "site/" in the package -->
31         <files folder="site">
32                 <filename>index.html</filename>
33                 <filename>helloworld.php</filename>
34                 <filename>controller.php</filename>
35                 <folder>views</folder>
36                 <folder>models</folder>
37         </files>
39         <administration>
40                 <menu>Hello World!</menu>
41                 <!-- Note the folder attribute: This attribute describes the folder
42                         to copy FROM in the package to install therefore files copied
43                         in this section are copied from "admin/" in the package -->
44                 <files folder="admin">
45                         <filename>index.html</filename>
46                         <filename>helloworld.php</filename>
47                         <folder>sql</folder>
48                         <folder>tables</folder>
49                         <folder>models</folder>
50                 </files>
51         </administration>
53 </extension>

Testing your component

For details on how to install the component into your Joomla! site, refer to the information provided in Part 01.

In order to test this component, go to the administrator interface and create a new menu item. In the menu item type selection interface, pick Hello World as the menu item type. In the options of the menu item you will be able to choose which hello message to show from the database, the message you choose should be displayed in the frontend as in the previous part.

File listing

Download this part

Download example package

Articles in this series

This tutorial is supported by the following versions of Joomla!

Joomla 2.5