4 tháng 1, 2008

Utility function for writing a menu link in Joomla

< ?php
/*** Utility function for writing a menu link
*/
function mosGetMenuLink( $mitem, $level=0, &$params, $open=null ) {
global $Itemid, $mosConfig_live_site, $mainframe;
$txt = '';
$image_link = 0;
switch ($mitem->type) {
case 'separator':
case 'component_item_link':
break;
case 'url':
if ( eregi( 'index.php\?', $mitem->link ) ) {
if ( !eregi( 'Itemid=', $mitem->link ) ) {
$mitem->link .= '&Itemid='. $mitem->id;
}
}
break;
case 'content_item_link':
case 'content_typed':
// load menu params
$menuparams = new mosParameters( $mitem->params,
$mainframe->getPath( 'menu_xml', $mitem->type ), 'menu' );
$unique_itemid = $menuparams->get( 'unique_itemid', 1 );
if ( $unique_itemid ) {
$mitem->link .= '&Itemid='. $mitem->id;
} else {
$temp = split('&task=view&id=', $mitem->link);
if ( $mitem->type == 'content_typed' ) {
$mitem->link .= '&Itemid='. $mainframe->getItemid($temp[1], 1, 0);
} else {
$mitem->link .= '&Itemid='. $mainframe->getItemid($temp[1], 0, 1);
}
}
break;
default:
$mitem->link .= '&Itemid='. $mitem->id;
break;
}
// Active Menu highlighting
$current_itemid = $Itemid;
if ( !$current_itemid ) {
$id = '';
} else if ( $current_itemid == $mitem->id ) {
$id = 'id="active_menu'. $params->get( 'class_sfx' ) .'"';
} else if( $params->get( 'activate_parent' ) && isset( $open ) && in_array( $mitem->id, $open ) ) {
$id = 'id="active_menu'. $params->get( 'class_sfx' ) .'"';
} else {
$id = '';
}
if ( $params->get( 'full_active_id' ) ) {
// support for `active_menu` of 'Link - Component Item'
if ( $id == '' && $mitem->type == 'component_item_link' ) {
parse_str( $mitem->link, $url );
if ( $url['Itemid'] == $current_itemid ) {
$id = 'id="active_menu'. $params->get( 'class_sfx' ) .'"';
}
}
// support for `active_menu` of 'Link - Url' if link is relative
if ( $id == '' && $mitem->type == 'url' && strpos( 'http', $mitem->link ) === false) {
parse_str( $mitem->link, $url );
if ( isset( $url['Itemid'] ) ) {
if ( $url['Itemid'] == $current_itemid ) {
$id = 'id="active_menu'. $params->get( 'class_sfx' ) .'"';
}
}
}
}
// replace & with amp; for xhtml compliance
$mitem->link = ampReplace( $mitem->link );
// run through SEF convertor
$mitem->link = sefRelToAbs( $mitem->link );
$menuclass = 'mainlevel'. $params->get( 'class_sfx' );
if ($level > 0) {
$menuclass = 'sublevel'. $params->get( 'class_sfx');
}
// replace & with amp; for xhtml compliance
// remove slashes from excaped characters
$mitem->name = stripslashes( ampReplace($mitem->name) );
switch ($mitem->browserNav) {
// cases are slightly different
case 1:
// open in a new window
$txt = '< a href="'. $mitem->link .'" target="_blank" class="'. $menuclass .'" '. $id .'>'. $mitem->name .'< /a>';
break;
case 2:
// open in a popup window
$txt = "< a href=\"#\" onclick=\"javascript: window.open('". $mitem->link ."', '', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=780,height=550'); return false\" class=\"$menuclass\" ". $id .">". $mitem->name ."< /a>\n";
break;
case 3:
// don't link it
$txt = '< span class="'. $menuclass .'" '. $id .'>'. $mitem->name .'< /span>';
break;
default:
// open in parent window
if ( $params->get( 'menu_images' ) ) {
$menu_params = new stdClass();
$menu_params = new mosParameters( $mitem->params );
$menu_image = $menu_params->def( 'menu_image', -1 );
$txt = '< a href="'. $mitem->link .'" class="'. $menuclass .'" '. $id .' id="link-'.$mitem->id.'">'.'< img src="'. $mosConfig_live_site .'/images/stories/'. $menu_image .'" border="0" alt="'. $mitem->name .'"/>'.'< /a>'."\n";
$image_link = 1;
}
else{
$txt = '< a href="'. $mitem->link .'" class="'. $menuclass .'" '. $id .' id="link-'.$mitem->id.'">'. $mitem->name .'< /a>'."\n";
}
break;
}
if ( $params->get( 'menu_images' ) ) {
$menu_params = new stdClass();
$menu_params = new mosParameters( $mitem->params );
$menu_image = $menu_params->def( 'menu_image', -1 );
if ( ( $menu_image != '-1' ) && $menu_image && !$image_link) {
$image = '< img src="'. $mosConfig_live_site .'/images/stories/'. $menu_image .'" border="0" alt="'. $mitem->name .'"/>';
if ( $params->get( 'menu_images_align' ) ) {
$txt = $txt .' '. $image;
} else {
$txt = $image .' '. $txt;
}
}
}
return $txt;
}
?>
-->đọc tiếp...

3 tháng 1, 2008

Model-View-Controller Component - Part 1

Model-View-Controller Component - Part 1
Introduction

The new framework in Joomla! 1.5 unleashes a great deal of power for developers. The code has been completely overhauled and cleaned up. This tutorial will guide you through the process of developing a component using this new framework.

The scope of this project will be to develop a simple Hello World! component. In future tutorials, this simple framework will be built upon to show the full power and versatility of the MVC design pattern in Joomla!
Requirements

You need Joomla! 1.5 or greater for this tutorial.
Introduction to Model-View-Controller

While the idea behind a component may seem extremely simple, code can quickly become very complex as additional features are added or the interface is customized.

Model-View-Controller (herein referred to as MVC) is a software design pattern that can be used to organize code in such a way that the business logic and data presentation are separate. The premise behind this approach is that if the business logic is grouped into one section, then the interface and user interaction that surrounds the data can revised and customized without having to reprogram the business logic.

There are three main parts of an MVC component. They are described here in brief, but for a more thorough explanation, please refer to the links provided at the end of this tutorial.
Model

The model is the part of the component that encapsulates the application’s data. It will often provide routines to manage and manipulate this data in a meaningful way in addition to routines that retrieve the data from the model. In our case, the model will contain methods to add, remove and update information about the greetings in the database. It will also contain methods to retrieve the list of greetings from the database. In general, the underlying data access technique should be encapsulated in the model. In this way, if an application is to be moved from a system that utilizes a flat file to store its information to a system that uses a database, the model is the only element that needs to be changed, not the view or the controller.
View

The view is the part of the component that is used to render the data from the model in a manner that is suitable for interaction. For a web-based application, the view would generally be an HTML page that is returned to the data. The view pulls data from the model (which is passed to it from the controller) and feeds the data into a template which is populated and presented to the user. The view does not cause the data to be modified in any way, it only displays data retrieved from the model.
Controller

The controller is responsible for responding to user actions. In the case of a web application, a user action is (generally) a page request. The controller will determine what request is being made by the user and respond appropriately by triggering the model to manipulate the data appropriately and passing the model into the view. The controller does not display the data in the model, it only triggers methods in the model which modify the data, and then pass the model into the view which displays the data.
Joomla! MVC Implementation

In Joomla!, the MVC pattern is implemented using three classes: <classname>JModel</classname>, <classname>JView</classname> and <classname>JController</classname>. For more detailed information about these classes, please refer to the API reference documentation (WIP).
Creating a Component

For our basic component, we only require five files:

*
hello.php - this is the entry point to our component

*
controller.php - this file contains our base controller

*
views/hello/view.html.php - this file retrieves the necessary data and pushes it into the template

*
views/hello/tmpl/default.php - this is the template for our output

*
hello.xml - this is an XML file that tells Joomla! how to install our component.

Creating the Entry Point

Joomla! is always accessed through a single point of entry: index.php for the Site Application or administrator/index.php for the Administrator Application. The application will then load the required component, based on the value of ‘option’ in the URL or in the POST data. For our component, the URL would be:

index.php?option=com_hello&view=hello

This will load our main file, which can be seen as the single point of entry for our component: components/com_hello/hello.php.

The code for this file is fairly typical across components.

<?php
/**
* @package Joomla.Tutorials
* @subpackage Components
* components/com_hello/hello.php
* @link http://dev.joomla.org/component/option,com_jd-wiki/Itemid,31/id,tutorials:modules/
* @license GNU/GPL
*/

// no direct access

defined( '_JEXEC' ) or die( 'Restricted access' );

// Require the base controller

require_once( JPATH_COMPONENT.DS.'controller.php' );

// Require specific controller if requested
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 = 'HelloController'.$controller;
$controller = new $classname( );

// Perform the Request task
$controller->execute( JRequest::getVar( 'task' ) );

// Redirect if set by the controller
$controller->redirect();

?>

The first statement is a security check.

JPATH_COMPONENT is the absolute path to the current component, in our case components/com_hello. If you specifically need either the Site component or the Administrator component, you can use JPATH_COMPONENT_SITE or JPATH_COMPONENT_ADMINISTRATOR.

DS is the directory separator of your system: either ‘/’ or ‘\’. This is automatically set by the framework so the developer doesn’t have to worry about developing different versions for different server OSs. DS should always be used when referring to files on the local server.

After loading the base controller, we check if a specific controller is needed. In this component, the base controller is the only controller, but we will leave this here for future use.

<classname>JRequest</classname>:getVar() finds a variable in the URL or the POST data. So if our URL is index.php?option=com_hello>controller=controller_name, then we can retrieve our controller name in our component using: echo <classname>JRequest</classname>::getVar(’controller’);

Now we have our base controller ‘<classname>HelloController</classname>’ in com_hello/controller.php, and, if needed, additional controllers like ‘<classname>HelloControllerController1</classname>’ in com_hello/controllers/controller1.php. Using this standard naming scheme will make things easy later on: ‘{Componentname}{Controller}{Controllername}’

After the controller is created, we instruct the controller to execute the task, as defined in the URL: index.php?option=com_hello&task=sometask. If no task is set, the default task ‘display’ will be assumed. When display is used, the ‘view’ variable will decide what will be displayed. Other common tasks are save, edit, new...

The controller might decide to redirect the page, usually after a task like ‘save’ has been completed. This last statement takes care of the actual redirection.

The main entry point (hello.php) essentially passes control to the controller, which handles performing the task that was specified in the request.
Creating the Controller

Our component only has one task - greet the world. Therefore, the controller will be very simple. No data manipulation is required. All that needs to be done is the appropriate view loaded. We will have only one method in our controller: display(). Most of the required functionality is built into the JController class, so all that we need to do is invoke the JController::display() method.

The code for the base controller is:

<?php
/**
* @package Joomla.Tutorials
* @subpackage Components
* @link http://dev.joomla.org/component/option,com_jd-wiki/Itemid,31/id,tutorials:modules/
* @license GNU/GPL
*/

// no direct access

defined( '_JEXEC' ) or die( 'Restricted access' );

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

/**
* Hello World Component Controller
*
* @package Joomla.Tutorials
* @subpackage Components
*/
class HelloController extends JController
{
/**
* Method to display the view
*
* @access public
*/
function display()
{
parent::display();
}

}
?>

The <classname>JController</classname> constructor will always register a display() task and unless otherwise specified (using the registerDefaultTask() method), it will set it as the default task.

This barebones display() method isn’t really even necessary since all it does is invoke the parent constructor. However, it is a good visual clue to indicate what is happening in the controller.

The <classname>JController</classname>::display() method will determine the name of the view and layout from the request and load that view and set the layout. When you create a menu item for your component, the menu manager will allow the administrator to select the view that they would like the menu link to display and to specify the layout. A view usually refers to a view of a certain set of data (i.e. a list of cars, a list of events, a single car, a single event). A layout is a way that that view is organized.

In our component, we will have a single view called hello, and a single layout (default).
Creating the View

The task of the view is very simple: It retrieves the data to be displayed and pushes it into the template. Data is pushed into the template using the <classname>JView</classname>::assignRef method.

The code for the view is:

<?php
/**
* @package Joomla.Tutorials
* @subpackage Components
* @link http://dev.joomla.org/component/option,com_jd-wiki/Itemid,31/id,tutorials:modules/
* @license GNU/GPL
*/

// no direct access

defined( '_JEXEC' ) or die( 'Restricted access' );

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

/**
* HTML View class for the HelloWorld Component
*
* @package HelloWorld
*/

class HelloViewHello extends JView
{
function display($tpl = null)
{
$greeting = "Hello World!";
$this->assignRef( 'greeting', $greeting );

parent::display($tpl);
}
}
?>

Creating the Template

Joomla! templates/layouts are regular PHP files that are used to layout the data from the view in a particular manner. The variables assigned by the JView::assignRef method can be accessed from the template using $this→{propertyname} (see the template code below for an example).

Our template is very simple: we only want to display the greeting that was passed in from the view:

<?php // no direct access
defined('_JEXEC') or die('Restricted access'); ?>
<h1><?php echo $this->greeting; ?></h1>

Wrapping It All Up - Creating the hello.xml File

It is possible to install a component manually by copying the files using an FTP client and modifying the database tables. It is more efficient to create a package file that will allow the Joomla! Installer to do this for you. This package file contains a variety of information:

*
basic descriptive details about your component (i.e. name), and optionally, a description, copyright and license information.

*
a list of files that need to be copied.

*
optionally, a PHP file that performs additional install and uninstall operations.

*
optionally, an SQL file which contains database queries that should be executed upon install/uninstall

The format of the XML file is as follows:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE install SYSTEM "http://dev.joomla.org/xml/1.5/component-install.dtd">
<install type="component" version="1.5.0">
<name>Hello</name>
<!-- The following elements are optional and free of formatting conttraints -->
<creationDate>2007 02 22</creationDate>
<author>John Doe</author>
<authorEmail>john.doe@example.org</authorEmail>
<authorUrl>http://www.example.org</authorUrl>
<copyright>Copyright Info</copyright>
<license>License Info</license>
<!-- The version string is recorded in the components table -->
<version>Component Version String</version>
<!-- The description is optional and defaults to the name -->
<description>Description of the component ...</description>

<!-- Site Main File Copy Section -->
<!-- Note the folder attribute: This attribute describes the folder
to copy FROM in the package to install therefore files copied
in this section are copied from /site/ in the package -->
<files folder="site">
<filename>index.html</filename>
<filename>hello.php</filename>
<filename>controller.php</filename>
<filename>views/index.html</filename>
<filename>views/hello/index.html</filename>
<filename>views/hello/view.html.php</filename>
<filename>views/hello/tmpl/index.html</filename>
<filename>views/hello/tmpl/default.php</filename>
</files>

<administration>
<!-- Administration Menu Section -->
<menu>Hello World!</menu>

<!-- Administration Main File Copy Section -->
<files folder="admin">
<filename>index.html</filename>
<filename>admin.hello.php</filename>
</files>
</administration>
</install>

If you look closely you will notice that there are some files that will be copied that we have not discussed. These are the index.html files. An index.html file is placed in each directory to prevent prying users from getting a directory listing. If there is no index.html file, some web servers will list the directory contents. This is often undesirable. These files have the simple line:

<html><body bgcolor="#FFFFFF"></body></html>

It will simply display a blank page.

The other file is the admin.hello.php file. This is the entry point for the admin section of our component. Since we don’t have an admin section of our component, it will have the same content as the index.html files at this point in time.
-->đọc tiếp...

Model-View-Controller Component - Part 2 - Adding a Model

Model-View-Controller Component - Part 2 - Adding a Model
Introduction

In the first tutorial of this series, creating a simple view-controller component using the Joomla! 1.5 CMS framework was demonstrated.

In the first tutorial, the greeting was hardcoded into the view. This doesn’t follow the MVC pattern exactly because the view is intended to only display the data, and not contain it.

In this second part of the tutorial we will demonstrate how to move this out of the view and into a model. In future tutorials we will demonstrate the power and flexibility that this design pattern provides.
Creating the Model

The concept of model gets its name because this class is intended to represent (or ‘model’) some entity. In our case, our first model will represent a ‘hello’, or a greeting. This is in line with our design thus far, because we have one view (’hello’), which is a view of our greeting.

The naming convention for models in the Joomla! framework is that the class name starts with the name of the component (in our case ‘hello’, followed by ‘model’, followed by the model name. Therefore, our model class is called HelloModelHello.

At this point, we will only model one behaviour of our hello, and that is retrieving the greeting. We will thus have one method, called getGreeting(). It will simply return the string ‘Hello, World!’.

Here is the code for our model class:

< ?php
/**
* Hello Model for Hello World Component
*
* @package Joomla.Tutorials
* @subpackage Components
* @link http://dev.joomla.org/component/option,com_jd-wiki/Itemid,31/id,tutorials:modules/
* @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 HelloModelHello extends JModel
{
/**
* Gets the greeting
* @return string The greeting to be displayed to the user
*/
function getGreeting()
{
return 'Hello, World!';
}
}

You will notice a line that starts with jimport. The jimport function is used to load files from the Joomla! framework that are required for our component. This particular statement will load the file /libraries/joomla/application/component/model.php. The ‘.’s are used as directory separators and the last part is the name of the file to load. All files are loaded relative to the libraries directory. This particular file contains the class definition for the JModel class, which is necessary because our model extends this class.

Now that we have created our model, we must modify our view so that it uses it to obtain the greeting.
Using the Model

The Joomla! framework is setup in such a way that the controller will automatically load the model that has the same name as the view and will push it into the view. Since our view is called ‘Hello’, our ‘Hello’ model will automatically be loaded and pushed into the view. Therefore, we can easily retrieve a reference to our model using the JView::getModel() method.

Our previous view code contained the lines:

$greeting = "Hello World!";

To take advantage of our model, we change this line to:

$model =& $this->getModel();
$greeting = $model->getGreeting();

The complete view now looks like:

< ?php

/**
* Hello View for Hello World Component
*
* @package Joomla.Tutorials
* @subpackage Components
* @link http://dev.joomla.org/component/option,com_jd-wiki/Itemid,31/id,tutorials:modules/
* @license GNU/GPL
*/

// no direct access

defined( '_JEXEC' ) or die( 'Restricted access' );

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

/**
* HTML View class for the HelloWorld Component
*
* @package Joomla.Tutorials
* @subpackage Components
*/

class HelloViewHello extends JView
{
function display($tpl = null)
{
$model =& $this->getModel();
$greeting = $model->getGreeting();
$this->assignRef( 'greeting', $greeting );

parent::display($tpl);
}
}
?>

Adding the File to the Package

All that remains is to add an entry to the XML file so that our new model will be copied. The Joomla! framework will look for our model in the models directory, so the entry for this file will look like (it should be added to the site section):

< filename>models/hello.php< /filename>

Our new hello.xml file will look like:

< ?xml version="1.0" encoding="utf-8"?>
< !DOCTYPE install SYSTEM "http://dev.joomla.org/xml/1.5/component-install.dtd">
< install type="component" version="1.5.0">
< name>Hello< /name>
< !-- The following elements are optional and free of formatting conttraints -->
< creationDate>2007 02 22< /creationDate>
< author>John Doe< /author>
< authorEmail>john.doe@example.org< /authorEmail>
< authorUrl>http://www.example.org< /authorUrl>
< copyright>Copyright Info< /copyright>
< license>License Info< /license>
< !-- The version string is recorded in the components table -->
< version>Component Version String< /version>
< !-- The description is optional and defaults to the name -->
< description>Description of the component ...< /description>

< !-- Site Main File Copy Section -->
< files folder="site">
< filename>index.html< /filename>
< filename>hello.php< /filename>
< filename>controller.php< /filename>
< filename>views/index.html< /filename>
< filename>views/hello/index.html< /filename>
< filename>views/hello/view.html.php< /filename>
< filename>views/hello/tmpl/index.html< /filename>
< filename>views/hello/tmpl/default.php< /filename>
< filename>models/index.html< /filename>
< filename>models/hello.php< /filename>
< /files>

< administration>
< !-- Administration Menu Section -->
< menu>Hello World!< /menu>

< !-- Administration Main File Copy Section -->
< !-- Note the folder attribute: This attribute describes the folder
to copy FROM in the package to install therefore files copied
in this section are copied from /admin/ in the package -->
< files folder="admin">
< !-- Site Main File Copy Section -->
< filename>index.html< /filename>
< filename>admin.hello.php< /filename>
< /files>
< /administration>
< /install>
-->đọc tiếp...

Model-View-Controller Component - Part 3 - Using the Database

Model-View-Controller Component - Part 3 - Using the Database
Introduction

In the first two tutorials, we showed you how to build a simple model-view-controller component. We had one view which retrieved data from a model (which was created in the 2nd tutorial). In this tutorial, we will be working with the model. Instead of the data being hard coded in the model, the model will retrieve the data from a table in the database.

This tutorial will demonstrate how to use the JDatabase class to retrieve data from the database.
Retrieving the Data

Our model currently has one method: getGreeting(). This method is very simple - all it does is return the hard-coded greeting.

To make things more interesting, we will load the greeting from a database table. We will demonstrate later how to create an SQL file and add the appropriate code to the XML manifest file so that the table and some sample data will be created when the component is installed. For now, we will simply replace our return statement with some code that will retrieve the greeting from the database and return it.

The first step is to obtain a reference to a database object. Since Joomla! uses the database for its normal operation, a database connection already exists; therefore, it is not necessary to create your own. A reference to the existing database can be obtained using:

$db =& JFactory::getDBO();

JFactory is a static class that is used to retrieve references to many of the system objects. More information about this class can be found in the API documentation.

The method name (getDBO) stands for get DataBase Object, and is easy and important to remember.

Now that we have obtained a reference to the database object, we can retrieve our data. We do this in two steps: * store our query in the database object

*

load the result

Our new getGreeting() method will therefore look like:

function getGreeting()
{
$db =& JFactory::getDBO();

$query = 'SELECT greeting FROM #__hello';
$db->setQuery( $query );
$greeting = $db->loadResult();

return $greeting;
}

hello is the name of the table that we will create later, and greeting is the name of the field that stores the greetings. If you are not familiar with SQL, it would be helpful to take a tutorial or a lesson to get yourself up to speed. One such tutorial can be found at w3schools.

The $db→loadResult() method will execute the stored database query and return the first field of the first row of the result. See JDatabase API reference for more information about other load methods in the JDatabase class.
Creating the Installation SQL File

The Joomla! installer has built-in support for executing queries during component installation. These queries are all stored in a standard text file.

We will have three queries in our install file: the first will drop the table in case it already exists, the second will create the table with the appropriate fields, and the third will insert the data.

Here are our queries:

DROP TABLE IF EXISTS `#__hello`;

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

INSERT INTO `#__hello` (`greeting`) VALUES ('Hello, World!'),
('Bonjour, Monde!'),
('Ciao, Mondo!');

You might find the prefix on the table names rather odd. Joomla! will replace this prefix with the prefix used by the current install. For most installs, this table will become jos_hello. This allows multiple installs of Joomla! to use the same database, and prevents collisions with other applications using the same table names (i.e. two applications might share a database, but might both require a ‘users’ table. This convention avoids problems.)

We have specified two fields in our database. The first field is id, and is called the ‘primary key’. The primary key of a database table is a field that is used to uniquely identify a record. This is often used to lookup rows in the database. The other field is greeting. This is the field that stores the greeting that is returned from the query that we used above.

We will save our queries in a file called install.utf.sql.
Creating the Uninstall SQL File

Though we might hope that people will never want to uninstall our component, it is important that if they do, we don’t leave anything behind. Joomla! will look after deleting the files and directories that were created during install, but you must manually include queries that will remove and tables that have been added to the database. Since we have only created one table, we only need one query:

DROP TABLE IF EXISTS `#__hello`;

We will save this query in a file called uninstall.utf.sql.
Updating our Install File

We need to change a few things in our install file. First, we need to add our two new files to the list of files to install. SQL install file have to go in the admin directory. Second, we need to tell the installer to execute the queries in our files on install and uninstall.

Our new file looks like this:

&lt ?xml version="1.0" encoding="utf-8"?>
&lt !DOCTYPE install SYSTEM "http://dev.joomla.org/xml/1.5/component-install.dtd">
&lt install type="component" version="1.5.0">
&lt name>Hello&lt /name>
&lt !-- The following elements are optional and free of formatting conttraints -->
&lt creationDate>2007 02 22&lt /creationDate>
&lt author>John Doe&lt /author>
&lt authorEmail>john.doe@example.org&lt /authorEmail>
&lt authorUrl>http://www.example.org&lt /authorUrl>
&lt copyright>Copyright Info&lt /copyright>
&lt license>License Info&lt /license>
&lt !-- The version string is recorded in the components table -->
&lt version>Component Version String&lt /version>
&lt !-- The description is optional and defaults to the name -->
&lt description>Description of the component ...&lt /description>

&lt !-- Site Main File Copy Section -->
&lt files folder="site">
&lt filename>index.html&lt /filename>
&lt filename>hello.php&lt /filename>
&lt filename>controller.php&lt /filename>
&lt filename>views/index.html&lt /filename>
&lt filename>views/hello/index.html&lt /filename>
&lt filename>views/hello/view.html.php&lt /filename>
&lt filename>views/hello/tmpl/index.html&lt /filename>
&lt filename>views/hello/tmpl/default.php&lt /filename>
&lt filename>models/hello.php&lt /filename>
&lt /files>
&lt install>
&lt sql>
&lt file charset="utf8" driver="mysql">install.sql&lt /file>
&lt /sql>
&lt /install>
&lt uninstall>
&lt sql>
&lt file charset="utf8" driver="mysql">uninstall.sql&lt /file>
&lt /sql>
&lt /uninstall>
&lt administration>
&lt !-- Administration Menu Section -->
&lt menu>Hello World!&lt /menu>

&lt !-- Administration Main File Copy Section -->
&lt !-- Note the folder attribute: This attribute describes the folder
to copy FROM in the package to install therefore files copied
in this section are copied from /admin/ in the package -->
&lt files folder="admin">
&lt !-- Site Main File Copy Section -->
&lt filename>index.html&lt /filename>
&lt filename>admin.hello.php&lt /filename>
&lt filename>install.sql&lt /filename>
&lt filename>uninstall.sql&lt /filename>
&lt /files>
&lt /administration>
&lt /install>

You will notice two attributes present on the &lt file> tags within the &lt install> and &lt uninstall> sections: charset and driver. The charset is the type of charset to use. The only valid charset is utf8. If you want to create install files for non-utf8 databases (for older version of MySQL), you should omit this attribute.

The driver attribute specifies which database the queries were written for. Currently, this can only be mysql, but in future versions of Joomla! there may be more database drivers available.
Conclusion

We now have a component that takes advantage of both the Joomla! MVC framework classes and the JDatabase classes. You are now able to write MVC components that interact with the database and can use the Joomla! installer to create and populate database tables.
-->đọc tiếp...

Model-View-Controller Component - Part 4 Creating an Administrator Interface

an Administrator Interface
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 this tutorial, we will develop an administrator section for our component which will make it possible to manage the entries in the database.
Creating the Basic Framework

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.

Here is the listing for admin.hello.php:

&lt?php
/**
* @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' );

// Require the base controller

require_once( JPATH_COMPONENT.DS.'controller.php' );

// Require specific controller if requested
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();

?>

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:

/**
* 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;
}

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:

/**
* 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;
}

The completed model looks like:

&lt?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;

/**
* 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;
}

/**
* 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;
}
}

This file is saved as models/hellos.php.
The Hellos View

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.

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:

&lt?php
/**
* 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!
defined('_JEXEC') or die();

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

/**
* Hellos View
*
* @package Joomla.Tutorials
* @subpackage Components
*/
class HellosViewHellos extends JView
{
/**
* Hellos view display method
* @return void
**/
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);
}
}

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:

&lt?php defined('_JEXEC') or die('Restricted access'); ?>
&ltform action="index.php" method="post" name="adminForm">
&ltdiv id="editcell">
&lttable class="adminlist">
&ltthead>
&lttr>
&ltth width="5">
&lt?php echo JText::_( 'ID' ); ?>
&lt/th>
&ltth>
&lt?php echo JText::_( 'Greeting' ); ?>
&lt/th>
&lt/tr>
&lt/thead>
&lt?php
$k = 0;
for ($i=0, $n=count( $this->items ); $i &lt $n; $i++)
{
$row =& $this->items[$i];
?>
&lttr class="&lt?php echo "row$k"; ?>">
&lttd>
&lt?php echo $row->id; ?>
&lt/td>
&lttd>
&lt?php echo $row->greeting; ?>
&lt/td>
&lt/tr>
&lt?php
$k = 1 - $k;
}
?>
&lt/table>
&lt/div>

&ltinput type="hidden" name="option" value="com_hello" />
&ltinput type="hidden" name="task" value="" />
&ltinput type="hidden" name="boxchecked" value="0" />
&ltinput type="hidden" name="controller" value="hello" />

&lt/form>

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:

JToolBarHelper::title( JText::_( 'Hello Manager' ), 'generic.png' );
JToolBarHelper::deleteList();
JToolBarHelper::editListX();
JToolBarHelper::addNewX();

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:

&ltth width="20">
&ltinput type="checkbox" name="toggle" value="" onclick="checkAll(&lt?php echo count( $this->items ); ?>);" />
&lt/th>

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:

$checked = JHTML::_( 'grid.id', $i, $row->id );

after the line:

$row =& $this->items[$i];

Then we will add a cell in between the two that we already have:

&lttd>
&lt?php echo $checked; ?>
&lt/td>

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:

$link = JRoute::_( 'index.php?option=com_hello>controller=hello>task=edit>cid[]='. $row->id );

And we include the link in the cell showing the greeting text:

&lttd>
&lta href="&lt?php echo $link; ?>">&lt?php echo $row->greeting; ?>&lt/a>
&lt/td>

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:

&lt?php defined('_JEXEC') or die('Restricted access'); ?>
&ltform action="index.php" method="post" name="adminForm">
&ltdiv id="editcell">
&lttable class="adminlist">
&ltthead>
&lttr>
&ltth width="5">
&lt?php echo JText::_( 'ID' ); ?>
&lt/th>
&ltth>
&lt?php echo JText::_( 'Greeting' ); ?>
&lt/th>
&lt/tr>
&lt/thead>
&lt?php
$k = 0;
for ($i=0, $n=count( $this->items ); $i &lt $n; $i++)
{
$row =& $this->items[$i];
?>
&lttr class="&lt?php echo "row$k"; ?>">
&lttd>
&lt?php echo $row->id; ?>
&lt/td>
&lttd>
&lt?php echo $row->greeting; ?>
&lt/td>
&lt/tr>
&lt?php
$k = 1 - $k;
}
?>
&lt/table>
&lt/div>

&ltinput type="hidden" name="option" value="com_hello" />
&ltinput type="hidden" name="task" value="" />
&ltinput type="hidden" name="boxchecked" value="0" />
&ltinput type="hidden" name="controller" value="hello" />

&lt/form>

Our hellos view is now complete. You can try out the component now to see the results.

The component can be downloaded at: 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:

/**
* constructor (registers additional tasks to methods)
* @return void
*/
function __construct()
{
parent::__construct();

// Register Extra tasks
$this->registerTask( 'add' , 'edit' );
}

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:

/**
* display the edit form
* @return void
*/
function edit()
{
JRequest::setVar( 'view', 'hello' );
JRequest::setVar( 'layout', 'form' );
JRequest::setVar('hidemainmenu', 1);

parent::display();
}

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:

/**
* display method of Hello view
* @return void
**/
function display($tpl = null)
{
//get the hello
$hello =& $this->get('Data');
$isNew = ($hello->id &lt 1);

$text = $isNew ? JText::_( 'New' ) : JText::_( 'Edit' );
JToolBarHelper::title( JText::_( 'Hello' ).': &ltsmall>&ltsmall>[ ' . $text.' ]&lt/small>&lt/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);
}

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:

/**
* Constructor that retrieves the ID from the request
*
* @access public
* @return void
*/
function __construct()
{
parent::__construct();

$array = JRequest::getVar('cid', 0, '', 'array');
$this->setId((int)$array[0]);
}

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:

/**
* 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;
}

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.

/**
* 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;
}

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:

&lt?php defined('_JEXEC') or die('Restricted access'); ?>

&ltform action="index.php" method="post" name="adminForm" id="adminForm">
&ltdiv class="col100">
&ltfieldset class="adminform">
&ltlegend>&lt?php echo JText::_( 'Details' ); ?>&lt/legend>
&lttable class="admintable">
&lttr>
&lttd width="100" align="right" class="key">
&ltlabel for="greeting">
&lt?php echo JText::_( 'Greeting' ); ?>:
&lt/label>
&lt/td>
&lttd>
&ltinput class="text_area" type="text" name="greeting" id="greeting" size="32" maxlength="250" value="&lt?php echo $this->hello->greeting;?>" />
&lt/td>
&lt/tr>
&lt/table>
&lt/fieldset>
&lt/div>

&ltdiv class="clr">&lt/div>

&ltinput type="hidden" name="option" value="com_hello" />
&ltinput type="hidden" name="id" value="&lt?php echo $this->hello->id; ?>" />
&ltinput type="hidden" name="task" value="" />
&ltinput type="hidden" name="controller" value="hello" />
&lt/form>

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:

&lt?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);
}
}
?>

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.

This file should be called hello.php and it will go in a directory called tables in the administrator section of our component.
Implementing the Function in our Model

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.

Our method looks like:

/**
* Method to store a record
*
* @access public
* @return boolean True on success
*/
function store()
{
$row =& $this->getTable();

$data = JRequest::get( 'post' );
// Bind the form fields to the hello table
if (!$row->bind($data)) {
$this->setError($this->_db->getErrorMsg());
return false;
}

// Make sure the hello record is valid
if (!$row->check()) {
$this->setError($this->_db->getErrorMsg());
return false;
}

// Store the web link table to the database
if (!$row->store()) {
$this->setError($this->_db->getErrorMsg());
return false;
}

return true;
}

This method gets added to the hello model.

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.

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.

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 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.

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.

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).
Adding the Task to the Controller

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:

/**
* save a record (and redirect to main page)
* @return void
*/
function save()
{
$model = $this->getModel('hello');

if ($model->store()) {
$msg = JText::_( 'Greeting Saved!' );
} else {
$msg = JText::_( 'Error Saving Greeting' );
}

// Check the table in so it can be edited.... we are done with it anyway
$link = 'index.php?option=com_hello';
$this->setRedirect($link, $msg);
}

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.

frame|none|The message that was passed is displayed at the top of the page.
Deleting a Record
Implementing the Function in the Model

In the model, we will retrieve the list of IDs to delete and call the JTable class to delete them. Here it is:

/**
* 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;
}

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:

/**
* 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 );
}

Cancelling the Edit Operation

To cancel the edit operation, all we have to do is redirect back to the main view:

/**
* cancel editing a record
* @return void
*/
function cancel()
{
$msg = JText::_( 'Operation Cancelled' );
$this->setRedirect( 'index.php?option=com_hello', $msg );
}

Conclusion

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.
-->đọc tiếp...

2 tháng 1, 2008

How to use the database classes in your script

Joomla provides a sopisticated database abstraction layer to simplify the usage for 3PD. This guide should help you using this layer.
1. Why should I use the Joomla database class?
Joomla is build to be able to use several different kinds of SQL-database-systems and to run in a variety of environments with different table-prefixes. In addition to these functions, the class automatically creates the database connection. Besides instantiating the object, you only need 2 lines of code to get a result from the database and that in a variety of formats. Using the Joomla database layer ensures a maximum of compatibility and flexibility for your extension.
2. Preparating the query
Database usage
// Get a database object
$db = JFactory::getDBO();
$query = "SELECT * FROM #__example_table WHERE id = 999999";
$db->setQuery($query);
First we instantiate the database object, then we prepare the query. You can use the normal SQL-syntax, the only thing you have to change is the table-prefix. To make this as flexible as possible, Joomla uses a placeholder for the prefix, the #__. In the next step, the setQuery(), this string is replaced with the correct prefix.
Now, if we don’t want to get information from the database, but insert a row into it, we need one more function. Every string-value in the SQL-syntax has to be quoted, therefore we have to hand over these values to the function $db→Quote($value).
Whatever we want to do, we have to set the query with the setQuery()-function. Although you could write the query directly as a parameter for setQuery(), its commonly done by first saving it in a variable, normally $query, and then handing this variable over. This helps writing clean, readable code.
3. Executing the Query
To execute the query, Joomla provides several functions, which differ in their return value.
Basic Query Execution
query
Query Execution Information
getAffectedRows
explain
insertid
Insert Query Execution
insertObject
4. Query Results
The database class contains many methods for working with a query’s result set.
Single Value Result
loadResult
Single Row Results
loadObject
loadRow
loadResultArray
Multi-Row Results
loadObjectList
loadRowList
loadAssocList
Misc Result Set Methods
getNumRows
5. Tips, Tricks & FAQ
We had a few people lately using sub-queries like these:
Sub-queries
SELECT * FROM #__example WHERE id IN (SELECT * FROM #__example2);
These kind of queries are only possible in MySQL 4.1 and above. Another way to achieve this, is splitting the query into two:
Splitted query
$query = "SELECT * FROM #__example2";
$database->setQuery($query);
$query = "SELECT * FROM #__example WHERE id IN (". implode(",", $database->loadArray()) .")";
-->đọc tiếp...

Calling different scripts in Joomla

Now we’ve changed a lot of our database and variable-retrieving code, but we still don’t know how to properly call our different script-files our former script consists of.If you have more than just one file in your script, you seem to have a problem calling those inside of Joomla. Joomla uses a case switching for this:
Case switching for multiple scripts
// no direct access
defined( '_VALID_MOS' ) or die( 'Restricted access' );
require_once( $mainframe->getPath( 'front_html' ) );
$task = mosGetParam( $_REQUEST, 'task', 'view' );
switch ($task) {
case 'edit':
include('edit.php');
break;
case 'save':
include('save.php');
break;
case 'view':
default:
include('view.php');
break;
}
?>
As you can see, we first read the value of the POST-variable “task” and then differentiate between the different tasks at hand. When we find our correct task, we link to the file with the corresponding code. You could also link to a function, which would reduce the number of files in your components-folder and gives you the chance to easily call, for example, the view-function after saving your data.
-->đọc tiếp...

How to determine if the user is viewing the front page

In Joomla! 1.0.x it was possible to determine if the user was viewing the front page by using code like this:
Determine if user is viewing the front page in Joomla! 1.0.x
<?php
if ($option == 'com_frontpage' || $option == '') { echo 'This is the front page'; }
?>

But in Joomla! 1.5.x the com_frontpage component is no longer present. This is how to achieve the same result in Joomla! 1.5.x
Determine if user is viewing the front page in Joomla! 1.5.x
<?php
$menu = & JSite::getMenu();
if ($menu->getActive() == $menu->getDefault()) { echo 'This is the front page'; }
?>

This works by checking to see if the current active menu item is the default one.
-->đọc tiếp...

here are the steps to display in joomla 1.5

hello.php includes the controller.php and invokes its execute() method. This method will invoke the task handling method() depending on the task passed from the request (in the link).
The default task is display().
The display() method is built into the JController class. The controller class name is HelloController. The view name is Hello. The display() method will take the Hello off the front of the controller class name, append View to it, and then add the view name, which is Hello, thus HelloViewHello. It will look for this in the directory views/{viewname}, so in this case, views/hello. It will look for a file called view.html.php.
So, here are the steps:
1. hello.php
2. HelloController->execute()
3. HelloController->display()
4. JController->display()
5. HelloViewHello->display()
Good to hear you've had some success, and hopefully I can help you out with things you're still working on.
What you have hit is one of the limitations of doing a Hello World example. It really isn't real world. But you have the general idea - each 'page' (or I'd rather, screen), has its own view. It isn't as clear in this example perhaps because the only difference between hello and goodbye is the message, nothing else. In our example, you could extract hello and goodbye as messages, and simply have one view, which would be message. But then you would have just one view.
Basically, for every set of data you want to display, you have a view. So for com_content, you have five views: archive, article, category, frontpage, section. This is one view for each set of data that is displayed.
But look at the templates in each of these directories:
archive
default.php
default_items.php
article
default.php
form.php
pagebreak.php
category
blog.php
blog_item.php
blog_links.php
default.php
default_items.php
frontpage
default.php
default_item.php
default_links.php
section
blog.php
blog_item.php
blog_links.php
default.php
You will see that each view displays a different set of data. There is one view to display a section, one view to display a category, one view for the frontpage, etc...
You will see templates broken up two different ways. You can see in a number of the views that there are different templates. As an example, in the section view, you have blog.php and default.php. These are different templates. They take the same information, but display them in different ways. These are called layouts. So you can have a blog layout, or you can have the default layout.
You'll see the same thing in the article view. In the article view, there are two possible layouts: default, and form. The default displays the article as the site visitor would see it when viewing the site. The form layout displays the information in a form that can be edited by the user.
Layouts can be selected using the setLayout() method.
The other breakdown of layouts can be seen in the category view. There are two files:
default.php
default_items.php
These aren't separate layouts, rather, default_items is a sub layout of default.php. So, default.php will specify where the items are displayed within the component, and then defaults_items.php specifies how the items in the category are displayed. This allows for greater flexibility and more modular modifications. This enables, for example, a Joomla! site template designer to override only the way the items are displayed and not have to write a whole new layout file for categories.
Hope this help explains things a little bit, and feel free to ask more questions!
-->đọc tiếp...
BlogWeb: tạo từ Blog của Google
Nội dung: lấy từ nhiều Nguồn khác nhau.
Mục đích: note lại bài Hướng dẫn hay và Đáng đọc.
Kết quả: nghiện Internet Nặng.
Tương lại: xuống lỗ Vẫn Nghiện nếu không có ai giúp.
Blog Web của: Trí Dũng đến từ Việt Nam - Liên kết đến trang Blog Cá Nhân
Tôi biết (^_^)
Thông tin về Tác giả. Chi Tiết
Sử dụng (FireFox | Google Chrome on Ubuntu) để xem tốt nhất. Học Nhiều Hơn Tại Đây
©2009 Google Blogger - HuuNguyen's Home