User

Rvsjoen/tutorial/Developing an MVC Component/Part 06

From Joomla! Documentation

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

Using a database[edit]

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 order order of business is to create some SQL tables.

SQL install/uninstall[edit]

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

admin/sql/install.mysql.utf8.sql

DROP TABLE IF EXISTS `#__helloworld`;

CREATE TABLE `#__helloworld` (
  `id` int(11) NOT NULL auto_increment,
  `greeting` varchar(25) NOT NULL,
   PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;

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

admin/sql/uninstall.mysql.utf8.sql

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[edit]

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.

You will also notice that the table class is not prefixed with the component name in the same way as the model, view and controller.

With your favorite editor, create the following file

site/models/helloworld.php

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

jimport('joomla.database.table');

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[edit]

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

site/models/helloworld.php

<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');

jimport('joomla.application.component.modelitem');

class HelloWorldModelHelloWorld extends JModelItem
{
        protected $item;

        /**
         * Get the message
         * @return string The message to be displayed to the user
         */
        public function getItem() 
        {
                if (!isset($this->item)) {
                        $id = JRequest::getInt('id');
                        // Get a TableHelloWorld instance
                        $table = $this->getTable('HelloWorld', 'HelloWorldTable');

                        // Load the message
                        $table->load($id);

                        // Assign the message
                        $this->item = $table->greeting;
                }
                return $this->item;
        }
}

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[edit]

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

admin/models/fields/helloworld.php

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

jimport('joomla.form.helper');

JFormHelper::loadFieldClass('list');

class JFormFieldHelloWorld extends JFormFieldList
{
        protected $type = 'HelloWorld';

        protected function getOptions()
        {
                $db = JFactory::getDBO();
                $query = $db->getQuery(true);
                $query->select('id,greeting');
                $query->from('#__helloworld');
                $db->setQuery((string)$query);
                $messages = $db->loadObjectList();
                $options = array();
                if($messages){
                        foreach($messages as $message){
                                $options[] = JHtml::_('select.option', $message->id, $message->greeting);
                        }
                }
                $options = array_merge(parent::getOptions(), $options);
                return $options;
        }
}

Installation manifest[edit]

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.

helloworld.xml

<?xml version="1.0" encoding="utf-8"?>
<extension type="component" version="1.6.0" method="upgrade">

        <name>Hello World!</name>
        <!-- The following elements are optional and free of formatting constraints -->
        <creationDate>June 2011</creationDate>
        <author>John Doe</author>
        <authorEmail>john.doe@example.org</authorEmail>
        <authorUrl>http://www.example.org</authorUrl>
        <copyright>Copyright Info</copyright>
        <license>License Info</license>
        <!--  The version string is stored in the components table -->
        <version>0.0.6</version>
        <!-- The description is optional and defaults to the name -->
        <description>Description of the Hello World component ...</description>

        <install>
                <sql>
                        <file driver="mysql" charset="utf8">sql/install.mysql.utf8.sql</file>
                </sql>
        </install>
        <uninstall>
                <sql>
                        <file driver="mysql" charset="utf8">sql/uninstall.mysql.utf8.sql</file>
                </sql>
        </uninstall>

        <!-- Note the folder attribute: This attribute describes the folder
                to copy FROM in the package to install therefore files copied
                in this section are copied from "site/" in the package -->
        <files folder="site">
                <filename>index.html</filename>
                <filename>helloworld.php</filename>
                <filename>controller.php</filename>
                <folder>views</folder>
                <folder>models</folder>
        </files>

        <administration>
                <menu>Hello World!</menu>
                <!-- Note the folder attribute: This attribute describes the folder
                        to copy FROM in the package to install therefore files copied
                        in this section are copied from "admin/" in the package -->
                <files folder="admin">
                        <filename>index.html</filename>
                        <filename>helloworld.php</filename>
                        <folder>sql</folder>
                        <folder>tables</folder>
                        <folder>models</folder>
                </files>
        </administration>

</extension>

Testing your component[edit]

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[edit]

Download this part[edit]

com_helloworld-part01.zip

Articles in this series[edit]

This tutorial is supported by the following versions of Joomla!

Joomla 2.5