Actions

J1.5

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

From Joomla! Documentation

< J1.5:Developing a MVC Component
m
 
(25 intermediate revisions by 16 users not shown)
Line 1: Line 1:
{{ambox
+
{{Chunk:Developing a Model-View-Controller (MVC) Component for Joomla!1.5 - Contents}}
| type  = notice
+
| image = notice
+
| text  = This {{thingamabob}} has been divided into three sections, two new articles are added. Especially this page needs a review
+
<small>(August 2009)</small>}}
+
 
== Introduction ==
 
== Introduction ==
  
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 the next articles 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 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 article, [[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 of the MVC pattern. In the frontend solution (site section) 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 - we will have to develop all of the code that manages the application flow.
+
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]].
 +
 
 +
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 ==
 
== Site / Admin ==
Line 18: Line 16:
 
   ...
 
   ...
 
   <administration>
 
   <administration>
  <!--  Administration Menu Section -->  
+
    <!--  Administration Menu Section -->  
  <menu>Hello World!</menu>  
+
    <menu>Hello World!</menu>  
  <!--  Administration Main File Copy Section -->  
+
    <!--  Administration Main File Copy Section -->  
  <files folder="admin">
+
    <files folder="admin">
  <filename>hello.php</filename>  
+
      <filename>hello.php</filename>  
  <filename>index.html</filename>  
+
      <filename>index.html</filename>  
  <filename>install.sql</filename>  
+
      <filename>install.sql</filename>  
  <filename>uninstall.sql</filename>  
+
      <filename>uninstall.sql</filename>  
  </files>
+
    </files>
 
   </administration>
 
   </administration>
 
   ...
 
   ...
Line 39: Line 37:
 
  <root>/administrator/index.php
 
  <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 Controls, Views and Models naming can (and sometimes must) be used as in the site section.
+
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 ==
 
== MVC pattern interaction ==
Line 54: Line 52:
 
[[image:Library Example.png|400px|frameless|center]]
 
[[image:Library Example.png|400px|frameless|center]]
  
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 chapter it should be easy to follow the tutorial in the succeeding chapters
+
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 ===
 
=== Mapping a Joomla! MVC component from the example ===
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 (''Hint'': <code>if ($user->registered) {}</code> ).
+
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).
  
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 lend books.  
+
 
  Alice | One flew over ... | 12 aug 2009
+
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 | Celeb talk        | 12 aug 2009
+
  Alice | One flew over ... | 12-aug-2009
  Mark  | Joomla!          | 15 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:
 
With respect to the administration part it is important to understand that we have one default and three dedicated views, each controlling three tasks:
Line 95: Line 94:
 
{
 
{
 
     JRequest::setVar( 'view', '[<componentname> | users | books | relation ]' );
 
     JRequest::setVar( 'view', '[<componentname> | users | books | relation ]' );
     JRequest::setVar( 'layout', 'default'  );    // <-- The default form is named here but in complex
+
     JRequest::setVar( 'layout', 'default'  );    // <-- The default form is named here, but in
                                                   //     views multiple layouts might be needed.
+
                                                   // some complex views, multiple layouts might
 +
                                                  // be needed.
 
     parent::display();
 
     parent::display();
 
}
 
}
Line 126: Line 126:
 
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.
 
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/<componentname>/view.html.php + .../tmpl/default.php
  <root>/administrator/views/users/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/books/view.html.php           + .../tmpl/default.php
  <root>/administrator/views/relation/view.html.php   + .../tmpl/default.php
+
  <root>/administrator/views/relation/view.html.php       + .../tmpl/default.php
&nbsp;
+
  <root>/administrator/views/delete/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'': 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.  
Line 149: Line 148:
 
$pathToGeneralView = $pathToGeneralView . "/../../general/";  <-- returning path from current position.  
 
$pathToGeneralView = $pathToGeneralView . "/../../general/";  <-- returning path from current position.  
 
...
 
...
<?php require_once $pathToGeneralView . 'navigation.header.php'; ?>
+
<?php require_once $pathToGeneralView . 'navigate.header.php'; ?>
 
<P>Do something     
 
<P>Do something     
<?php require_once $pathToGeneralView . 'navigation.footer.php'; ?>
+
<?php require_once $pathToGeneralView . 'navigate.footer.php'; ?>
 
</source>
 
</source>
 
Another Way to do the same thing:
 
Another Way to do the same thing:
 
<source lang=php>
 
<source lang=php>
$pathToGeneralView = JPATH_COMPONENT_ADMINISTRATOR.DS. "views".DS."general".DS;  <-- will return 'path/Joomla/administrator/components/com_example/views/general/
+
$pathToGeneralView = JPATH_COMPONENT_ADMINISTRATOR. "/views/general/";  <-- will return 'path/Joomla/administrator/components/com_example/views/general/'
 
...
 
...
<?php require_once $pathToGeneralView . 'navigation.header.php'; ?>
+
<?php require_once $pathToGeneralView . 'navigate.header.php'; ?>
 
<P>Do something     
 
<P>Do something     
<?php require_once $pathToGeneralView . 'navigation.footer.php'; ?>
+
<?php require_once $pathToGeneralView . 'navigate.footer.php'; ?>
 
</source>
 
</source>
  
''Note'': Giving the forms logical instead of the ''default'' naming is of course handy when having a lot of different views. Having also that much ''default'' forms could make you easily loose oversight. On the other hand the view.html.php can not be renamed and you are always forced to look at the directory name for the view name you are working in.
+
''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 ===
 
=== Essential Interaction Parameters ===
 
Everything is in place:
 
Everything is in place:
 
* main and dedicated controllers;
 
* main and dedicated controllers;
* main and dedicated modules;
+
* main and dedicated models;
 
* different views and their forms.
 
* different views and their forms.
  
Line 184: Line 183:
 
Looking at the simplified MVC picture Joomla! the logical flow of interaction goes the following way:
 
Looking at the simplified MVC picture Joomla! the logical flow of interaction goes the following way:
 
# What is my entrance point?  
 
# 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 wil go to the <root>/index.php entrance.
+
#*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?  
 
# 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/modules/com_<componentname>/<componentname>.php
+
#*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?  
 
# 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/modules/com_<componentname>/controllers/<dedicatedcontroller>.php
+
#* 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?  
 
# Is there a task that needs to be addressed?  
 
#* The identified controller is handed the task value as parameter.  
 
#* The identified controller is handed the task value as parameter.  
 
# The Model is derived from the controller and instantiated.
 
# The Model is derived from the controller and instantiated.
 
# The View and Form are set in the controller and initiated to become active.
 
# The View and Form are set in the controller and initiated to become active.
 
((Remark: the text states that the path is <root>/administrator/modules/com_<componentname>/<componentname>.php, but I am pretty sure that this is an error. It probably should say <root>/administrator/components/com_<componentname>/<componentname>.php. Can somebody please verify this and correct it?))
 
  
 
=== How to add interaction ===
 
=== How to add interaction ===
Line 207: Line 204:
 
<source lang=php>
 
<source lang=php>
 
$link = JRoute::_( 'index.php?option=com_library&controller=users&task=edit&cid='. $row->idu );
 
$link = JRoute::_( 'index.php?option=com_library&controller=users&task=edit&cid='. $row->idu );
echo "<td><a href=\"".$link."\">$row->name</a></td>";
+
echo "<td><a href='$link'>{$row->name}</a></td>";
 
$link = JRoute::_( 'index.php?option=com_library&controller=books&task=edit&cid='. $row->idb );
 
$link = JRoute::_( 'index.php?option=com_library&controller=books&task=edit&cid='. $row->idb );
echo "<td><a href=\"".$link."\">$row->title</a></td>";
+
echo "<td><a href='$link'>{$row->title}</a></td>";
 
$link = JRoute::_( 'index.php?option=com_library&controller=relation&task=edit&cid='. $row->idr );
 
$link = JRoute::_( 'index.php?option=com_library&controller=relation&task=edit&cid='. $row->idr );
echo "<td><a href=\"".$link."\">$row->date</a></td>";
+
echo "<td><a href='$link'>{$row->date}</a></td>";
 
</source>
 
</source>
  
Within each clickable field the three mandatory parameters to manipulate MVC 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 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.
+
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] | [One flew over ...] | [12-aug-2009]
  [Alice] | [Celeb talk]        | [12 aug 2009]
+
  [Alice] | [Celeb talk]        | [12-aug-2009]
  [Mark]  | [Joomla!]          | [15 aug 2009]
+
  [Mark]  | [Joomla!]          | [15-aug-2009]
  
 
==== Posting Form Data to the Joomla! Engine ====
 
==== Posting Form Data to the Joomla! Engine ====
After being initiated by an activating task, an input form view might be the result. The sniplet code below could be the result of clicking the first cell of the default component view that is clicked for editing ([Alice]:cid=3).  
+
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).  
  
 
<source lang="php">
 
<source lang="php">
Line 238: Line 235:
 
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.
 
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 <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. Of course one can look at the source code but using ''Post'' instead of ''Get'', but this eliminates the first 90% of the earth population. The other reason is more technical and the simple explanation is that post methods (i.e. method="post") can contain more (complex) data.
+
''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.
  
 
''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''.
 
''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''.
Line 245: Line 242:
  
 
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.
 
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.
 
== Articles in this Series ==
 
[[Developing a Model-View-Controller Component - Part 1]]
 
 
[[Developing a Model-View-Controller Component - Part 2 - Adding a Model]]
 
 
[[Developing a Model-View-Controller Component - Part 3 - Using the Database]]
 
 
[[Developing a Model-View-Controller Component - Part 4 - Creating an Administrator Interface]]
 
 
[[Developing a Model-View-Controller Component - Part 5 - Basic Backend Framework]]
 
 
[[Developing a Model-View-Controller Component - Part 6 - Adding Backend Actions]]
 
  
 
== Contributors ==
 
== Contributors ==
Line 263: Line 247:
 
* jamesconroyuk
 
* jamesconroyuk
  
[[Category:Development]]
+
[[Category:Component Development]]

Latest revision as of 08:34, 9 May 2013

Replacement filing cabinet.png
This Namespace has been archived - Please Do Not Edit or Create Pages in this namespace. Pages contain information for a Joomla! version which is no longer supported. It exists only as a historical reference, will not be improved and its content may be incomplete.

Contents

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.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  • staalanden
  • jamesconroyuk