J1.5

Difference between revisions of "Developing a MVC Component/Creating an Administrator Interface"

From Joomla! Documentation

< J1.5:Developing a MVC Component
 
(178 intermediate revisions by 33 users not shown)
Line 1: Line 1:
====== Developing a Model-View-Controller Component - Part 4 - Creating an Administrator Interface ======
+
{{Chunk:Developing a Model-View-Controller (MVC) Component for Joomla!1.5 - Contents}}
 +
== Introduction ==
  
===== Introduction =====
+
In the first three Parts, we have developed a MVC component that retrieves its data from a table in the database. Currently, there is no way to add data to the database except to do it manually using another tool. In the next Parts of this tutorial, we will develop an administrator section for our component which will make it possible to manage the entries in the database.
  
In the first three tutorials, we have developed a MVC component that retrieves its data from a table in the database. Currently, there is no way to add data to the database except to do it manually using another tool. In this tutorial, we will develop an administrator section for our component which will make it possible to manage the entries in the database.
+
This Part, [[Developing a Model-View-Controller Component - Part 4 - Creating an Administrator Interface | Part 4 - Creating an Administrator Interface]], will be an article with no new source code for our Hello component but will describe some basic details and in-depth explanation of the MVC pattern. This intermediate chapter is not required to complete the Hello model so if you think you understand the basics continue with [[Developing a Model-View-Controller Component - Part 5 - Basic Backend Framework]].
  
===== Creating the Basic Framework =====
+
In the frontend solution (site section, parts 1,2 and 3) we developed the first part of our component. The frontend solution is based upon default Controllers, Views and Templates and you were "taken by the hand" and "left to trust" the default handling of the code. This is going to change in the Backend or Administration section of our Hello component ( parts 5 and 6) - we will have to develop all of the code that manages the application flow.
  
The basic framework of the administrator panel is very similar to the site portion. The main entry point for the administrator section of the component is admin.hello.php. This file is identical to the hello.php file that was used in the site portion except the name of the controller it loads will be changed to HellosController. The default controller is also called controller.php and this file is identical to the default controller in the site portion, with the exception that the controller is named HellosController instead of HelloController. This difference is so that JController will by default load the hellos view, which will display a list of our greetings.
+
== Site / Admin ==
 +
Joomla! is a content management system. The '''frontend''' is used for presenting the users with content and allows certain logged in users to manipulate the content. The '''backend''' is responsible for administering the website framework (structuring / managing / controlling / maintaining). This division between (frontend) site-content and (backend) administration is a fundamental aspect of the Joomla! architecture.
  
Here is the listing for admin.hello.php:
+
=== Entrance points ===
 +
From the XML file of our frontend example it was already obvious that there would be an administration part:
 +
<source lang="xml"><?xml version="1.0" encoding="utf-8"?>
 +
  ...
 +
  <administration>
 +
    <!--  Administration Menu Section -->
 +
    <menu>Hello World!</menu>
 +
    <!--  Administration Main File Copy Section -->
 +
    <files folder="admin">
 +
      <filename>hello.php</filename>
 +
      <filename>index.html</filename>
 +
      <filename>install.sql</filename>
 +
      <filename>uninstall.sql</filename>
 +
    </files>
 +
  </administration>
 +
  ...
 +
</source>
 +
Only the .sql files were of use and only during installation for our frontend view, the other two files have no content besides generating a blank page. Access your websites' file system at your hosting provider (or on your own server) and browse through the directories after installing the frontend com_hello component. You may have noticed that our Hello component is to be found twice:
 +
<root>/components/com_hello
 +
<root>/administrator/components/com_hello
  
<source lang="php"><?php
+
These two sub-directories link to the previously explained site-content and administration. Administrator interactions explicitly go via the administrator sub-directory, where guest or registered users will enter the default entrance on the root:
/**
+
<root>/index.php
* @package    Joomla.Tutorials
+
Administrative users will have to log in, and after logging in they will enter your site via:
* @subpackage Components
+
  <root>/administrator/index.php
* @link http://dev.joomla.org/component/option,com_jd-wiki/Itemid,31/id,tutorials:components/
 
  * @license    GNU/GPL
 
*/
 
  
// no direct access
+
With the different access points it is easy to grasp that with setting up the administrator section the naming conventions have no dependency with the site section. Whilst the MVC pattern is also applicable for the administrator section this implies that identical Controllers, Views and Models naming can (and sometimes must) be used as in the site section.
  
defined( '_JEXEC' ) or die( 'Restricted access' );
+
== MVC pattern interaction ==
 +
[[image:MVC joomla.png|frameless|right]]In [[Developing a Model-View-Controller Component - Part 1]] the figure on the right was used to explain the focus of the first three parts of this ''Developing a Model-View-Controller Component tutorial''. Now we will use this figure to explain how decisions are made on what is going to be displayed and how to manipulate this.
  
// Require the base controller
+
=== Example roll-out ===
 +
For explanation purposes an easy to grasp example will be used. A library has the main function of lending books to registered users. Simply laid out there are three tables:
 +
* users
 +
* books
 +
* relation
  
require_once( JPATH_COMPONENT.DS.'controller.php' );
+
Lets keep it all very simple. The users are addressed by Id and Name. The books are identified by Id and Title and the relation contains both Ids and the date of lending.
  
// Require specific controller if requested
+
[[image:Library Example.png|400px|frameless|center]]
if($controller = JRequest::getWord('controller')) {
 
    $path = JPATH_COMPONENT.DS.'controllers'.DS.$controller.'.php';
 
    if (file_exists($path)) {
 
        require_once $path;
 
    } else {
 
        $controller = '';
 
    }
 
}
 
 
 
// Create the controller
 
$classname    = 'HellosController'.$controller;
 
$controller  = new $classname( );
 
 
 
// Perform the Request task
 
$controller->execute( JRequest::getVar( 'task' ) );
 
 
 
// Redirect if set by the controller
 
$controller->redirect();
 
 
 
?></source>
 
 
 
The view and model that we will start with is the hellos view and the hellos model. We will start with the model.
 
 
 
==== The Hellos Model ====
 
 
 
The Hellos Model will be very simple. The only operation that we currently need is the ability to retrieve the list of hellos from the database. This operation will be implemented in a method called getData().
 
 
 
The JModel class has a built in protected method called _getList(). This method can be used to simplify the task of retrieving a list of records from the database. We simply need to pass it the query and it will return the list of records.
 
 
 
At a later point in time, we might want to use our query from within another method. Therefore, we will create a private method called _buildQuery() which will return the query that will be passed to _getList(). This makes it easier to change the query as well since it is localized in one place.
 
 
 
Therefore we need two methods in our class: getData() and _buildQuery().
 
 
 
_buildQuery() simply returns the query. It looks like:
 
 
 
<source  lang="php">/**
 
* Returns the query
 
* @return string The query to be used to retrieve the rows from the database
 
*/
 
function _buildQuery()
 
{
 
    $query = ' SELECT * '
 
          . ' FROM #__hello '
 
    ;
 
 
 
    return $query;
 
}</source>
 
 
 
getData() will obtain the query and retrieve the records from the database. Now it might happen that we need to retrieve this list of data twice in one page load. It would be a waste to have to query the database twice. Therefore, we will have this method store the data in a protected property so that on subsequent requests it can simply return the data it has already retrieved. This property will be called _data.
 
 
 
Here is the getData() method:
 
 
 
<source  lang="php">/**
 
* Retrieves the hello data
 
* @return array Array of objects containing the data from the database
 
*/
 
function getData()
 
{
 
    // Lets load the data if it doesn't already exist
 
    if (empty( $this->_data ))
 
    {
 
        $query = $this->_buildQuery();
 
        $this->_data = $this->_getList( $query );
 
    }
 
 
 
    return $this->_data;
 
}</source>
 
 
 
The completed model looks like:
 
 
 
<source lang="php"><?php
 
/**
 
* Hellos Model for Hello World Component
 
*
 
* @package    Joomla.Tutorials
 
* @subpackage Components
 
* @link http://dev.joomla.org/component/option,com_jd-wiki/Itemid,31/id,tutorials:components/
 
* @license        GNU/GPL
 
*/
 
 
 
// Check to ensure this file is included in Joomla!
 
defined('_JEXEC') or die();
 
 
 
jimport( 'joomla.application.component.model' );
 
 
 
/**
 
* Hello Model
 
*
 
* @package    Joomla.Tutorials
 
* @subpackage Components
 
*/
 
class HellosModelHellos extends JModel
 
{
 
    /**
 
    * Hellos data array
 
    *
 
    * @var array
 
    */
 
    var $_data;
 
  
    /**
+
The example is carefully chosen and will help in explaining the Joomla! architecture in more detail. The administrative side of our Hello component is not even that complex with only one table to manage. After the explanation of this Part it should be easy to follow the tutorial in the succeeding Parts.
    * Returns the query
 
    * @return string The query to be used to retrieve the rows from the database
 
    */
 
    function _buildQuery()
 
    {
 
        $query = ' SELECT * '
 
            . ' FROM #__hello '
 
        ;
 
        return $query;
 
    }
 
  
    /**
+
=== Mapping a Joomla! MVC component from the example ===
    * Retrieves the hello data
+
In this example we will assume that administrative actions (add, edit, delete) are tasks that are to be performed by the administrator. For the frontend user only the view of the Relation table is interesting ("when do I have to bring back the books?"). This example shows the entire list and ignores all privacy stuff that could be taken care of by letting registered users only see their own books. (''See'': [http://api.joomla.org/Joomla-Framework/User/JUser.html JUser object] for making user deviations in template module).
    * @return array Array of objects containing the data from the database
 
    */
 
    function getData()
 
    {
 
        // Lets load the data if it doesn't already exist
 
        if (empty( $this->_data ))
 
        {
 
            $query = $this->_buildQuery();
 
            $this->_data = $this->_getList( $query );
 
        }
 
  
        return $this->_data;
 
    }
 
}</source>
 
  
This file is saved as models/hellos.php.
+
Just like our frontend Hello component, for this library component only the default view is being used in the frontend. It lists the relational table, left joining the other two tables to obtain a human readable list of books with their corresponding due date.  
 +
Alice | One flew over ... | 12-aug-2009
 +
Alice | Celeb talk        | 12-aug-2009
 +
Mark  | Joomla!          | 15-aug-2009
  
==== The Hellos View ====
+
With respect to the administration part it is important to understand that we have one default and three dedicated views, each controlling three tasks:
 +
* <Component name default view>
 +
* User administration
 +
** Add
 +
** Change
 +
** Delete
 +
* Book administration
 +
** Add
 +
** Change
 +
** Delete
 +
* Relation administration
 +
** Add
 +
** Change
 +
** Delete
  
Now that we have a model to retrieve our data, we need to display it. This view will be fairly similar to the view from the site section as well.
+
==== Controllers ====
 +
The main controller of the admin section needs to differentiate between the different Adds, Changes or Deletes that are requested. This is taken care of by creating sub-controllers for each view for handling their specific tasks.
 +
<root>/administrator/controller.php
 +
<root>/administrator/controllers/users.php
 +
<root>/administrator/controllers/books.php
 +
<root>/administrator/controllers/relation.php
  
Just as our model was automatically instantiated in the site, so it is in the administrator. Methods that start with get in the model can be accessed using the get() method of the JView class. So our view has three lines: one to retrieve the data from the model, one to push the data into the template, and one to invoke the display method to display the output. Thus we have:
+
The controller is an important part of the MVC pattern. Not only does it take care of the requested tasks, it is also the initiator of instantiating the model with the same name and it is responsible for setting the view and the desired form for that view. The controller really justifies its name.  
  
<source lang="php"><?php
+
Within the controller it is good to make a difference between '''activating tasks''' (for example the edit selection from a menu) and '''resulting tasks''' (for example the result of an edit trigger is the posted data).
/**
 
* Hellos View for Hello World Component
 
*
 
* @package    Joomla.Tutorials
 
* @subpackage Components
 
* @link http://dev.joomla.org/component/option,com_jd-wiki/Itemid,31/id,tutorials:components/
 
* @license        GNU/GPL
 
*/
 
  
// Check to ensure this file is included in Joomla!
+
Typical controller functions look like:
defined('_JEXEC') or die();
+
<source lang="php">
 
+
function <activating task>() // <-- edit, add, delete
jimport( 'joomla.application.component.view' );
 
 
 
/**
 
* Hellos View
 
*
 
* @package    Joomla.Tutorials
 
* @subpackage Components
 
*/
 
class HellosViewHellos extends JView
 
 
{
 
{
     /**
+
     JRequest::setVar( 'view', '[<componentname> | users | books | relation ]' );
    * Hellos view display method
+
     JRequest::setVar( 'layout', 'default'  );    // <-- The default form is named here, but in
    * @return void
+
                                                  // some complex views, multiple layouts might
    **/
+
                                                  // be needed.
    function display($tpl = null)
 
    {
 
        JToolBarHelper::title( JText::_( 'Hello Manager' ), 'generic.png' );
 
        JToolBarHelper::deleteList();
 
        JToolBarHelper::editListX();
 
        JToolBarHelper::addNewX();
 
 
 
        // Get data from the model
 
        $items =& $this->get( 'Data');
 
 
 
        $this->assignRef( 'items', $items );
 
 
 
        parent::display($tpl);
 
    }
 
}</source>
 
 
 
This file is saved as views/hellos/view.html.php.
 
 
 
==== The Hellos Template ====
 
 
 
The template will take the data pushed into it from the view and produce the output. We will display our output in a simple table. While the frontend template was very simple, in the administrator we will need a minimal amount of extra logic to handle looping through the data.
 
 
 
Here is our template:
 
 
 
 
 
<source lang="php"><?php defined('_JEXEC') or die('Restricted access'); ?>
 
<form action="index.php" method="post" name="adminForm">
 
<div id="editcell">
 
     <table class="adminlist">
 
    <thead>
 
        <tr>
 
            <th width="5">
 
                <?php echo JText::_( 'ID' ); ?>
 
            </th>
 
            <th>
 
                <?php echo JText::_( 'Greeting' ); ?>
 
            </th>
 
        </tr>           
 
    </thead>
 
    <?php
 
    $k = 0;
 
    for ($i=0, $n=count( $this->items ); $i < $n; $i++)
 
    {
 
        $row =& $this->items[$i];
 
        ?>
 
        <tr class="<?php echo "row$k"; ?>">
 
            <td>
 
                <?php echo $row->id; ?>
 
            </td>
 
            <td>
 
                <?php echo $row->greeting; ?>
 
            </td>
 
        </tr>
 
        <?php
 
        $k = 1 - $k;
 
    }
 
    ?>
 
    </table>
 
</div>
 
 
 
<input type="hidden" name="option" value="com_hello" />
 
<input type="hidden" name="task" value="" />
 
<input type="hidden" name="boxchecked" value="0" />
 
<input type="hidden" name="controller" value="hello" />
 
 
 
</form></source>
 
 
 
This template is saved as views/hellos/tmpl/default.php.
 
 
 
You will notice that our output is enclosed in a form. Though this is not necessary now, it will be soon.
 
 
 
We have now completed the basic part of the first view. We have added five files to the admin section of our component:
 
 
 
  * admin.hello.php
 
 
 
  * controller.php
 
 
 
  * models/hellos.php
 
 
 
  * views/hellos/view.html.php
 
 
 
  * views/hellos/tmpl/default.php
 
 
 
You can now add these files to the XML install file and give it a try!
 
 
 
===== Adding Functionality =====
 
 
 
So far our administrator section is pretty useless. It doesn't really do anything - all it does is display the entries that we have in our database.
 
 
 
In order to make it useful, we need to add some buttons and links.
 
 
 
==== The Toolbar ====
 
 
 
You may have noticed the toolbar that appears at the top of other Joomla! component administrator panels. Our component needs one as well. Joomla! makes this very easy to do. We will add buttons Delete records, Edit records, and create New records. We will also add a title that will be displayed on our toolbar.
 
 
 
This is done by adding code to the view. To add the buttons, we use static methods from the Joomla! JToolBarHelper class. The code looks like:
 
 
 
 
 
<source lang="php">JToolBarHelper::title(  JText::_( 'Hello Manager' ), 'generic.png' );
 
JToolBarHelper::deleteList();
 
JToolBarHelper::editListX();
 
JToolBarHelper::addNewX();</source>
 
 
 
These three methods will create the appropriate buttons. The deleteList() method can optionally take up to three parameters - the first parameter is a string to display to the user to confirm that they want to delete the records. The second is the task that should be sent with the query (the default is 'remove'), and the third is the text that should be displayed below the button.
 
 
 
The editListX() and addNewX() methods can each take two optional parameters. The first is the task (which are by default edit and add, respectively), and the second is the text that should be displayed below the button.
 
 
 
  ''*You may have noticed the use of the JText::_ method in the template before and here as well. This is a handy function that makes component translation much easier. The JText::_ method will look up the string in your component language file and return the translated string. If not translation is found, it will return the string that you passed it. If you want to translate your component into another language, all you have to do is create a language file that will map the strings within the quotes to the translated version of the string.''
 
 
 
==== Checkboxes and Links ====
 
 
 
We now have buttons. Two of those buttons operate on existing records. But how do we know which records to operate on? We have to let the user tell us. To do this, we need to add checkboxes to our table so that the user can select certain records. This is done in our template.
 
 
 
In order to the add the checkboxes, we need to add an extra column into our table. We will add the column in between the two that we already have.
 
 
 
In the header of the column, we will add a checkbox which can be used to toggle all the boxes below it on or off:
 
 
 
 
 
<source lang="php"><th width="20">
 
    <input type="checkbox" name="toggle" value="" onclick="checkAll(<?php echo count( $this->items ); ?>);" />
 
</th></source>
 
 
 
The Javascript checkAll function is a function that is built into the Joomla! base Javascript package that provides the functionality that we want here.
 
 
 
Now we need to add the checkboxes into the individual rows. Joomla!'s JHTML class has a method, JHTML::_(), which will generate our checkbox for us. We will add the following line to our loop:
 
 
 
 
 
<source lang="php">$checked    = JHTML::_( 'grid.id', $i, $row->id );</source>
 
 
 
after the line:
 
 
 
 
 
<source lang="php">$row =& $this->items[$i];</source>
 
 
 
Then we will add a cell in between the two that we already have:
 
 
 
 
 
<source lang="php"><td>
 
     <?php echo $checked; ?>
 
</td></source>
 
 
 
It can be cumbersome to have to check the box that we want to edit and then move up and click the edit button. Therefore, we will add a link that it will go straight to the greeting's edit form. We will add the following line after the call to the JHTML::_() method to generate the link HTML:
 
 
 
 
 
<source lang="php">$link = JRoute::_( 'index.php?option=com_hello>controller=hello>task=edit>cid[]='. $row->id );</source>
 
 
 
And we include the link in the cell showing the greeting text:
 
 
 
 
 
<source lang="php"><td>
 
    <a href="<?php echo $link; ?>"><?php echo $row->greeting; ?></a>
 
</td></source>
 
 
 
You will notice that this link points to the hello controller. This controller will handle the data manipulation of our greetings.
 
 
 
If you recall from above, we had four hidden input fields at the bottom of our form. The first input field was named 'option'. This field is necessary so that we stay in our component. The second input field was task. This form property gets set when one of the buttons in the toolbar is clicked. A Javascript error will result and the buttons will not work if this input field is omitted. The third input field is the boxchecked field. This field keeps track of the number of boxes that are checked. The edit and delete buttons will check to ensure that this is greater than zero and will not allow the form to be submitted if it is not. The fourth input field is the controller field. This is used to specify that tasks fired from this form will be handled by the hello controller.
 
 
 
Here is the code for the completed default.php file:
 
 
 
 
 
<source lang="php"><?php defined('_JEXEC') or die('Restricted access'); ?>
 
<form action="index.php" method="post" name="adminForm">
 
<div id="editcell">
 
    <table class="adminlist">
 
    <thead>
 
        <tr>
 
            <th width="5">
 
                <?php echo JText::_( 'ID' ); ?>
 
            </th>
 
            <th>
 
                <?php echo JText::_( 'Greeting' ); ?>
 
            </th>
 
        </tr>           
 
    </thead>
 
    <?php
 
    $k = 0;
 
    for ($i=0, $n=count( $this->items ); $i < $n; $i++)
 
    {
 
        $row =& $this->items[$i];
 
        ?>
 
        <tr class="<?php echo "row$k"; ?>">
 
            <td>
 
                <?php echo $row->id; ?>
 
            </td>
 
            <td>
 
                <?php echo $row->greeting; ?>
 
            </td>
 
        </tr>
 
        <?php
 
        $k = 1 - $k;
 
    }
 
    ?>
 
    </table>
 
</div>
 
 
 
<input type="hidden" name="option" value="com_hello" />
 
<input type="hidden" name="task" value="" />
 
<input type="hidden" name="boxchecked" value="0" />
 
<input type="hidden" name="controller" value="hello" />
 
 
 
</form></source>
 
 
 
Our hellos view is now complete. You can try out the component now to see the results.
 
 
 
The component can be downloaded at: [[http://dev.joomla.org/components/com_jd-wiki/data/media/components/com_hello4a.zip|com_hello4a.zip]]
 
 
 
===== Getting Down and Dirty: Doing the Real Work =====
 
 
 
Now that the Hellos view is done, it is time to move to the Hello view and model. This is where the real work will get done.
 
 
 
==== The Hello Controller ====
 
 
 
Our default controller just isn't going to cut it when it comes to doing work - all it is capable of doing is displaying views.
 
 
 
We need to be able to handle the tasks that we are launching from the Hellos view: add, edit and remove.
 
 
 
Add and edit are essentially the same task: they both display a form to the user that allows a greeting to be edited. The only difference is that new displays a blank form, and edit displays a form with data already in it. Since they are similar, we will map the add task onto the edit task handler. This is specified in our constructor:
 
 
 
 
 
<source lang="php">/**
 
* constructor (registers additional tasks to methods)
 
* @return void
 
*/
 
function __construct()
 
{
 
    parent::__construct();
 
 
 
    // Register Extra tasks
 
    $this->registerTask( 'add'  ,    'edit' );
 
}</source>
 
 
 
The first parameter of JController::registerTask is the task to map, and the second is the method to map it to.
 
 
 
We will start with handling the edit task. The controller's job is fairly simple for the edit task. All it has to do is specify the view and layout to load (the hello view and the form layout). We will also tell Joomla! to disable the mainmenu while we are editing our greeting. This prevents users from leaving unsaved records open.
 
 
 
Our edit task handler looks like:
 
 
 
 
 
<source lang="php">/**
 
* display the edit form
 
* @return void
 
*/
 
function edit()
 
{
 
    JRequest::setVar( 'view', 'hello' );
 
    JRequest::setVar( 'layout', 'form'  );
 
    JRequest::setVar('hidemainmenu', 1);
 
 
 
 
     parent::display();
 
     parent::display();
}</source>
+
}
 
 
==== The Hello View ====
 
 
 
The Hello view will display a form which will allow the user to edit a greeting. The display method if the hello view has to do a few simple tasks:
 
 
 
  * retrieve the data from the model
 
 
 
  * create the toolbar
 
 
 
  * pass the data into the template
 
 
 
  * invoke the display() method to render the template
 
 
 
This becomes a bit more complicated because the one view handles both the edit and add tasks. In our toolbar we want the user to know what whether they are adding or editing, so we have to determine which task was fired.
 
 
 
Since we are already retrieving the record that we want to display from the model, we can use this data to determine what task was fired. If the task was edit, then the id field of our record will have been set. If the task was new, then it will not have been set. This can be used to determine if we have a new record or an existing record.
 
 
 
We will add two buttons to the toolbar: save and cancel. Though the functionality will be the same, we want to display different buttons depending on whether it is a new or existing record. If it is a new record, we will display cancel. If it already exists, we will display close.
 
 
 
Thus our display method looks like this:
 
 
 
 
<source lang="php">/**
 
* display method of Hello view
 
* @return void
 
**/
 
function display($tpl = null)
 
{
 
    //get the hello
 
    $hello        =& $this->get('Data');
 
    $isNew        = ($hello->id < 1);
 
 
 
    $text = $isNew ? JText::_( 'New' ) : JText::_( 'Edit' );
 
    JToolBarHelper::title(  JText::_( 'Hello' ).': <small><small>[ ' . $text.' ]</small></small>' );
 
    JToolBarHelper::save();
 
    if ($isNew)  {
 
        JToolBarHelper::cancel();
 
    } else {
 
        // for existing items the button is renamed `close`
 
        JToolBarHelper::cancel( 'cancel', 'Close' );
 
    }
 
 
 
    $this->assignRef('hello', $hello);
 
    parent::display($tpl);
 
}</source>
 
 
 
==== The Hello Model ====
 
 
 
Our view needs data. Therefore, we need to create a model to model a hello.
 
 
 
Our model will have two properties: _id and _data. _id will hold the id of the greeting and data will hold the data.
 
  
We will start with a constructor, which will attempt to retrieve the id from the query:
+
function <resulting task>()  // <-- save, remove
 
 
 
 
<source lang="php">/**
 
* Constructor that retrieves the ID from the request
 
*
 
* @access    public
 
* @return    void
 
*/
 
function __construct()
 
 
{
 
{
    parent::__construct();
+
$model = $this->getModel('[<componentname> | users | books | relation ]');
 +
if(!$model->action() ) {    // <-- action could be delete() or store()
 +
$msg = JText::_( 'Error: Could not perform action' );
 +
} else {
 +
$msg = JText::_( 'Action executed' );
 +
}
  
    $array = JRequest::getVar('cid',  0, '', 'array');
+
$this->setRedirect( 'index.php?option=<componentname>', $msg );
    $this->setId((int)$array[0]);
 
}</source>
 
 
 
The JRequest::getVar() method is used to retrieve data from the request. The first parameter is the name of the form variable. The second parameter is the default value to assign if there is no value found. The third parameter is the name of the hash to retrieve the value from (get, post, etc), and the last value is the data type that should be forced on the value.
 
 
 
Our constructor will take the first value from the cid array and assign it to the id.
 
 
 
Our setId() method can be used to set our id. Changing the id that our model points to will mean the id points to the wrong data. Therefore, when we set the id, we will clear the data property:
 
 
 
 
<source lang="php">/**
 
* Method to set the hello identifier
 
*
 
* @access    public
 
* @param    int Hello identifier
 
* @return    void
 
*/
 
function setId($id)
 
{
 
    // Set id and wipe data
 
    $this->_id        = $id;
 
    $this->_data    = null;
 
}</source>
 
 
 
Finally, we need a method to retrieve our data: getData()
 
 
 
getData will check if the _data property has already been set. If it has, it will simply return it. Otherwise, it will load the data from the database.
 
 
 
 
<source lang="php">/**
 
* Method to get a hello
 
* @return object with data
 
*/
 
 
 
function &getData()
 
{
 
    // Load the data
 
    if (empty( $this->_data )) {
 
        $query = ' SELECT * FROM #__hello '.
 
                ' WHERE id = '.$this->_id;
 
        $this->_db->setQuery( $query );
 
        $this->_data = $this->_db->loadObject();
 
    }
 
    if (!$this->_data) {
 
        $this->_data = new stdClass();
 
        $this->_data->id = 0;
 
        $this->_data->greeting = null;
 
    }
 
    return $this->_data;
 
}</source>
 
 
 
==== The Form ====
 
 
 
Now all that is left is to create the form that the data will go into. Since we specified our layout as form, the form will go in a file in the tmpl directory of the hello view called form.php:
 
 
 
 
<source lang="php"><?php defined('_JEXEC') or die('Restricted access'); ?>
 
 
 
<form action="index.php" method="post" name="adminForm" id="adminForm">
 
<div class="col100">
 
    <fieldset class="adminform">
 
        <legend><?php echo JText::_( 'Details' ); ?></legend>
 
        <table class="admintable">
 
        <tr>
 
            <td width="100" align="right" class="key">
 
                <label for="greeting">
 
                    <?php echo JText::_( 'Greeting' ); ?>:
 
                </label>
 
            </td>
 
            <td>
 
                <input class="text_area" type="text" name="greeting" id="greeting" size="32" maxlength="250" value="<?php echo $this->hello->greeting;?>" />
 
            </td>
 
        </tr>
 
    </table>
 
    </fieldset>
 
</div>
 
 
 
<div class="clr"></div>
 
 
 
<input type="hidden" name="option" value="com_hello" />
 
<input type="hidden" name="id" value="<?php echo $this->hello->id; ?>" />
 
<input type="hidden" name="task" value="" />
 
<input type="hidden" name="controller" value="hello" />
 
</form></source>
 
 
 
Notice that in addition to the input field, there is a hidden field for the id. The user doesn't need to edit the id (and shouldn't), so we silently pass it along in the form.
 
 
 
==== Implementing the Functionality ====
 
 
 
So far, our controller only handles two tasks: edit and new. However, we also have buttons to save, delete and cancel records. We need to write code to handle and perform these tasks.
 
 
 
=== Saving a Record ===
 
 
 
The logical next step is to implement the functionality to save a record. Normally, this would require some switches and logic to handle various cases, such as the difference between creating a new record (an INSERT query), and updating an existing query (an UPDATE query). Also, there are complexities involved in getting the data from the form and putting it into the query.
 
 
 
The Joomla! framework takes care of a lot of this for you. The JTable class makes it easy to manipulate records in the database without having to worry about writing the SQL code that lies behind these updates. It also makes it easy to transfer data from an HTML form into the database.
 
 
 
== Creating the Table Class ==
 
 
 
The JTable class is an abstract class from which you can derive child classes to work with specific tables. To use it, you simply create a class that extends the JTable class, add your database fields as properties, and override the constructor to specify the name of the table and the primary key.
 
 
 
Here is our JTable class:
 
 
 
 
<source lang="php"><?php
 
/**
 
* Hello World table class
 
*
 
* @package    Joomla.Tutorials
 
* @subpackage Components
 
* @link http://dev.joomla.org/component/option,com_jd-wiki/Itemid,31/id,tutorials:components/
 
* @license        GNU/GPL
 
*/
 
 
 
// no direct access
 
defined('_JEXEC') or die('Restricted access');
 
 
 
/**
 
* Hello Table class
 
*
 
* @package    Joomla.Tutorials
 
* @subpackage Components
 
*/
 
class TableHello extends JTable
 
{
 
    /**
 
    * Primary Key
 
    *
 
    * @var int
 
    */
 
    var $id = null;
 
 
 
    /**
 
    * @var string
 
    */
 
    var $greeting = null;
 
 
 
    /**
 
    * Constructor
 
    *
 
    * @param object Database connector object
 
    */
 
    function TableHello( &$db ) {
 
        parent::__construct('#__hello', 'id', $db);
 
    }
 
 
}
 
}
?></source>
+
</source>
 +
A controller takes care of all tasks for that dedicated controller. After completing a resulting task the module will return to the main administration entrance point for that component, the main controller with the default view. Activating tasks enforce a new view with a form to display after first defining it.
  
You will see here that we have defined our two fields: the id field and the greeting field. Then we have defined a constructor, which will call the constructor of the parent class and pass it the name of the table (hello), the name of the field which is the primary key (id), and the database connector object.
+
The explicit definition of the form within a view might raise some eyebrows but our examples are too simple. For the general understanding and consistency this field should mostly be ''default''. In complex views multiple forms could be defined within one view.
  
This file should be called hello.php and it will go in a directory called tables in the administrator section of our component.
+
==== Models ====
 +
The Controllers interact with their equally named Model counter part. In the frontend view the Model was only used to retrieve data. The backend has more controllers and thus also more model files. The backend model files not only are responsible for delivering data to the viewer but also take care of tasks initiated from the controller. A good model contains all actions required to manage a single table in the database.
 +
<root>/administrator/models/<componentname>.php
 +
<root>/administrator/models/users.php
 +
<root>/administrator/models/books.php
 +
<root>/administrator/models/relation.php
  
== Implementing the Function in our Model ==
+
==== Views ====
 +
Separate views are of course also required. For views and subsequent forms no forced naming conventions are required (linking to views is taken care of in the controller). In the following listing the Administrative tasks are identified as a subset for the different views. This choice is totally random and maybe even non-logical but that doesn't matter for the explanation. Just for example purposes I added also a different view, a delete view, that could be used for all the deletes for all administrative tasks asking an "Are you sure" display.
  
We are now ready to add the method to the model which will save our record. We will call this method store. Our store() method will do three things: bind the data from the form to the TableHello object, check to ensure that the record is properly formed, and store the record in the database.
+
<root>/administrator/views/<componentname>/view.html.php + .../tmpl/default.php
 +
<root>/administrator/views/users/view.html.php          + .../tmpl/default.php
 +
<root>/administrator/views/books/view.html.php          + .../tmpl/default.php
 +
<root>/administrator/views/relation/view.html.php        + .../tmpl/default.php
 +
<root>/administrator/views/delete/view.html.php          + .../tmpl/default.php
  
Our method looks like:
+
''Note'': In general it is good practice to maintain one form per view because the view.html.php still has to deliver the content. With some basic logic you can enable, disable certain content but if this logic is becoming too complex start considering splitting up the view.
  
+
''Note'': Sharing template parts amongst the different views (for uniform layouting of headers and titles of your component) can be done using the PHP <code>include / require;</code>. There is one slight problem ... how to make the logical reference? In my modules I have a collector bin for general to use sniplets. Because it involved the views and forms I put this general bin in the views directory. The variable $pathToGeneralView needs to be defined somewhere in the first lines of your file and you have to make sure that the logical reference path is correct (the '..'s). In the following example the files marked with a '*' use the following code:
<source lang="php">/**
 
* Method to store a record
 
*
 
* @access    public
 
* @return    boolean    True on success
 
*/
 
function store()
 
{
 
    $row =& $this->getTable();
 
  
    $data = JRequest::get( 'post' );
+
./com_compname/views/general/navigate.header.php  <-- sniplet code for the header
    // Bind the form fields to the hello table
+
./com_compname/views/general/navigate.footer.php  <-- sniplet code for the footer
    if (!$row->bind($data)) {
+
./com_compname/views/mngtable1/view.html.php
        $this->setError($this->_db->getErrorMsg());
+
./com_compname/views/mngtable1/tmpl/default.php *
        return false;
+
./com_compname/views/mngtable2/view.html.php
    }
+
./com_compname/views/mngtable2/tmpl/default.php *
  
    // Make sure the hello record is valid
+
<source lang=php>
    if (!$row->check()) {
+
$pathToGeneralView = strchr(dirname(__FILE__), dirname($_SERVER['SCRIPT_NAME']));
        $this->setError($this->_db->getErrorMsg());
+
$pathToGeneralView = str_replace(dirname($_SERVER['SCRIPT_NAME']),'.',$pathToGeneralView );
        return false;
+
$pathToGeneralView = $pathToGeneralView . "/../../general/";  <-- returning path from current position.
    }
+
...
 +
<?php require_once $pathToGeneralView . 'navigate.header.php'; ?>
 +
<P>Do something   
 +
<?php require_once $pathToGeneralView . 'navigate.footer.php'; ?>
 +
</source>
 +
Another Way to do the same thing:
 +
<source lang=php>
 +
$pathToGeneralView = JPATH_COMPONENT_ADMINISTRATOR. "/views/general/";  <-- will return 'path/Joomla/administrator/components/com_example/views/general/'
 +
...
 +
<?php require_once $pathToGeneralView . 'navigate.header.php'; ?>
 +
<P>Do something   
 +
<?php require_once $pathToGeneralView . 'navigate.footer.php'; ?>
 +
</source>
  
    // Store the web link table to the database
+
''Note'': Giving the forms logical instead of the ''default'' naming is of course handy when having a lot of different views. Also, having that many ''default'' forms can make it difficult to determine the context. On the other hand, the view.html.php cannot be renamed, and one is always forced to look at the directory name for the view.
    if (!$row->store()) {
 
        $this->setError($this->_db->getErrorMsg());
 
        return false;
 
    }
 
  
    return true;
+
=== Essential Interaction Parameters ===
}</source>
+
Everything is in place:
 +
* main and dedicated controllers;
 +
* main and dedicated models;
 +
* different views and their forms.
  
This method gets added to the hello model.
+
Just one big question remains: '''How to use them'''!
  
The method takes one parameter, which is an associative array of data that we want to store in the database. This can easily be retrieved from the request as will be seen later.
+
Three parameters are mandatory for letting Joomla! do its job:
 +
* option
 +
* controller
 +
* task
  
You will see that the first line retrieves a reference to our JTable object. If we name our table properly, we don't have to specify its name - the JModel class knows where to find it. You may recall that we called our table class TableHello and put it in a file called hello.php in the tables directory. If you follow this convention, the JModel class can create your object automatically.
+
These three parameters are almost self explaining ;). The ''option'' part when developing a component is easy, always assign your component name to it. For component development consider this one as a constant, of course the Joomla! engine has more options than only components.
  
The second line will retrieve the data from the form. The JRequest class makes this very easy. In this case, we are retrieving all of the variables that were submitted using the 'POST' method. These will be returned as an associative array.
+
The ''controller'' and ''task'' parameters can be manipulated within your component anyway you want it to.  
  
The rest is easy - we bind, check and store. The bind() method will copy values from the array into the corresponding property of the table object. In this case, it will take the values of id and greeting and copy them to our TableHello object.
+
==== How it all works together ====
 +
Looking at the simplified MVC picture Joomla! the logical flow of interaction goes the following way:
 +
# What is my entrance point?
 +
#*The Joomla! engine discovers a logged in administrator and sets the entrance point to <root>/administrator/index.php otherwise it will go to the <root>/index.php entrance.
 +
# What option is requested?
 +
#*The Joomla! engine reads the option variable and discovers that a component named <componentname> is requested. The entrance point becomes: <root>/administrator/components/com_<componentname>/<componentname>.php
 +
# Is there need to access a dedicated controller?
 +
#* The Joomla! engine reads the controller variable and discovers that a dedicated controller is required: <root>/administrator/components/com_<componentname>/controllers/<dedicatedcontroller>.php
 +
# Is there a task that needs to be addressed?
 +
#* The identified controller is handed the task value as parameter.
 +
# The Model is derived from the controller and instantiated.
 +
# The View and Form are set in the controller and initiated to become active.
  
The check() method will perform data verification. In the JTable() class, this method simply returns true. While this doesn't provide any value for us currently, by calling this method we make it possible to do data checking using our TableHello class in the future. This method can be overridden in our TableHello class with a method that performs the appropriate checks.
+
=== How to add interaction ===
 +
Within HTML there are two common ways to interact with Joomla!:
 +
# reference to a link
 +
# form submission post / get
  
The store() method will take the data that is in the object and store it in the database. If the id is 0, it will create a new record (INSERT), otherwise, it will update the existing record (UPDATE).
+
==== Link reference for the Joomla! engine ====
 +
Remember the '''activating tasks''' and '''resulting tasks''' mentioned earlier? Most activating tasks are initiated by a link. In case of the Library example the site section overview could be copied to the admin section. This default view will now be extended and every cell will become a link for editing the specific database element.
  
== Adding the Task to the Controller ==
+
Using the Library example, the template PHP code without looping control will contain the following code:
 +
<source lang=php>
 +
$link = JRoute::_( 'index.php?option=com_library&controller=users&task=edit&cid='. $row->idu );
 +
echo "<td><a href='$link'>{$row->name}</a></td>";
 +
$link = JRoute::_( 'index.php?option=com_library&controller=books&task=edit&cid='. $row->idb );
 +
echo "<td><a href='$link'>{$row->title}</a></td>";
 +
$link = JRoute::_( 'index.php?option=com_library&controller=relation&task=edit&cid='. $row->idr );
 +
echo "<td><a href='$link'>{$row->date}</a></td>";
 +
</source>
  
We are now ready to add our task to the controller. Since the task that we are firing is called 'save', we must call our method 'save'. This is simple:
+
Within each clickable field the three mandatory parameters to manipulate Joomla! can be identified. In addition there is one user parameter for handling the correct index in the controller task (cid). These parameter are separated by '&'. Do not use spaces in your variables, as this might screw-up parameter handling in certain browsers. After looping, all text entries will be clickable and trigger the corresponding controller with the correct row id in the associated table.
  
   
+
  [Alice] | [One flew over ...] | [12-aug-2009]
<source lang="php">/**
+
  [Alice] | [Celeb talk]        | [12-aug-2009]
  * save a record (and redirect to main page)
+
  [Mark] | [Joomla!]          | [15-aug-2009]
  * @return void
 
  */
 
function save()
 
{
 
    $model = $this->getModel('hello');
 
  
    if ($model->store()) {
+
==== Posting Form Data to the Joomla! Engine ====
        $msg = JText::_( 'Greeting Saved!' );
+
After being initiated by an activating task, an input form view might be the result. The snippet of code below could be the result of clicking the first cell of the default component view that is clicked for editing ([Alice]:cid=3).
    } else {
 
        $msg = JText::_( 'Error Saving Greeting' );
 
    }
 
  
    // Check the table in so it can be edited.... we are done with it anyway
+
<source lang="php">
    $link = 'index.php?option=com_hello';
+
<form action="index.php" method="post">
    $this->setRedirect($link, $msg);
+
  <input type="text" name="username" id="username" size="32" maxlength="250" value="<?php echo $this->user->name;?>" />
}</source>
 
  
All we do is get our model and invoke the store() method. Then we use the setRedirect() method to redirect back to our list of greetings. We also pass a message along, which will be displayed at the top of the page.
+
  <input type="submit" name="SubmitButton" value="Save" />
  
[[Image:-message.png|frame|none|The message that was passed is displayed at the top of the page.]]
+
  <input type="hidden" name="option" value="com_library" />                  // <-- mandatory
==== Deleting a Record ====
+
  <input type="hidden" name="controller" value="hello" />                    // <-- mandatory
 +
  <input type="hidden" name="task" value="save" />                          // <-- mandatory
 +
  <input type="hidden" name="id" value="<?php echo $this->user->id; ?>" />  // <-- user parameter, index in database for [Alice]
 +
</form>
 +
</source>
  
=== Implementing the Function in the Model ===
+
The three Joomla! mandatory parameters are placed as hidden in the form. Hidden parameters are not shown in any way but will be added to the posting data.
 
 
In the model, we will retrieve the list of IDs to delete and call the JTable class to delete them. Here it is:
 
 
 
 
<source lang="php">/**
 
* Method to delete record(s)
 
*
 
* @access    public
 
* @return    boolean    True on success
 
*/
 
function delete()
 
{
 
    $cids = JRequest::getVar( 'cid', array(0), 'post', 'array' );
 
    $row =& $this->getTable();
 
 
 
    foreach($cids as $cid) {
 
        if (!$row->delete( $cid )) {
 
            $this->setError( $row->getErrorMsg() );
 
            return false;
 
        }
 
    }
 
 
 
    return true;
 
}</source>
 
 
 
We invoke the JRequest::getVar() method to get the data from the request, then we invoke the $row->delete() method to delete each row. By storing errors in the model we make it possible to retrieve them later if we so choose.
 
 
 
=== Handling the Remove Task in the Controller ===
 
 
 
This is similar to the save() method which handled the save task:
 
 
 
 
<source lang="php">/**
 
* remove record(s)
 
* @return void
 
*/
 
function remove()
 
{
 
    $model = $this->getModel('hello');
 
    if(!$model->delete()) {
 
        $msg = JText::_( 'Error: One or More Greetings Could not be Deleted' );
 
    } else {
 
        $msg = JText::_( 'Greeting(s) Deleted' );
 
    }
 
 
 
    $this->setRedirect( 'index.php?option=com_hello', $msg );
 
}</source>
 
 
 
==== Cancelling the Edit Operation ====
 
 
 
To cancel the edit operation, all we have to do is redirect back to the main view:
 
 
 
 
<source lang="php">/**
 
* cancel editing a record
 
* @return void
 
*/
 
function cancel()
 
{
 
    $msg = JText::_( 'Operation Cancelled' );
 
    $this->setRedirect( 'index.php?option=com_hello', $msg );
 
}</source>
 
  
===== Conclusion =====
+
''Tip'': when debugging this form, replace in the form tag <code>method="post"</code> temporarily with <code>method="get"</code>. All posted parameters will be shown in the URL of your browser. If the module is working undo this change. For one reason it looks sharper without all the parameters being shown in the URL and you avoid motivating people to manipulate the browser URL themselves. Another reason is more technical and the simple explanation is that post methods (i.e. method="post") can contain more (complex) data. There is a third reason for using <code>method="post"</code> in form processing, and that is to increase security and prevent [http://en.wikipedia.org/wiki/Cross-site_request_forgery CSRF] attacks on your site. <code>method="post"</code> should always be used when the resulting operation will modify the database.
  
We have now implemented a basic backend to our component. We are now able to edit the entries that are viewed in the frontend. We have demonstrated the interaction between models, views and controllers. We have shown how the JTable class can be extended to provide easy access to tables in the database. It can also be seen how the JToolBarHelper class can be used to create button bars in components to present a standardized look between components.
+
''Remark'': In some developed modules you may notice that developers have also added the ''view'' parameter. This is bad programming whilst the controller(s) should take care of the ''view'' and the ''form''.
  
===== Contributors =====
+
== Conclusion ==
  
  * staalanden
+
The use of the three mandatory parameters and the different access points are clarified. Let's do something with this knowledge and extend the Hello component to the administrative section in the succeeding articles of this tutorial.
  
===== Download =====
+
== Contributors ==
 +
* staalanden
 +
* jamesconroyuk
  
The component can be downloaded at: [[http://dev.joomla.org/components/com_jd-wiki/data/media/components/com_hello4.zip|com_hello4.zip]]
+
[[Category:Component Development]]

Latest revision as of 08:34, 9 May 2013

The "J1.5" namespace is an archived namespace. This page contains information for a Joomla! version which is no longer supported. It exists only as a historical reference, it will not be improved and its content may be incomplete and/or contain broken links.

Introduction[edit]

In the first three Parts, we have developed a MVC component that retrieves its data from a table in the database. Currently, there is no way to add data to the database except to do it manually using another tool. In the next Parts of this tutorial, we will develop an administrator section for our component which will make it possible to manage the entries in the database.

This Part, Part 4 - Creating an Administrator Interface, will be an article with no new source code for our Hello component but will describe some basic details and in-depth explanation of the MVC pattern. This intermediate chapter is not required to complete the Hello model so if you think you understand the basics continue with Developing a Model-View-Controller Component - Part 5 - Basic Backend Framework.

In the frontend solution (site section, parts 1,2 and 3) we developed the first part of our component. The frontend solution is based upon default Controllers, Views and Templates and you were "taken by the hand" and "left to trust" the default handling of the code. This is going to change in the Backend or Administration section of our Hello component ( parts 5 and 6) - we will have to develop all of the code that manages the application flow.

Site / Admin[edit]

Joomla! is a content management system. The frontend is used for presenting the users with content and allows certain logged in users to manipulate the content. The backend is responsible for administering the website framework (structuring / managing / controlling / maintaining). This division between (frontend) site-content and (backend) administration is a fundamental aspect of the Joomla! architecture.

Entrance points[edit]

From the XML file of our frontend example it was already obvious that there would be an administration part:

<?xml version="1.0" encoding="utf-8"?>
  ...
  <administration>
    <!--  Administration Menu Section --> 
    <menu>Hello World!</menu> 
    <!--  Administration Main File Copy Section --> 
    <files folder="admin">
      <filename>hello.php</filename> 
      <filename>index.html</filename> 
      <filename>install.sql</filename> 
      <filename>uninstall.sql</filename> 
    </files>
  </administration>
  ...

Only the .sql files were of use and only during installation for our frontend view, the other two files have no content besides generating a blank page. Access your websites' file system at your hosting provider (or on your own server) and browse through the directories after installing the frontend com_hello component. You may have noticed that our Hello component is to be found twice:

<root>/components/com_hello
<root>/administrator/components/com_hello

These two sub-directories link to the previously explained site-content and administration. Administrator interactions explicitly go via the administrator sub-directory, where guest or registered users will enter the default entrance on the root:

<root>/index.php

Administrative users will have to log in, and after logging in they will enter your site via:

<root>/administrator/index.php

With the different access points it is easy to grasp that with setting up the administrator section the naming conventions have no dependency with the site section. Whilst the MVC pattern is also applicable for the administrator section this implies that identical Controllers, Views and Models naming can (and sometimes must) be used as in the site section.

MVC pattern interaction[edit]

MVC joomla.png

In Developing a Model-View-Controller Component - Part 1 the figure on the right was used to explain the focus of the first three parts of this Developing a Model-View-Controller Component tutorial. Now we will use this figure to explain how decisions are made on what is going to be displayed and how to manipulate this.

Example roll-out[edit]

For explanation purposes an easy to grasp example will be used. A library has the main function of lending books to registered users. Simply laid out there are three tables:

  • users
  • books
  • relation

Lets keep it all very simple. The users are addressed by Id and Name. The books are identified by Id and Title and the relation contains both Ids and the date of lending.

Library Example.png

The example is carefully chosen and will help in explaining the Joomla! architecture in more detail. The administrative side of our Hello component is not even that complex with only one table to manage. After the explanation of this Part it should be easy to follow the tutorial in the succeeding Parts.

Mapping a Joomla! MVC component from the example[edit]

In this example we will assume that administrative actions (add, edit, delete) are tasks that are to be performed by the administrator. For the frontend user only the view of the Relation table is interesting ("when do I have to bring back the books?"). This example shows the entire list and ignores all privacy stuff that could be taken care of by letting registered users only see their own books. (See: JUser object for making user deviations in template module).


Just like our frontend Hello component, for this library component only the default view is being used in the frontend. It lists the relational table, left joining the other two tables to obtain a human readable list of books with their corresponding due date.

Alice | One flew over ... | 12-aug-2009
Alice | Celeb talk        | 12-aug-2009
Mark  | Joomla!           | 15-aug-2009

With respect to the administration part it is important to understand that we have one default and three dedicated views, each controlling three tasks:

  • <Component name default view>
  • User administration
    • Add
    • Change
    • Delete
  • Book administration
    • Add
    • Change
    • Delete
  • Relation administration
    • Add
    • Change
    • Delete

Controllers[edit]

The main controller of the admin section needs to differentiate between the different Adds, Changes or Deletes that are requested. This is taken care of by creating sub-controllers for each view for handling their specific tasks.

<root>/administrator/controller.php
<root>/administrator/controllers/users.php
<root>/administrator/controllers/books.php
<root>/administrator/controllers/relation.php

The controller is an important part of the MVC pattern. Not only does it take care of the requested tasks, it is also the initiator of instantiating the model with the same name and it is responsible for setting the view and the desired form for that view. The controller really justifies its name.

Within the controller it is good to make a difference between activating tasks (for example the edit selection from a menu) and resulting tasks (for example the result of an edit trigger is the posted data).

Typical controller functions look like:

function <activating task>()  // <-- edit, add, delete 
{
    JRequest::setVar( 'view', '[<componentname> | users | books | relation ]' );
    JRequest::setVar( 'layout', 'default'  );     // <-- The default form is named here, but in
                                                  // some complex views, multiple layouts might
                                                  // be needed.
    parent::display();
}

function <resulting task>()  // <-- save, remove
{
	$model = $this->getModel('[<componentname> | users | books | relation ]');
	if(!$model->action() ) {    // <-- action could be delete() or store()
		$msg = JText::_( 'Error: Could not perform action' );
	} else {
		$msg = JText::_( 'Action executed' );
	}

	$this->setRedirect( 'index.php?option=<componentname>', $msg );
}

A controller takes care of all tasks for that dedicated controller. After completing a resulting task the module will return to the main administration entrance point for that component, the main controller with the default view. Activating tasks enforce a new view with a form to display after first defining it.

The explicit definition of the form within a view might raise some eyebrows but our examples are too simple. For the general understanding and consistency this field should mostly be default. In complex views multiple forms could be defined within one view.

Models[edit]

The Controllers interact with their equally named Model counter part. In the frontend view the Model was only used to retrieve data. The backend has more controllers and thus also more model files. The backend model files not only are responsible for delivering data to the viewer but also take care of tasks initiated from the controller. A good model contains all actions required to manage a single table in the database.

<root>/administrator/models/<componentname>.php
<root>/administrator/models/users.php
<root>/administrator/models/books.php
<root>/administrator/models/relation.php

Views[edit]

Separate views are of course also required. For views and subsequent forms no forced naming conventions are required (linking to views is taken care of in the controller). In the following listing the Administrative tasks are identified as a subset for the different views. This choice is totally random and maybe even non-logical but that doesn't matter for the explanation. Just for example purposes I added also a different view, a delete view, that could be used for all the deletes for all administrative tasks asking an "Are you sure" display.

<root>/administrator/views/<componentname>/view.html.php + .../tmpl/default.php
<root>/administrator/views/users/view.html.php           + .../tmpl/default.php
<root>/administrator/views/books/view.html.php           + .../tmpl/default.php
<root>/administrator/views/relation/view.html.php        + .../tmpl/default.php
<root>/administrator/views/delete/view.html.php          + .../tmpl/default.php

Note: In general it is good practice to maintain one form per view because the view.html.php still has to deliver the content. With some basic logic you can enable, disable certain content but if this logic is becoming too complex start considering splitting up the view.

Note: Sharing template parts amongst the different views (for uniform layouting of headers and titles of your component) can be done using the PHP include / require;. There is one slight problem ... how to make the logical reference? In my modules I have a collector bin for general to use sniplets. Because it involved the views and forms I put this general bin in the views directory. The variable $pathToGeneralView needs to be defined somewhere in the first lines of your file and you have to make sure that the logical reference path is correct (the '..'s). In the following example the files marked with a '*' use the following code:

./com_compname/views/general/navigate.header.php  <-- sniplet code for the header
./com_compname/views/general/navigate.footer.php  <-- sniplet code for the footer
./com_compname/views/mngtable1/view.html.php
./com_compname/views/mngtable1/tmpl/default.php *
./com_compname/views/mngtable2/view.html.php
./com_compname/views/mngtable2/tmpl/default.php *
$pathToGeneralView = strchr(dirname(__FILE__), dirname($_SERVER['SCRIPT_NAME']));
$pathToGeneralView = str_replace(dirname($_SERVER['SCRIPT_NAME']),'.',$pathToGeneralView );
$pathToGeneralView = $pathToGeneralView . "/../../general/";  <-- returning path from current position. 
...
<?php require_once $pathToGeneralView . 'navigate.header.php'; ?>
<P>Do something    
<?php require_once $pathToGeneralView . 'navigate.footer.php'; ?>

Another Way to do the same thing:

$pathToGeneralView = JPATH_COMPONENT_ADMINISTRATOR. "/views/general/";  <-- will return 'path/Joomla/administrator/components/com_example/views/general/'
...
<?php require_once $pathToGeneralView . 'navigate.header.php'; ?>
<P>Do something    
<?php require_once $pathToGeneralView . 'navigate.footer.php'; ?>

Note: Giving the forms logical instead of the default naming is of course handy when having a lot of different views. Also, having that many default forms can make it difficult to determine the context. On the other hand, the view.html.php cannot be renamed, and one is always forced to look at the directory name for the view.

Essential Interaction Parameters[edit]

Everything is in place:

  • main and dedicated controllers;
  • main and dedicated models;
  • different views and their forms.

Just one big question remains: How to use them!

Three parameters are mandatory for letting Joomla! do its job:

  • option
  • controller
  • task

These three parameters are almost self explaining ;). The option part when developing a component is easy, always assign your component name to it. For component development consider this one as a constant, of course the Joomla! engine has more options than only components.

The controller and task parameters can be manipulated within your component anyway you want it to.

How it all works together[edit]

Looking at the simplified MVC picture Joomla! the logical flow of interaction goes the following way:

  1. What is my entrance point?
    • The Joomla! engine discovers a logged in administrator and sets the entrance point to <root>/administrator/index.php otherwise it will go to the <root>/index.php entrance.
  2. What option is requested?
    • The Joomla! engine reads the option variable and discovers that a component named <componentname> is requested. The entrance point becomes: <root>/administrator/components/com_<componentname>/<componentname>.php
  3. Is there need to access a dedicated controller?
    • The Joomla! engine reads the controller variable and discovers that a dedicated controller is required: <root>/administrator/components/com_<componentname>/controllers/<dedicatedcontroller>.php
  4. Is there a task that needs to be addressed?
    • The identified controller is handed the task value as parameter.
  5. The Model is derived from the controller and instantiated.
  6. The View and Form are set in the controller and initiated to become active.

How to add interaction[edit]

Within HTML there are two common ways to interact with Joomla!:

  1. reference to a link
  2. form submission post / get

Link reference for the Joomla! engine[edit]

Remember the activating tasks and resulting tasks mentioned earlier? Most activating tasks are initiated by a link. In case of the Library example the site section overview could be copied to the admin section. This default view will now be extended and every cell will become a link for editing the specific database element.

Using the Library example, the template PHP code without looping control will contain the following code:

$link = JRoute::_( 'index.php?option=com_library&controller=users&task=edit&cid='. $row->idu );
echo "<td><a href='$link'>{$row->name}</a></td>";
$link = JRoute::_( 'index.php?option=com_library&controller=books&task=edit&cid='. $row->idb );
echo "<td><a href='$link'>{$row->title}</a></td>";
$link = JRoute::_( 'index.php?option=com_library&controller=relation&task=edit&cid='. $row->idr );
echo "<td><a href='$link'>{$row->date}</a></td>";

Within each clickable field the three mandatory parameters to manipulate Joomla! can be identified. In addition there is one user parameter for handling the correct index in the controller task (cid). These parameter are separated by '&'. Do not use spaces in your variables, as this might screw-up parameter handling in certain browsers. After looping, all text entries will be clickable and trigger the corresponding controller with the correct row id in the associated table.

[Alice] | [One flew over ...] | [12-aug-2009]
[Alice] | [Celeb talk]        | [12-aug-2009]
[Mark]  | [Joomla!]           | [15-aug-2009]

Posting Form Data to the Joomla! Engine[edit]

After being initiated by an activating task, an input form view might be the result. The snippet of code below could be the result of clicking the first cell of the default component view that is clicked for editing ([Alice]:cid=3).

<form action="index.php" method="post">
  <input type="text" name="username" id="username" size="32" maxlength="250" value="<?php echo $this->user->name;?>" />

  <input type="submit" name="SubmitButton" value="Save" />

  <input type="hidden" name="option" value="com_library" />                  // <-- mandatory
  <input type="hidden" name="controller" value="hello" />                    // <-- mandatory
  <input type="hidden" name="task" value="save" />                           // <-- mandatory
  <input type="hidden" name="id" value="<?php echo $this->user->id; ?>" />   // <-- user parameter, index in database for [Alice]
</form>

The three Joomla! mandatory parameters are placed as hidden in the form. Hidden parameters are not shown in any way but will be added to the posting data.

Tip: when debugging this form, replace in the form tag method="post" temporarily with method="get". All posted parameters will be shown in the URL of your browser. If the module is working undo this change. For one reason it looks sharper without all the parameters being shown in the URL and you avoid motivating people to manipulate the browser URL themselves. Another reason is more technical and the simple explanation is that post methods (i.e. method="post") can contain more (complex) data. There is a third reason for using method="post" in form processing, and that is to increase security and prevent CSRF attacks on your site. method="post" should always be used when the resulting operation will modify the database.

Remark: In some developed modules you may notice that developers have also added the view parameter. This is bad programming whilst the controller(s) should take care of the view and the form.

Conclusion[edit]

The use of the three mandatory parameters and the different access points are clarified. Let's do something with this knowledge and extend the Hello component to the administrative section in the succeeding articles of this tutorial.

Contributors[edit]

  • staalanden
  • jamesconroyuk