Improving components with Joomla! 1.5

Exclusive offer: get 50% off this eBook here
Mastering Joomla! 1.5 Extension and Framework Development

Mastering Joomla! 1.5 Extension and Framework Development — Save 50%

The Professional Guide to Programming Joomla!

$26.99    $13.50
by James Kennard | June 2010 | Joomla! Open Source

Joomla! is one of the world's top open source content management systems. The main sources of the PHP MySQL application's success are its comprehensive extension libraries, which extend Joomla! far beyond content management, and it's very active forums where one can easily tap into the knowledge of other Joomla! users, administrators, and developers.

In this article by Chuck Lanham and James Kennard, author of Mastering Joomla! 1.5 Extension and Framework Development, we will cover:

  • How to Improve toolbars in the backend
  • How to Modify the Submenu
  • The joomla.html library
  • How to Build better layouts and templates

(Read more interesting articles on Nhibernate 2 Beginner's Guide here.)

Improving components

We are going to be working almost exclusively on the backend component in this article but most of what we will be covering could easily be adapted for the frontend component if we wished to do so.

Component backend

When we build the backend of a component there are some very important things to consider. Most components will include at least two backend views or forms; one will display a list of items and another will provide a form for creating or editing a single item. There may be additional views depending on the component but for now we will work with our com_boxoffice component, which consists of two views.

Toolbars

Although we have already built our component toolbars, we didn't spend much time discussing all the features and capabilities that are available to us, so let's start with a bit of a review and then add a few enhancements to our component.

Our backend component has two toolbars. The frst is displayed when we access our component from the Components | Box Offce Revues menu:

The second toolbar is displayed when we click on the New or Edit button, or click on a movie title link in the list that is displayed:

Administration toolbars consist of a title and a set of buttons that provide built-in functionality; it requires only a minimum amount of effort to add signifcant functionality to our administration page.

We add buttons to our toolbar in our view classes using the static JToolBarHelper class. In our administration/components/com_boxoffice/views folder we have two views, revues, and revue. In the revues/view.html.php file we generated the toolbar with the following code:

JToolBarHelper::title( JText::_( 'Box Office Revues' ),
'generic.png' );
JToolBarHelper::deleteList();
JToolBarHelper::editListX();
JToolBarHelper::addNewX();
JToolBarHelper::preferences( 'com_boxoffice', '200' );
JToolBarHelper::help( 'help', true );

In our example we set the title of our menu bar to Box Offce Revues, passing it through JText::_(), which will translate it if we have installed a language file. Next we add Delete, Edit, New, Preferences, and Help buttons.

Note that whenever we use JToolBarHelper we must set the title before we add any buttons.

There are many different buttons that we can add to the menu bar; if we cannot find a suitable button we can define our own. Most of the buttons behave as form buttons for the form adminForm, which we will discuss shortly. Some buttons require certain input fields to be included with the adminForm in order to function correctly. The following table lists the available buttons that we can add to the menu bar.

Method Name

Description

addNew

Adds an add new button to the menu bar.>

addNewX

Adds an extended version of the add new button calling hideMainMenu() before submitbutton().

apply

Adds an apply button to the menu bar.

archiveList

Adds an archive button to the menu bar.

assign

Adds an assign button to the menu bar.

back

Adds a back button to the menu bar.

cancel

Adds a cancel button to the menu bar.

custom

Adds a custom button to the menu bar.

customX

Adds an extended version of the custom button calling hideMainMenu() before submitbutton().

deleteList

Adds a delete button to the menu bar.

deleteListX

Adds an extended version of the delete button calling hideMainMenu() before submitbutton().

Divider

Adds a divider, a vertical line to the menu bar.

editCss

Adds an edit CSS button to the menu bar.

editCssX

Adds an extended version of the edit CSS button calling hideMainMenu() before submitbutton().

editHtml

Adds an edit HTML button to the menu bar.

editHtmlX

Adds an extended version of the edit HTML button calling hideMainMenu() before submitbutton().

editList

Adds an edit button to the menu bar.

editListX

Adds an extended version of the edit button calling hideMainMenu() before submitbutton().

help

Adds an Help button to the menu bar.

makeDefault

Adds an Default button to the menu bar.

media_manager

Adds an Media Manager button to the menu bar.

preferences

Adds a Preferences button to the menu bar.

preview

Adds a Preview button to the menu bar.

publish

Adds a Publish button to the menu bar.

publishList

Adds a Publish button to the menu bar.

save

Adds a Save button to the menu bar.

Spacer

Adds a sizable spacer to the menu bar.

title

Sets the Title and the icon class of the menu bar.

trash

Adds a Trash button to the menu bar.

unarchiveList

Adds an Unarchive button to the menu bar.

unpublish

Adds an Unpublish button to the menu bar.

unpublishList

Adds an Unpublish button to the menu bar.

Submenu

Directly below the main menu bar is an area reserved for the submenu. There are two methods available to populate the submenu. The submenu is automatically populated with items defined in the component XML manifest file. We can also modify the submenu, adding or removing menu items using the JSubMenuHelper class. We will begin by adding a submenu using the component XML manifest file. When we last updated our component XML manifest file we placed a menu item in the Administration section:

<menu>Box Office Revues</menu>

This placed a menu item under the Components menu. Our component utilizes a single table, #__boxoffice_revues, which stores specific information related to movie revues. One thing that might make our component more useful is to add the ability to categorize movies by genre (for example: action, romance, science fiction, and so on). Joomla!'s built-in #__categories table will make this easy to implement. We will need to make a few changes in several places so let's get started.

The first change we need to make is to modify our #_box_office_revues table, adding a foreign key field that will point to a record in the #__categories table. We will add one field to our table immediately after the primary key field id:

`catid` int(11) NOT NULL default '0',

If you have installed phpMyAdmin you can easily add this new field without losing any existing data. Be sure to update the install.sql file for future component installs.

Next we will add our submenu items to the component XML manifest file, immediately after the existing menu declaration:

<submenu>
<menu link="option=com_boxoffice">Revues</menu>
<menu link="option=com_categories
&amp;section=com_boxoffice">Categories</menu>

Note that we use &amp; rather than an ampersand (&) character to avoid problems with XML parsing.

Since we modifed our #__boxoffice_revues table we must update our JTable subclass /tables/revue.php to match by adding the following lines immediately after the id field:

/** @var int */
var $catid = 0;

And finally, we need to modify our layout /views/revue/tmpl/default.php to allow us to select a category or genre for our movie (place this immediately after the </tr> tag of the frst table row, the one that contains our movie title):

<tr>
<td width="100" align="right" class="key">
<label for="catid">
<?php echo JText::_('Movie Genre'); ?>:
</label>
</td>
<td>
<?php echo JHTML::_('list.category',
'catid',
'com_boxoffice',
$this->revue->catid );?>
</td>
</tr>

The call to JHTML::_() produces the HTML to display the selection drop-down list of component specifc categories. The static JHTML class is an integral part of the joomla.html library which we will discuss in the next section.

Creating submenu items through the component XML manifest file is not the only method at our disposal; we can modify the submenu using the static JSubMenuHelper class.

Please note however that these methods differ in a number of ways. Submenu items added using the manifest file will appear as submenu items under the Components menu item as well as the submenu area of the menu bar. For example the Components menu will appear as it does in the following screenshot:

The submenu items will appear on the component list page as shown in the following image:

And the submenu items will also appear on the Category Manager page:

If we were to use JSubMenuHelper class the submenu items would only appear on our component submenu bar; they would not appear on Components | Box Offce Revues or on the Category Manager submenu which would eliminate the means of returning to our component menu. For these reasons it is generally better to create submenus that link to other components using the XML manifest file.

There are, however, valid reasons for using JSubMenuHelper to create submenu items. If your component provides additional views of your data adding submenu items using JSubMenuHelper would be the more appropriate method for doing so. This example adds two options to the submenu using JSubMenuHelper:

// get the current task
$task = JRequest::getCmd('task');
if ($task == 'item1' || $task == 'item2')
{
// determine selected task
$selected = ($task == 'item1');
// prepare links
$item1 = 'index.php?option=com_myextension&task=item1';
$item2 = 'index.php?option=com_myextension&task=item2';
// add sub menu items
JSubMenuHelper::addEntry(JText::_('Item 1'), $item1,
$selected);
JSubMenuHelper::addEntry(JText::_('Item 2'), $item2,
$selected);
}

The addEntry() method adds a new item to the submenu. Items are added in order of appearance. The frst parameter is the name, the second is the link location, and the third is true if the item is the current menu item.

The next screenshot depicts the given example, in the component My Extension, when the selected task is Item1:

There is one more thing that we can do with the submenu. We can remove it. This is especially useful with views for which, when a user navigates away without following the correct procedure, an item becomes locked.

If we modify the hidemainmenu request value to 1, the submenu will not be displayed. We normally do this in methods in our controllers; a common method in which this would be done is edit(). This example demonstrates how:

JRequest::setVar('hidemainmenu', 1);

There is one other caveat when doing this; the main menu will be deactivated. This screenshot depicts the main menu across the top of backend:

This screenshot depicts the main menu across the top of backend when hidemainmenu is enabled; you will notice that all of the menu items are grayed out:

The joomla.html library

The joomla.html library provides a comprehensive set of classes for use in rendering XHMTL. An integral part of the library is the static JHTML class. Within this class is the class loader method JHTML::_(), that we will use to generate and render XHTML elements and JavaScript behaviors.

We generate an XHTML element or JavaScript behavior using the following method:

echo JHTML::_('type', 'parameter_1', …,'parameter_N');

The JHTML class supports eight basic XHTML element types; there are eight supporting classes that provide support for more complex XHTML element types and JavaScript behaviors. While we will not be using every available element type or behavior, we will make good use of a signifcant number of them throughout this article; enough for you to make use of others as the need arises.

The basic element types are:

calendar

Generates a calendar control field and a clickable calendar image

date

Returns a formatted date string

iframe

Generates a XHTML <iframe></iframe> element

image

Generates a XHTML <img></img> element

link

Generates a XHTML <a></a> element

script

Generates a XHTML <script></script> element

style

Generates a <link rel=”stylesheet” style=”text/css” /> element

tooltip

Generates a popup tooltip using JavaScript

There are eight supporting classes that provide more complex elements and behaviors that we generally define as grouped types. Grouped types are identifed by a group name and a type name. The supporting classes and group names are:

Class

Group

Description

JHTMLBehavior

behavior

Creates JavaScript client-side behaviors

JHTMLEmail

Email

Provides email address cloaking

JHTMLForm

Form

Generates a hidden token field

JHTMLGrid

Grid

Creates HTML form grids

JHTMLImage

image

Enables a type of image overriding in templates

JHTMLList

list

Generates common selection lists

JHTMLMenu

menu

Generates menus

JHTMLSelect

select

Generates dropdown selection boxes

All group types are invoked using the JHTML::_('group.type',…) syntax.

The following section provides an overview of the available group types.

behavior

These types are special because they deal with JavaScript in order to create client-side behaviors.

We'll use behavior.modal as an example. This behavior allows us to display an inline modal window that is populated from a specifc URI. A modal window is a window that prevents a user from returning to the originating window until the modal window has been closed. A good example of this is the 'Pagebreak' button used in the article manager when editing an article.

The behavior.modal type does not return anything; it prepares the necessary JavaScript. In fact, none of the behavior types return data; they are designed solely to import functionality into the document.

This example demonstrates how we can use the behavior.modal type to open a modal window that uses www.example.org as the source:

// prepare the JavaScript parameters
$params = array('size'=>array('x'=>100, 'y'=>100));
// add the JavaScript
JHTML::_('behavior.modal', 'a.mymodal', $params);
// create the modal window link
echo '<a class="mymodal" title="example"
href="http://www.example.org"
rel="{handler: \'iframe\',
size: {x: 400, y: 150}}">Example Modal Window</a>';

The a.mymodal parameter is used to identify the elements that we want to attach the modal window to. In this case, we want to use all <a> tags of class mymodal. This parameter is optional; the default selector is a.modal.

We use $params to specify default settings for modal windows. This list details the keys that we can use in this array to define default values:

  • ajaxOptions
  • size
  • onOpen
  • onClose
  • onUpdate
  • onResize
  • onMove
  • onShow
  • onHide

The link that we create can only be seen as special because of the JavaScript in the rel attribute. This JavaScript array is used to determine the exact behavior of the modal window for this link. We must always specify handler; this is used to determine how to parse the input from the link. In most cases, this will be iframe, but we can also use image, adopt, url, and string.

The size parameter is optional; here it is used to override the default specifed when we used the behavior.modal type to import the JavaScript. The settings have three layers of inheritance:

  • The default settings defined in the modal.js file
  • The settings we define when using the behavior.modal type
  • The settings we define when creating the link

This is a screenshot of the resultant modal window when the link is used :

Here are the behavior types:

calendar

Adds JavaScript to use the showCalendar() function

caption

Places the image title beneath an image

combobox

Adds JavaScript to add combo selection to text fields

formvalidation

Adds the generic JFormValidator JavaScript class to the document

keepalive

Adds JavaScript to maintain a user’s session

modal

Adds JavaScript to implement modal windows

mootools

Adds the MooTools JavaScript library to the document head

switcher

Adds JavaScript to toggle between hidden and displayed elements

tooltip

Adds JavaScript required to enable tooltips

tree

Instantiates the MooTools JavaScript class MooTree

uploader

Adds a dynamic file uploading mechanism using JavaScript

email

There is only one e-mail type.

cloak

Adds JavaScript to encrypt e-mail addresses in the browser

form

There is only one form type.

token

Generates a hidden token field to reduce the risk of CSRF exploits

grid

The grid types are used for displaying a dataset's item elements in a table of a backend form. There are seven grid types, each of which handles a commonly defined database field such as access, published, ordering, checked_out.

The grid types are used within a form named adminForm that must include a hidden field named boxchecked with a default value of 0 and another named task that will be used to determine which task a controller will execute.

To illustrate how the grid types are used we will use grid.id and grid.published along with our component database table #__boxoffice_revues that has a primary key field named id, a field named published, which we use to determine if an item should be displayed, and a field named name.

We can determine the published state of a record in our table by using grid.published.

This example demonstrates how we might process each record in a view form layout and output data into a grid or table ($this->revues is an array of objects representing records from the table):

<?php
$i = 0;
foreach ($this->revues as $row) :
$checkbox = JHTML::_('grid.id', ++$i, $row->id);
$published = JHTML::_('grid.published', $row, $i); ?>
<tr class=<?php echo "row$i%2"; ?>">
<td><?php echo $checkbox; ?></td>
<td><?php echo $row->name; ?></td>
<td align="center"><?php echo $published ?></td>
</tr>
<?php
endforeach;
?>

If $revues were to contain two objects named Item 1 and Item 2, of which only the frst object is published, the resulting table would look like this:

Not all of the grid types are used for data item elements. The grid.sort and grid.order types are used to render table column headings. The grid.state type is used to display an item state selection box, All, Published, Unpublished and, optionally, Archived and Trashed.

The grid types include:

access

Generates an access group text link

checkedOut

Generates selectable checkbox or small padlock image

id

Generates a selectable checkbox

order

Outputs a clickable image for every orderable column

published

Outputs a clickable image that toggles between published & unpublished

sort

Outputs a sortable heading for a grid/table column

state

Outputs a drop-down selection box called filter_state

image

We use the image types to perform a form of image overriding by determining if a template image is present before using a system default image.

We will use image.site to illustrate, using an image named edit.png:

echo JHTML::_('image.site', 'edit.png');

This will output an image tag for the image named edit.png. The image will be located in the currently selected template's /images folder. If edit.png is not found in the /images folder then the /images/M_images/edit.png file will be used.

We can change the default directories using the $directory and $param_directory parameters.

There are two image types, image.administrator and image.site.

administrator

Loads image from backend templates image directory or default image

site

Loads image from frontend templates image directory or default image

Mastering Joomla! 1.5 Extension and Framework Development The Professional Guide to Programming Joomla!
Published: November 2007
eBook Price: $26.99
Book Price: $49.99
See more
Select your format and quantity:

(Read more interesting articles on Joomla! 1.5 here.)

list

The list types are used for the generation of common selection lists. We'll take a look at the list.accesslevel type. This type produces a selection list of access level groups.

This type is relatively simple; it only requires one parameter, an object that includes the attribute access. This type is intended for use when modifying a single item, so in most cases the parameter will be an object representation of the item.

This code demonstrates how we might use list.accesslevel:

// get an item
$query = 'SELECT *'
.' FROM #__sections'
.' WHERE id = '.(int)$id;
$db =& JFactory::getDBO();
$db->setQuery($query);
$item = $db->loadObject();
echo JHTML::_('list.accesslevel', $item);

Assuming that the selected item has an attribute called access and it is 0 (Public), the resultant selection list will appear like this:

The list types are generally used to implement a flter when viewing itemized data or, as with list.accesslevel, for use when creating or modifying a single item. We will discuss how to use the list types to implement a flter later in this article.

accesslevel

Generates a drop-down selection box of access level groups

category

Generates a drop-down selection box of categories

genericordering

Generates an array of objects used with the select types

images

Generates a drop-down selection box of images in a directory

positions

Generates a drop-down selection box of positions

section

Generates a drop-down selection box of sections

specificordering

Generates a drop-down selection box of order positions

users

Generates a drop-down selection box of site users

menu

The menu types are designed specifcally for use with menus. It is unlikely that we should ever need to use any of these because menus are handled for us by Joomla!.However, the menu.treerecursetype may be of interest if we are rendering tree structures.

linkoptions

Generates an array of options representing menu items

ordering

Generates a drop-down list of menu items to facilitate menu ordering

treerecurse

Recursively builds an array of objects from menu items as a tree

select

The select types are intended to create selection boxes easily. They can be used to create drop-down selection boxes and radio selection buttons.

We will use select.genericlist as an example to create a drop-down selection box with three values. We'll call the drop-down selection box someoptions and use the second option as the default.

// prepare the options
$options = array();
$options[] = JHTML::_('select.option', '1', 'Option A');
$options[] = JHTML::_('select.option', '2', 'Option B');
$options[] = JHTML::_('select.option', '3', 'Option C');
// render the options
echo JHTML::_('select.genericlist', $options, 'someoptions',
null, 'value', 'text', '2');

The resultant drop-down selection box will look like this:

The select types include:

  • booleanlist-Generates a pair of radio button options with values of true or false
  • genericlist- Generates a drop-down selection list using an array of options
  • integerlist-Generates a drop-down selection list of integers
  • optgroup-Generates an object that represents an option group
  • option-Generates an object that represents a single selectable option
  • options-Generates the option tags for a XHTML select list
  • radiolist-Generates a radio button selection list

 

Component layouts (templates) revisited

When we think of templates we normally envisage site templates that detail precisely how our website will appear to our users. As we learned earlier, components have templates—or more precisely, layouts—to display our data in a comprehensible and presentable manner.

Layouts are PHP files that consist mainly of XHTML with small snippets of PHP to output data. Although there are no strict conventions on the way in which we use our templates, there are some common rules that we normally observe:

  • Do not process data
  • Use colon and endX in preference of curly braces
  • Encapsulate each line of PHP in its own PHP tags
  • Keep tag IDs lowercase and use underscore word separators
  • Indent for the XHTML, but not the PHP

This example shows a very basic layout that demonstrates each of the rules:

<div id="some_division">
<?php foreach ($this->items as $item) : ?>
<div id="item_<?php echo $item->id; ?>">
<?php echo $item->name; ?>
</div>
<?php endforeach; ?>
</div>

Take particular note of the use of the colon to denote the start of the foreach block, and endforeach to denote the end of the block. Using this alternative syntax often makes our layouts easier to read; just imagine hunting for the correct ending curly brace in a large template file!

You almost certainly noticed the use of $this in the example layout template. Layout templates are always invoked by a view; when we do this we actually incorporate the layout code into the view object's loadTemplate() method .

This means that the variable $this is referring to the view object from which the layout template was invoked. This is why we attach data to our view; it means that in the layout we can access all the data we added to view through $this.

Admin form

When we create templates for component backends that require a form, we must always name the form adminForm. This code demonstrates how we normally define adminForm in a template:

<form action="<?php echo $this->request_url; ?>"
method="post" name="adminForm" id="adminForm">

Instead of adding buttons to the form in the usual way we add buttons to the toolbar, as we discussed earlier.

It is normal when creating a form in the backend to also include JavaScript validation, although please note that we must never rely on JavaScript validation alone.

Here is an example of a script that verifes that a text field called name contains a value:

<script language="javascript" type="text/javascript">
<!--
function submitbutton(pressbutton)
{
var form = document.adminForm;
// No need to validate if cancelling
if (pressbutton == 'cancel')
{
submitform( pressbutton );
return;
}
// Do validation
if (form.name.value == "")
{
// no name supplied
alert("<?php echo JText::_('You must supply a name',
true); ?>" );
}
else
{
submitform( pressbutton );
}
}
</script>

Most important is our defning of the JavaScript function submitbutton(). This function is executed when toolbar buttons are used to submit a form.

The frst part of the function checks that the button that has been pressed is not cancel. If it is, then the function stops because no validation is required.

If the name field is empty we display an alert box. When we translate the text to show the alert, we provide a second parameter of true. This makes the translated text JavaScript safe.

If no validation problems are encountered we proceed to submit the form. In order to do this, we use a JavaScript function called submitform().

If you require more complex JavaScript form validation, you might want to investigate using JHTML::_(behavior.formvalidation).

Layout improvements

There are many ways we can improve our component functionality.

Adding a WYSIWYG editor

Let's start by adding a few features to our backend revue view layout found in the views/revue/tmpl/default.php file. The frst improvement that we will add is to change the revue field to use the system WYSIWYG editor. This is a fairly simple change but will add signifcant capabilities to our form, including the ability to format our revue using html tags

Open the default.php file and change the following code which is currently the last <td></td> entry in the file:

<td><input class="text_area" type="text" name="revue"
id="revue" size="50" maxlength="250"
value="<?php echo $this->revue->revue;?>" /></td>

We will change this code to the following:

<td>
<?php
$editor =& JFactory::getEditor();
$params = array('element_path' => '0',
'smilies' => '1',
'fullscreen' => '0',
'layer' => '0',
'xhtmlxtras' => '1' );
echo $editor->display('revue',
$this->revue->revue,
'100%', '100%', '70', '20',
true, $params );
?>
</td>

Let's take a quick look at what we just did. We frst obtained a reference to the global editor object.

We then created an array of parameters that will tailor our editor instance to our specifc requirements:

  • The editor tool buttons (elements) can be displayed either at the top of the editor window (element_path='1') or the bottom (element_path='0')
  • The second element tells the editor to add the smilies icons to the editor toolbar
  • The next element disables the ability to expand the editor window to full screen
  • The layer element is disabled; this removes HTML layer features
  • And finally, xhtmlxtras adds buttons for HTML cite, abbr, acronym, ins, del, and attribs tags

There are many other parameter settings that we could set but these will do fne for our needs. If you wish to learn more about all the available editor settings take a look at the {editor}.php file located in the /plugins/editors folder. Joomla! installs with two editors: xstandard.php and tinymce.php.

There are a number of third-party editors available; verify that the options are available when invoking them as we did previously.

In the final step we display the editor window. The JEditor::display() method is defined as follows:

display($name, $html, $width, $height, $col, $row, $buttons, $params)

  • string $name : The control name
  • string $html : The contents of the text area
  • string $width : The width of the text area (px or %)
  • string $height : The height of the text area (px or %)
  • integer $col : The number of columns for the textarea
  • integer $row : The number of rows for the textarea
  • boolean $buttons : Optional; if true the editor buttons will be displayed
  • array $params : Optional; an associative array of editor parameters
  • void : No Return

Here is what our edit area looks like with the TinyMCE editor:

Iterative layout templates

What will become apparent is that layout templates can grow very large and rapidly become both unmanageable and difficult to understand and maintain. The good news is that we can break layout templates into smaller, more manageable pieces. We can split layouts into common or iterative elements of layout code. A major advantage to splitting our layout code is to allow these layouts to be used by other layout templates.

These sub-templates should be prefixed with the word default_. For example if we had a sub-template to display a form it would be called default_form.php. For our component we will split our layout into three separate files: default.php, default_details.php, and default_revue.php,default.php.

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

<form action="index.php" method="post"
name="adminForm" id="adminForm">
<div class="col width-50">
<fieldset class="adminform">
<legend><?php echo JText::_( 'Details' ); ?></legend>
<?php echo $this->loadTemplate('details'); ?>
</fieldset>
</div>
<div class="col width-50">
<fieldset class="adminform">
<legend><?php echo JText::_( 'Revue' ); ?></legend>
<?php echo $this->loadTemplate('revue'); ?>
</fieldset>
</div>
<div class="clr"></div>

<input type="hidden" name="option"
value="<?php echo JRequest::getVar('option'); ?>" />
<input type="hidden" name="filter_order"
value="<?php echo $this->revue->order; ?>" />
<input type="hidden" name="id"
value="<?php echo $this->revue->id; ?>" />
<input type="hidden" name="task" value="" />
</form>

Now that we have split the default.php file into three files we can readily appreciate how much easier it is to determine how the form is configured. There are a few things that we have done to clean up the form which need some explanation. We have divided the form into two equal width areas; notice the <div class="col width-50"7gt; wrapper divisions. Joomla! has defined CSS class styles for creating columns with various widths; width-50 defines the width of a column as 50% of the page width.

We have wrapped the content of the default_details.php file within one column and the content of the default_revue.php file within the other column. Each column area is contained within a labeled fieldset.

We load the split layout files using the loadTemplate() method.default_details.php

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

<table class="admintable">

<tr>
<td width="100" align="right" class="key">
<label for="title">
<?php echo JText::_('Movie Title'); ?>:
</label>
</td>
<td>
<input class="inputbox" type="text"
name="title" id="title" size="25"
value="<?php echo $this->revue->title;?>" />
</td>
</tr>
<tr>
<td width="100" align="right" class="key">
<label for="catid">
<?php echo JText::_('Movie Genre'); ?>:
</label>
</td>
<td>
<?php
echo JHTML::_('list.category',
'catid', 'com_boxoffice',
$this->revue->catid );
?>
</td>
</tr>
<tr>
<td width="100" align="right" class="key">
<label for="rating">
<?php echo JText::_('Rating'); ?>:
</label>
</td>
<td>
<?php
$ratings = array();
$ratings[] =JHTML::_('select.option',
JText::_("MPAA_VK001"),
JText::_("MPAA_TK001"));
$ratings[] =JHTML::_('select.option',
JText::_("MPAA_VK002"),
JText::_("MPAA_TK002"));
$ratings[] =JHTML::_('select.option',
JText::_("MPAA_VK003"),
JText::_("MPAA_TK003"));
$ratings[] =JHTML::_('select.option',
JText::_("MPAA_VK004"),
JText::_("MPAA_TK004"));
$ratings[] =JHTML::_('select.option',
JText::_("MPAA_VK005"),
JText::_("MPAA_TK005"));
$ratings[] =JHTML::_('select.option',
JText::_("MPAA_VK006"),
JText::_("MPAA_TK006"));

echo JHTML::_('select.genericlist', $ratings,
'rating', null, 'value',
'text', $this->revue->rating);
?>
</td>
</tr>

<tr>
<td width="100" align="right" class="key">
<label for="quikquip">
<?php echo JText::_( 'Quik Quip' ); ?>:
</label>
</td>
<td>
<input class="text_area" type="text"
name="quikquip" id="quikquip"
size="32" maxlength="250"
value="<?php echo $this->revue->quikquip;?>" />
</td>
</tr>
<tr>
<td width="100" align="right" class="key">
<label for="revuer">
<?php echo JText::_('Revuer'); ?>:
</label>
</td>
<td>
<input class="inputbox" type="text"
name="revuer" id="revuer" size="50"
value="<?php echo $this->revue->revuer;?>" />
</td>
</tr>
<tr>
<td width="100" align="right" class="key">
<label for="stars">
<?php echo JText::_('Stars'); ?>:
</label>
</td>
<td>
<input class="inputbox" type="text"
name="stars" id="stars" size="10" maxlength="5"
value="<?php echo $this->revue->stars;?>" />
</td>
</tr>

<tr>
<td width="100" align="right" class="key">
<label for="revued">
<?php echo JText::_('Date Revued'); ?>:
</label>
</td>
<td>
<?php
echo JHTML::_('calendar',
JHTML::_('date', $this->revue->revued,
JTEXT::_('%m/%d/%Y')),
'revued', 'revued', '%m/%d/%Y',
array('class'=>'inputbox',
'size'=>'25', 'maxlength'=>'19'));
?>
</td>
</tr>
<tr>
<td width="100" align="right" class="key">
<label for="published">
<?php echo JText::_('Published'); ?>:
</label>
</td>
<td>
<?php
echo JHTML::_('select.booleanlist', 'published',
'class="inputbox"',
$this->revue->published);
?>
</td>
</tr>

</table>

While we are splitting the layout into three parts we are going to make a few changes that use the joomla.html library.

The first change we will discuss is one we made earlier in the article when we added a drop-down selection box for our movie category/genre list. We used the group type list.category to generate the drop-down selection box:

<?php echo JHTML::_('list.category', 'catid', 'com_boxoffice',

$this->revue->catid);?>

The first parameter is the group and type that will be called, 'list.category'. The next parameter is the HTML name for the list, 'catid'. The third parameter is the section name. Component categories belong to a section that uses the component name; in our case this is 'com_boxoffice'. The final parameter is the id of the category that is currently selected. There are additional optional parameters that can be specified but for our use the defaults are sufficient.

The next change uses two group types, select.option and select.genericlist, to provide a drop-down list of ratings. We first build an array of options that will be used by the select list. The select.option method takes a key and a value which we provide with calls to JText::_(). The strings that are passed are translation keys located in our translation file administrator/language/en-GB/en-GB.com_boxoffice.ini. We have only created a British English translation file; we could create and place additional translation files for other languages we support in their appropriate directories. We will discuss translation files in more detail in the next chapter. Here are the entries used for our ratings drop-down:

# MPAA Ratings

MPAA_VK001=NR
MPAA_TK001=Not Rated (NR)
MPAA_VK002=G
MPAA_TK002=General Audiences (G)
MPAA_VK003=PG
MPAA_TK003=Parental Guidance Suggested (PG)
MPAA_VK004=PG-13
MPAA_TK004=Parents Strongly Cautioned (PG-13)
MPAA_VK005=R
MPAA_TK005=Restricted (R)
MPAA_VK006=NC-17
MPAA_TK006=17 and under not admitted (NC-17)

JText::_() looks for the key within the language translation file and returns the string to the right of the equals sign. In our code above, the first array element will contain an object with two properties, a key of 'NR' and a value of 'Not Rated (NR)'.

The select.genericlist takes a number of parameters. The first is the html name attribute for the select tag, followed by any additional attributes (we have none so we pass null), followed by the property names for the key and value attributes (key='value' and value='text'). The last parameter is the currently selected option.

We have replaced the simple text box for entering a date with a nested set of basic element types, calendar and date. JHTML::_('date',…) returns a formatted date string which is placed within an calendar control text box generated by JHTML::_('calendar',…). The calendar control consists of an input text box and a small clickable calendar image that when clicked, pops up a calendar from which you can select a date.

Our final change is to add a pair of radio buttons using select.booleanlist to provide an opportunity to publish the revue. The first parameter is the HTML name attribute, followed by additional html attributes ('class="inputbox"'), and then the currently selected option.

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

<table class="admintable" width="100%">

<tr>
<td>
<?php
$editor =& JFactory::getEditor();
$params = array('element_path' => '0',
'smilies' => '1',
'fullscreen' => '0',
'layer' => '0',
'xhtmlxtras' => '1');

echo $editor->display('revue', $this->revue->revue,
'100%', '100%', '70', '20',
true, $params);
?>
</td>
</tr>
</table>

Our third file, default_revue.php, contains the editor display. Let's take a look at the form now:

This is a much better presentation than our earlier form. We can now create a revue using a WYSIWYG editor and we can select a genre or category for the movie. We also have a translatable drop-down list of ratings, a nice calendar or date picker, and a simple pair of radio buttons to publish or unpublish. But we can do more.

Summary

In this article, we have covered:

  • How to Improve toolbars in the backend
  • How to Modify the Submenu
  • The joomla.html library
  • How to Build better layouts and templates

If you have read this article you may be interested to view:

Mastering Joomla! 1.5 Extension and Framework Development The Professional Guide to Programming Joomla!
Published: November 2007
eBook Price: $26.99
Book Price: $49.99
See more
Select your format and quantity:

About the Author :


James Kennard

James Kennard is a computer programmer. He has worked with various PHP and MySQL applications, since 2002. He quickly discovered Mambo/Joomla! because of its flexible extension manager. James currently maintains one open-source Joomla! component, which has been translated into over fifteen languages. Moreover, he has plans to build two more open-source components. Examples of his work can be found on his personal website www.webamoeba.co.uk.

Books From Packt


Joomla! 1.5 SEO
Joomla! 1.5 SEO

Joomla! 1.5: Beginner's Guide
Joomla! 1.5: Beginner's Guide

Joomla! E-Commerce with VirtueMart
Joomla! E-Commerce with VirtueMart

Joomla! 1.5 Multimedia
Joomla! 1.5 Multimedia

Joomla! 1.5 Content Administration
Joomla! 1.5 Content Administration

Learning Joomla! 1.5 Extension Development
Learning Joomla! 1.5 Extension Development

Joomla! with Flash
Joomla! with Flash

Joomla! Web Security
Joomla! Web Security


Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software