Developing a Model-View-Controller (MVC) Component for Joomla!1.6 – Part 09

http://docs.joomla.org

Introduction

This tutorial is part of the Developing a Model-View-Controller (MVC) Component for Joomla!1.6 tutorial. You are encouraged to read the previous parts of the tutorial before reading this.

Adding a toolbar

In Joomla!1.6, the administrator interacts generally with components through the use of a toolbar. In the file admin/views/helloworlds/view.html.php put this content. It will create a basic toolbar and a title for the component.

admin/views/helloworlds/view.html.php

<?php  // No direct access to this file  defined('_JEXEC') or die('Restricted access');     // import Joomla view library  jimport('joomla.application.component.view');     /**   * HelloWorlds View   */  class HelloWorldViewHelloWorlds extends JView  {  	/**  	 * HelloWorlds view display method  	 * @return void  	 */  	function display($tpl = null)   	{  		// Get data from the model  		$items = $this->get('Items');  		$pagination = $this->get('Pagination');     		// Check for errors.  		if (count($errors = $this->get('Errors')))   		{  			JError::raiseError(500, implode('<br />', $errors));  			return false;  		}  		// Assign data to the view  		$this->items = $items;  		$this->pagination = $pagination;     		// Set the toolbar  		$this->addToolBar();     		// Display the template  		parent::display($tpl);  	}     	/**  	 * Setting the toolbar  	 */  	protected function addToolBar()   	{  		JToolBarHelper::title(JText::_('COM_HELLOWORLD_MANAGER_HELLOWORLDS'));  		JToolBarHelper::deleteList('', 'helloworlds.delete');  		JToolBarHelper::editList('helloworld.edit');  		JToolBarHelper::addNew('helloworld.add');  	}  }  

You can find others classic backend actions in the administrator/includes/toolbar.php file of your Joomla!1.6 installation.

Since the view can perform some actions, we have to add some input data. With your favorite file manager and editor, put in the file admin/views/helloworlds/tmpl/default.php

admin/views/helloworlds/tmpl/default.php

<?php  // No direct access to this file  defined('_JEXEC') or die('Restricted Access');  // load tooltip behavior  JHtml::_('behavior.tooltip');  ?>  <form action="<?php echo JRoute::_('index.php?option=com_helloworld'); ?>" method="post" name="adminForm">  	<table class="adminlist">  		<thead><?php echo $this->loadTemplate('head');?></thead>  		<tfoot><?php echo $this->loadTemplate('foot');?></tfoot>  		<tbody><?php echo $this->loadTemplate('body');?></tbody>  	</table>  	<div>  		<input type="hidden" name="task" value="" />  		<input type="hidden" name="boxchecked" value="0" />  		<?php echo JHtml::_('form.token'); ?>  	</div>  </form>  

Adding specific controllers

Three actions have been added:

  • helloworlds.delete
  • helloworld.edit
  • helloworld.add

These are compound tasks (controller.task). So two new controllers HelloWorldControllerHelloWorlds and HelloWorldControllerHelloWorld have to be coded.

admin/controllers/helloworlds.php

<?php  // No direct access to this file  defined('_JEXEC') or die('Restricted access');     // import Joomla controlleradmin library  jimport('joomla.application.component.controlleradmin');     /**   * HelloWorlds Controller   */  class HelloWorldControllerHelloWorlds extends JControllerAdmin  {  	/**  	 * Proxy for getModel.  	 * @since	1.6  	 */  	public function getModel($name = 'HelloWorld', $prefix = 'HelloWorldModel')   	{  		$model = parent::getModel($name, $prefix, array('ignore_request' => true));  		return $model;  	}  }  

admin/controllers/helloworld.php

<?php  // No direct access to this file  defined('_JEXEC') or die('Restricted access');     // import Joomla controllerform library  jimport('joomla.application.component.controllerform');     /**   * HelloWorld Controller   */  class HelloWorldControllerHelloWorld extends JControllerForm  {  }  

Adding an editing view

With your favorite file manager and editor, put a file admin/views/helloworld/view.html.php containing:

admin/views/helloworld/view.html.php

<?php  // No direct access to this file  defined('_JEXEC') or die('Restricted access');     // import Joomla view library  jimport('joomla.application.component.view');     /**   * HelloWorld View   */  class HelloWorldViewHelloWorld extends JView  {  	/**  	 * display method of Hello view  	 * @return void  	 */  	public function display($tpl = null)   	{  		// get the Data  		$form = $this->get('Form');  		$item = $this->get('Item');     		// Check for errors.  		if (count($errors = $this->get('Errors')))   		{  			JError::raiseError(500, implode('<br />', $errors));  			return false;  		}  		// Assign the Data  		$this->form = $form;  		$this->item = $item;     		// Set the toolbar  		$this->addToolBar();     		// Display the template  		parent::display($tpl);  	}     	/**  	 * Setting the toolbar  	 */  	protected function addToolBar()   	{  		JRequest::setVar('hidemainmenu', true);  		$isNew = ($this->item->id == 0);  		JToolBarHelper::title($isNew ? JText::_('COM_HELLOWORLD_MANAGER_HELLOWORLD_NEW') : JText::_('COM_HELLOWORLD_MANAGER_HELLOWORLD_EDIT'));  		JToolBarHelper::save('helloworld.save');  		JToolBarHelper::cancel('helloworld.cancel', $isNew ? 'JTOOLBAR_CANCEL' : 'JTOOLBAR_CLOSE');  	}  }  

This view will display data using a layout.

Put a file admin/views/helloworld/tmpl/edit.php containing

admin/views/helloworld/tmpl/edit.php

<?php  // No direct access  defined('_JEXEC') or die('Restricted access');  JHtml::_('behavior.tooltip');  ?>  <form action="<?php echo JRoute::_('index.php?option=com_helloworld&layout=edit&id='.(int) $this->item->id); ?>" method="post" name="adminForm" id="helloworld-form">  	<fieldset class="adminform">  		<legend><?php echo JText::_( 'COM_HELLOWORLD_HELLOWORLD_DETAILS' ); ?></legend>  		<ul class="adminformlist">  <?php foreach($this->form->getFieldset() as $field): ?>  			<li><?php echo $field->label;echo $field->input;?></li>  <?php endforeach; ?>  		</ul>  	</fieldset>  	<div>  		<input type="hidden" name="task" value="helloworld.edit" />  		<?php echo JHtml::_('form.token'); ?>  	</div>  </form>  

Adding a model and modifying the existing one

The HelloWorldViewHelloWorld view asks form and data from a model. This model has to provide a getTable, a getForm method and a loadData method (called from the JModelAdmin controller)

admin/models/helloworld.php

<?php  // No direct access to this file  defined('_JEXEC') or die('Restricted access');     // import Joomla modelform library  jimport('joomla.application.component.modeladmin');     /**   * HelloWorld Model   */  class HelloWorldModelHelloWorld extends JModelAdmin  {  	/**  	 * Returns a reference to the a Table object, always creating it.  	 *  	 * @param	type	The table type to instantiate  	 * @param	string	A prefix for the table class name. Optional.  	 * @param	array	Configuration array for model. Optional.  	 * @return	JTable	A database object  	 * @since	1.6  	 */  	public function getTable($type = 'HelloWorld', $prefix = 'HelloWorldTable', $config = array())   	{  		return JTable::getInstance($type, $prefix, $config);  	}  	/**  	 * Method to get the record form.  	 *  	 * @param	array	$data		Data for the form.  	 * @param	boolean	$loadData	True if the form is to load its own data (default case), false if not.  	 * @return	mixed	A JForm object on success, false on failure  	 * @since	1.6  	 */  	public function getForm($data = array(), $loadData = true)   	{  		// Get the form.  		$form = $this->loadForm('com_helloworld.helloworld', 'helloworld', array('control' => 'jform', 'load_data' => $loadData));  		if (empty($form))   		{  			return false;  		}  		return $form;  	}  	/**  	 * Method to get the data that should be injected in the form.  	 *  	 * @return	mixed	The data for the form.  	 * @since	1.6  	 */  	protected function loadFormData()   	{  		// Check the session for previously entered form data.  		$data = JFactory::getApplication()->getUserState('com_helloworld.edit.helloworld.data', array());  		if (empty($data))   		{  			$data = $this->getItem();  		}  		return $data;  	}  }  

This model inherits from the JModelAdmin class and uses its loadForm method. This method searches for forms in the forms folder. With your favorite file manager and editor, put a file admin/models/forms/helloworld.xml containing:

admin/models/forms/helloworld.xml

<?xml version="1.0" encoding="utf-8"?>  <form>  	<fieldset>  		<field  			name="id"  			type="hidden"  		/>  		<field  			name="greeting"  			type="text"  			label="COM_HELLOWORLD_HELLOWORLD_GREETING_LABEL"  			description="COM_HELLOWORLD_HELLOWORLD_GREETING_DESC"  			size="40"  			class="inputbox"  			default=""  		/>  	</fieldset>  </form>  

Packaging the component

Content of your code directory

Create a compressed file of this directory or directly download the archive, modify the code in /admin/models/helloworld.php and install it using the extension manager of Joomla!1.6. You can add a menu item of this component using the menu manager in the backend.

helloworld.xml

<?xml version="1.0" encoding="utf-8"?>  <extension type="component" version="1.6.0" method="upgrade">     	<name>Hello World!</name>  	<!-- The following elements are optional and free of formatting conttraints -->  	<creationDate>November 2009</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>0.0.9</version>  	<!-- The description is optional and defaults to the name -->  	<description>COM_HELLOWORLD_DESCRIPTION</description>     	<install> <!-- Runs on install -->  		<sql>  			<file driver="mysql" charset="utf8">sql/install.mysql.utf8.sql</file>  		</sql>  	</install>  	<uninstall> <!-- Runs on uninstall -->  		<sql>  			<file driver="mysql" charset="utf8">sql/uninstall.mysql.utf8.sql</file>  		</sql>  	</uninstall>  	<update> <!-- Runs on update; New in 1.6 -->  		<schemas>  			<schemapath type="mysql">sql/updates/mysql</schemapath>  		</schemas>  	</update>     	<!-- 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>helloworld.php</filename>  		<filename>controller.php</filename>  		<folder>views</folder>  		<folder>models</folder>  		<folder>language</folder>  	</files>     	<administration>  		<!-- Administration Menu Section -->  		<menu>COM_HELLOWORLD_MENU</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">  			<!-- Admin Main File Copy Section -->  			<filename>index.html</filename>  			<filename>helloworld.php</filename>  			<filename>controller.php</filename>  			<!-- SQL files section -->  			<folder>sql</folder>  			<!-- tables files section -->  			<folder>tables</folder>  			<!-- models files section -->  			<folder>models</folder>  			<!-- views files section -->  			<folder>views</folder>  			<!-- controllers files section -->  			<folder>controllers</folder>  		</files>     		<languages folder="admin">  			<language tag="en-GB">language/en-GB/en-GB.com_helloworld.ini</language>  			<language tag="en-GB">language/en-GB/en-GB.com_helloworld.sys.ini</language>  		</languages>  	</administration>     </extension>  

Advertisements

Developing a Model-View-Controller (MVC) Component for Joomla!1.6 – Part 08

http://docs.joomla.org/

Introduction

This tutorial is part of the Developing a Model-View-Controller (MVC) Component for Joomla!1.6 tutorial. You are encouraged to read the previous parts of the tutorial before reading this.

Joomla!1.6 manages languages for components in four different situations:

  • displaying a component in the public site
  • managing a component in the backend
  • managing menus in the backend
  • installing a component (new in 1.6)

Joomla!1.6 uses two different location folder for languages:

  • one in administrator/language or language
  • one in the component folder (administrator/component/*component*/language or component/*component*/language)

It depends how the component is installed.

Adding language translation in the public site

With your favorite file manager and editor, put a file site/language/en-GB/en-GB.com_helloworld.ini. This file will contain translation for the public part. For the moment, this file is empty

site/language/en-GB/en-GB.com_helloworld.ini

   

For the moment, there are no translations strings in this file.

Adding language translation when managing the component

With your favorite file manager and editor, put a file admin/language/en-GB/en-GB.com_helloworld.ini. This file will contain translation for the backend part.

admin/language/en-GB/en-GB.com_helloworld.ini

COM_HELLOWORLD_HELLOWORLD_FIELD_GREETING_DESC="This message will be displayed"  COM_HELLOWORLD_HELLOWORLD_FIELD_GREETING_LABEL="Message"  COM_HELLOWORLD_HELLOWORLD_HEADING_GREETING="Greeting"  COM_HELLOWORLD_HELLOWORLD_HEADING_ID="Id"  

Adding language translation when managing the menus in the backend

With your favorite file manager and editor, put a file admin/language/en-GB/en-GB.com_helloworld.sys.ini. This file will contain translation for the backend part.

admin/language/en-GB/en-GB.com_helloworld.sys.ini

COM_HELLOWORLD="Hello World!"  COM_HELLOWORLD_DESCRIPTION="This is the Hello World description"  COM_HELLOWORLD_HELLOWORLD_VIEW_DEFAULT_TITLE="Hello World"  COM_HELLOWORLD_HELLOWORLD_VIEW_DEFAULT_DESC="This view displays a selected message"  COM_HELLOWORLD_MENU="Hello World!"  

Adding translation when installing the component

With your favorite file manager and editor, put a file language/en-GB/en-GB.ini. This file will contain translation for the install.

language/en-GB/en-GB.ini

COM_HELLOWORLD="Hello World!"  COM_HELLOWORLD_DESCRIPTION="This is the Hello World description"  

The COM_HELLOWORLD_DESCRIPTION can be used in the helloworld.xml file

Packaging the component

Content of your code directory

Create a compressed file of this directory or directly download the archive and install it using the extension manager of Joomla!1.6. You can add a menu item of this component using the menu manager in the backend.

helloworld.xml

<?xml version="1.0" encoding="utf-8"?>  <extension type="component" version="1.6.0" method="upgrade">     	<name>COM_HELLOWORLD</name>  	<!-- The following elements are optional and free of formatting conttraints -->  	<creationDate>November 2009</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>0.0.8</version>  	<!-- The description is optional and defaults to the name -->  	<description>COM_HELLOWORLD_DESCRIPTION</description>     	<install> <!-- Runs on install -->  		<sql>  			<file driver="mysql" charset="utf8">sql/install.mysql.utf8.sql</file>  		</sql>  	</install>  	<uninstall> <!-- Runs on uninstall -->  		<sql>  			<file driver="mysql" charset="utf8">sql/uninstall.mysql.utf8.sql</file>  		</sql>  	</uninstall>  	<update> <!-- Runs on update; New in 1.6 -->  		<schemas>  			<schemapath type="mysql">sql/updates/mysql</schemapath>  		</schemas>  	</update>     	<!-- 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>helloworld.php</filename>  		<filename>controller.php</filename>  		<folder>views</folder>  		<folder>models</folder>  		<folder>language</folder>  	</files>     	<administration>  		<!-- Administration Menu Section -->  		<menu>COM_HELLOWORLD_MENU</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">  			<!-- Admin Main File Copy Section -->  			<filename>index.html</filename>  			<filename>helloworld.php</filename>  			<filename>controller.php</filename>  			<!-- SQL files section -->  			<folder>sql</folder>  			<!-- tables files section -->  			<folder>tables</folder>  			<!-- models files section -->  			<folder>models</folder>  			<!-- views files section -->  			<folder>views</folder>  		</files>  		<languages folder="admin">  			<language tag="en-GB">language/en-GB/en-GB.com_helloworld.ini</language>  			<language tag="en-GB">language/en-GB/en-GB.com_helloworld.sys.ini</language>  		</languages>  	</administration>     </extension>  

In this helloworld.xml file, languages are installed in:

  • administrator/language for the admin part (look at the xml languages tag)
  • components/com_helloworld/language for the site part (there are no xml languages tag in the site part of the xml description file, but the language folder is included)

Developing a Model-View-Controller (MVC) Component for Joomla!1.6 – Part 07

http://docs.joomla.org

Introduction

This tutorial is part of the Developing a Model-View-Controller (MVC) Component for Joomla!1.6 tutorial. You are encouraged to read the previous parts of the tutorial before reading this.

Basic backend

Designing the backend interface leads us to create at least a Model-View-Controller triptych. We have to modify the administrator entry point of our component, the admin/helloworld.php file

admin/helloworld.php

<?php  // No direct access to this file  defined('_JEXEC') or die('Restricted access');     // import joomla controller library  jimport('joomla.application.component.controller');     // Get an instance of the controller prefixed by HelloWorld  $controller = JController::getInstance('HelloWorld');     // Perform the Request task  $controller->execute(JRequest::getCmd('task'));     // Redirect if set by the controller  $controller->redirect();  

Create the general controller

The entry point now get an instance of a HelloWorld prefixed controller. Let create a basic controller for the administrator part:

admin/controller.php

<?php  // No direct access to this file  defined('_JEXEC') or die('Restricted access');     // import Joomla controller library  jimport('joomla.application.component.controller');     /**   * General Controller of HelloWorld component   */  class HelloWorldController extends JController  {  	/**  	 * display task  	 *  	 * @return void  	 */  	function display($cachable = false)   	{  		// set default view if not set  		JRequest::setVar('view', JRequest::getCmd('view', 'HelloWorlds'));     		// call parent behavior  		parent::display($cachable);  	}  }  

This controller will display the ‘HelloWorlds view by default.

Create the view

With your favorite file manager and editor, create a file admin/views/helloworlds/view.html.php containing:

admin/views/helloworlds/view.html.php

<?php  // No direct access to this file  defined('_JEXEC') or die('Restricted access');     // import Joomla view library  jimport('joomla.application.component.view');     /**   * HelloWorlds View   */  class HelloWorldViewHelloWorlds extends JView  {  	/**  	 * HelloWorlds view display method  	 * @return void  	 */  	function display($tpl = null)   	{  		// Get data from the model  		$items = $this->get('Items');  		$pagination = $this->get('Pagination');     		// Check for errors.  		if (count($errors = $this->get('Errors')))   		{  			JError::raiseError(500, implode('<br />', $errors));  			return false;  		}  		// Assign data to the view  		$this->items = $items;  		$this->pagination = $pagination;     		// Display the template  		parent::display($tpl);  	}  }  

In Joomla, views display data using layout. With your favorite file manager and editor, put a file admin/views/helloworlds/tmpl/default.php containing

admin/views/helloworlds/tmpl/default.php

<?php  // No direct access to this file  defined('_JEXEC') or die('Restricted Access');     // load tooltip behavior  JHtml::_('behavior.tooltip');  ?>  <form action="<?php echo JRoute::_('index.php?option=com_helloworld'); ?>" method="post" name="adminForm">  	<table class="adminlist">  		<thead><?php echo $this->loadTemplate('head');?></thead>  		<tfoot><?php echo $this->loadTemplate('foot');?></tfoot>  		<tbody><?php echo $this->loadTemplate('body');?></tbody>  	</table>  </form>  

This layout calls several sub-layout (head, foot and body). Each sub-layout corresponds to a file prefixed by the name of the main layout (default), and an underscore.

Put a file admin/views/helloworlds/tmpl/default_head.php containing

admin/views/helloworlds/tmpl/default_head.php

<?php  // No direct access to this file  defined('_JEXEC') or die('Restricted Access');  ?>  <tr>  	<th width="5">  		<?php echo JText::_('COM_HELLOWORLD_HELLOWORLD_HEADING_ID'); ?>  	</th>  	<th width="20">  		<input type="checkbox" name="toggle" value="" onclick="checkAll(<?php echo count($this->items); ?>);" />  	</th>			  	<th>  		<?php echo JText::_('COM_HELLOWORLD_HELLOWORLD_HEADING_GREETING'); ?>  	</th>  </tr>  

checkAll is a javascript function defined in the Joomla core able to check all items.

Put a file admin/views/helloworlds/tmpl/default_body.php containing

admin/views/helloworlds/tmpl/default_body.php

<?php  // No direct access to this file  defined('_JEXEC') or die('Restricted Access');  ?>  <?php foreach($this->items as $i => $item): ?>  	<tr class="row<?php echo $i % 2; ?>">  		<td>  			<?php echo $item->id; ?>  		</td>  		<td>  			<?php echo JHtml::_('grid.id', $i, $item->id); ?>  		</td>  		<td>  			<?php echo $item->greeting; ?>  		</td>  	</tr>  <?php endforeach; ?>  

JHtml::_ is a helper function able to display several HTML output. In this case, it will display a checkbox for the item.

Put a file admin/views/helloworlds/tmpl/default_foot.php containing

admin/views/helloworlds/tmpl/default_foot.php

<?php  // No direct access to this file  defined('_JEXEC') or die('Restricted Access');  ?>  <tr>  	<td colspan="3"><?php echo $this->pagination->getListFooter(); ?></td>  </tr>  

JPagination is a Joomla class able to manage and display pagination object.

Create the model

The HelloWorlds view asks the model for data. In Joomla!1.6, there is a class able to manage list of data: JModelList. Class JModelList and inherited classes needs only one method:

  • getListQuery which constructs and SQL query

and two states:

  • list.start for determining the list offset
  • list.limit for determining the list length

getItems and getPagination method are defined in JModelList class. They don’t need to be defined in the HelloWorldModelHelloWorlds class.

admin/models/helloworlds.php

<?php  // No direct access to this file  defined('_JEXEC') or die('Restricted access');  // import the Joomla modellist library  jimport('joomla.application.component.modellist');  /**   * HelloWorldList Model   */  class HelloWorldModelHelloWorlds extends JModelList  {  	/**  	 * Method to build an SQL query to load the list data.  	 *  	 * @return	string	An SQL query  	 */  	protected function getListQuery()  	{  		// Create a new query object.		  		$db = JFactory::getDBO();  		$query = $db->getQuery(true);  		// Select some fields  		$query->select('id,greeting');  		// From the hello table  		$query->from('#__helloworld');  		return $query;  	}  }  

The _populateState method is, by default, automatically called when a state is read by the getState method.

Packaging the component

Content of your code directory

Create a compressed file of this directory or directly download the archive and install it using the extension manager of Joomla!1.6. You can add a menu item of this component using the menu manager in the backend.

helloworld.xml

<?xml version="1.0" encoding="utf-8"?>  <extension type="component" version="1.6.0" method="upgrade">  	<name>Hello World!</name>  	<creationDate>November 2009</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>  	<version>0.0.7</version>  	<description>Description of the Hello World component ...</description>     	<install> <!-- Runs on install -->  		<sql>  			<file driver="mysql" charset="utf8">sql/install.mysql.utf8.sql</file>  		</sql>  	</install>  	<uninstall> <!-- Runs on uninstall -->  		<sql>  			<file driver="mysql" charset="utf8">sql/uninstall.mysql.utf8.sql</file>  		</sql>  	</uninstall>  	<update> <!-- Runs on update; New in 1.6 -->  		<schemas>  			<schemapath type="mysql">sql/updates/mysql</schemapath>  		</schemas>  	</update>     	<files folder="site">  		<filename>index.html</filename>  		<filename>helloworld.php</filename>  		<filename>controller.php</filename>  		<folder>views</folder>  		<folder>models</folder>  	</files>     	<administration>  		<menu>Hello World!</menu>  		<files folder="admin">  			<filename>index.html</filename>  			<filename>helloworld.php</filename>  			<filename>controller.php</filename>  			<folder>sql</folder>  			<folder>tables</folder>  			<folder>models</folder>  			<!-- views files section -->  			<folder>views</folder>  		</files>		  	</administration>  </extension>  

Now you can see in your component hello-world an array with two colums, two rows and checkboxes. You can click the checkboxes in order to select the different options you want.

Developing a Model-View-Controller (MVC) Component for Joomla!1.6 – Part 06

http://docs.joomla.org

Introduction

This tutorial is part of the Developing a Model-View-Controller (MVC) Component for Joomla!1.6 tutorial. You are encouraged to read the previous parts of the tutorial before reading this.

Using the database

Components usually manage their contents using the database. During the install/uninstall/update phase of a component, you can execute SQL queries through the use of SQL text files.

With your favorite file manager and editor put two files admin/sql/install.mysql.utf8.sql and admin/sql/updates/mysql/0.0.6.sql containing:

admin/sql/install.mysql.utf8.sql and admin/sql/updates/mysql/0.0.6.sql

DROP TABLE IF EXISTS `#__helloworld`;     CREATE TABLE `#__helloworld` (    `id` int(11) NOT NULL AUTO_INCREMENT,    `greeting` varchar(25) NOT NULL,     PRIMARY KEY  (`id`)  ) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;     INSERT INTO `#__helloworld` (`greeting`) VALUES  	('Hello World!'),  	('Good bye World!');  

This is the install file. It will be executed if your put an appropriate order in the helloworld.xml file

helloworld.xml

<?xml version="1.0" encoding="utf-8"?>  <extension type="component" version="1.6.0" method="upgrade">     	<name>Hello World!</name>  	<!-- The following elements are optional and free of formatting conttraints -->  	<creationDate>November 2009</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>0.0.6</version>  	<!-- The description is optional and defaults to the name -->  	<description>Description of the Hello World component ...</description>     	<install> <!-- Runs on install -->  		<sql>  			<file driver="mysql" charset="utf8">sql/install.mysql.utf8.sql</file>  		</sql>  	</install>  	<uninstall> <!-- Runs on uninstall -->  		<sql>  			<file driver="mysql" charset="utf8">sql/uninstall.mysql.utf8.sql</file>  		</sql>  	</uninstall>  	<update> <!-- Runs on update; New in 1.6 -->  		<schemas>  			<schemapath type="mysql">sql/updates/mysql</schemapath>  		</schemas>  	</update>     	<!-- 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>helloworld.php</filename>  		<filename>controller.php</filename>  		<folder>views</folder>  		<folder>models</folder>  	</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">  			<!-- Admin Main File Copy Section -->  			<filename>index.html</filename>  			<filename>helloworld.php</filename>  			<!-- SQL files section -->  			<folder>sql</folder>  			<!-- tables files section -->  			<folder>tables</folder>  			<!-- models files section -->  			<folder>models</folder>  		</files>  	</administration>     </extension>  

Do the same for the uninstall file:

With your favorite file manager and editor put a file admin/sql/uninstall.mysql.utf8.sql containing:

admin/sql/uninstall.mysql.utf8.sql

DROP TABLE IF EXISTS `#__helloworld`;  

Adding a new field type

For the moment, we have used a hard coded field type for messages. We need to use our database for choosing the message.

Modify the site/views/helloworld/tmpl/default.xml file and put these lines

site/views/helloworld/tmpl/default.xml

<?xml version="1.0" encoding="utf-8"?>  <metadata>  	<layout title="COM_HELLOWORLD_HELLOWORLD_VIEW_DEFAULT_TITLE">  		<message>COM_HELLOWORLD_HELLOWORLD_VIEW_DEFAULT_DESC</message>  	</layout>  	<fields  		name="request"  		addfieldpath="/administrator/components/com_helloworld/models/fields"  	>  		<fieldset name="request">  			<field  				name="id"  				type="helloworld"  				label="COM_HELLOWORLD_HELLOWORLD_FIELD_GREETING_LABEL"  				description="COM_HELLOWORLD_HELLOWORLD_FIELD_GREETING_DESC"  			/>  		</fieldset>  	</fields>  </metadata>  

It introduces a new field type and tells Joomla to look for the field definition in the /administrator/components/com_helloworld/models/fields folder.

With your favorite file manager and editor put a file admin/models/fields/helloworld.php file containing:

admin/models/fields/helloworld.php

<?php  // No direct access to this file  defined('_JEXEC') or die;     // import the list field type  jimport('joomla.form.helper');  JFormHelper::loadFieldClass('list');     /**   * HelloWorld Form Field class for the HelloWorld component   */  class JFormFieldHelloWorld extends JFormFieldList  {  	/**  	 * The field type.  	 *  	 * @var		string  	 */  	protected $type = 'HelloWorld';     	/**  	 * Method to get a list of options for a list input.  	 *  	 * @return	array		An array of JHtml options.  	 */  	protected function getOptions()   	{  		$db = JFactory::getDBO();  		$query = $db->getQuery(true);  		$query->select('id,greeting');  		$query->from('#__helloworld');  		$db->setQuery((string)$query);  		$messages = $db->loadObjectList();  		$options = array();  		if ($messages)  		{  			foreach($messages as $message)   			{  				$options[] = JHtml::_('select.option', $message->id, $message->greeting);  			}  		}  		$options = array_merge(parent::getOptions(), $options);  		return $options;  	}  }  

The new field type displays a drop-down list of messages to choose from. You can see the result of this change in the menu manager section for the helloworld item.

Display the chosen message

When a menu item of this component is created/updated, Joomla stores the identifier of the message. The HelloWorldModelHelloWorld model has now to compute the message according to this identifier and the data stored in the database.

Modify the site/models/helloworld.php file:

site/models/helloworld.php

<?php  // No direct access to this file  defined('_JEXEC') or die('Restricted access');     // import Joomla modelitem library  jimport('joomla.application.component.modelitem');     /**   * HelloWorld Model   */  class HelloWorldModelHelloWorld extends JModelItem  {  	/**  	 * @var string msg  	 */  	protected $msg;     	/**  	 * Returns a reference to the a Table object, always creating it.  	 *  	 * @param	type	The table type to instantiate  	 * @param	string	A prefix for the table class name. Optional.  	 * @param	array	Configuration array for model. Optional.  	 * @return	JTable	A database object  	 * @since	1.6  	 */  	public function getTable($type = 'HelloWorld', $prefix = 'HelloWorldTable', $config = array())   	{  		return JTable::getInstance($type, $prefix, $config);  	}  	/**  	 * Get the message  	 * @return string The message to be displayed to the user  	 */  	public function getMsg()   	{  		if (!isset($this->msg))   		{  			$id = JRequest::getInt('id');  			// Get a TableHelloWorld instance  			$table = $this->getTable();     			// Load the message  			$table->load($id);     			// Assign the message  			$this->msg = $table->greeting;  		}  		return $this->msg;  	}  }  

The model now asks the TableHelloWorld to get the message. This table class has to be defined in admin/tables/helloworld.php file

admin/tables/helloworld.php

<?php  // No direct access  defined('_JEXEC') or die('Restricted access');     // import Joomla table library  jimport('joomla.database.table');     /**   * Hello Table class   */  class HelloWorldTableHelloWorld extends JTable  {  	/**  	 * Constructor  	 *  	 * @param object Database connector object  	 */  	function __construct(&$db)   	{  		parent::__construct('#__helloworld', 'id', $db);  	}  }  

You shouldn’t see any differences, but if you access the database you should see a table named jos_helloworld with two columns: id and greeting. And two entries: Hello World! and Good bye World

Packaging the component

Content of your code directory

Create a compressed file of this directory or directly download the archive and install it using the extension manager of Joomla!1.6. You can add a menu item of this component using the menu manager in the backend.

Developing a Model-View-Controller (MVC) Component for Joomla!1.6 – Part 05

http://docs.joomla.org

Introduction

This tutorial is part of the Developing a Model-View-Controller (MVC) Component for Joomla!1.6 tutorial. You are encouraged to read the previous parts of the tutorial before reading this.

Adding a variable request in the menu type

For the moment, the displayed message is always Hello World!. Joomla!1.6 gives the possibility to add parameters to menu types. In our case, this is done in the site/views/helloworld/tmpl/default.xml file:

site/views/helloworld/tmpl/default.xml

<?xml version="1.0" encoding="utf-8"?>  <metadata>  	<layout title="COM_HELLOWORLD_HELLOWORLD_VIEW_DEFAULT_TITLE">  		<message>COM_HELLOWORLD_HELLOWORLD_VIEW_DEFAULT_DESC</message>  	</layout>  	<fields name="request">  		<fieldset name="request">  			<field  				name="id"  				type="list"  				label="COM_HELLOWORLD_HELLOWORLD_FIELD_GREETING_LABEL"  				description="COM_HELLOWORLD_HELLOWORLD_FIELD_GREETING_DESC"  				default="1"  			>  				<option value="1">Hello World!</option>  				<option value="2">Good bye World!</option>  			</field>  		</fieldset>  	</fields>  </metadata>  

Two important things to note:

  • the request group of fields indicates mandatory fields
  • the array parameter that indicates that these parameters will be added in the request URL [??]

The model has to be modified in order to switch between the two different messages (which is chosen by the user with the field defined above):

site/models/helloworld.php

<?php  // No direct access to this file  defined('_JEXEC') or die('Restricted access');     // import Joomla modelitem library  jimport('joomla.application.component.modelitem');     /**   * HelloWorld Model   */  class HelloWorldModelHelloWorld extends JModelItem  {  	/**  	 * @var string msg  	 */  	protected $msg;     	/**  	 * Get the message  	 * @return string The message to be displayed to the user  	 */  	public function getMsg()   	{  		if (!isset($this->msg))   		{  			$id = JRequest::getInt('id');  			switch ($id)   			{  			case 2:  				$this->msg = 'Good bye World!';  			break;  			default:  			case 1:  				$this->msg = 'Hello World!';  			break;  			}  		}  		return $this->msg;  	}  }  

Also modify your helloworld.xml file to indicate the new version:

helloworld.xml

<?xml version="1.0" encoding="utf-8"?>  <extension type="component" version="1.6.0" method="upgrade">     	<name>Hello World!</name>  	<!-- The following elements are optional and free of formatting conttraints -->  	<creationDate>November 2009</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>0.0.5</version>  	<!-- The description is optional and defaults to the name -->  	<description>Description of the Hello World component ...</description>     	<update> <!-- Runs on update; New in 1.6 -->  		<schemas>  			<schemapath type="mysql">sql/updates/mysql</schemapath>  		</schemas>  	</update>     	<!-- 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>helloworld.php</filename>  		<filename>controller.php</filename>  		<folder>views</folder>  		<folder>models</folder>  	</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">  			<!-- Admin Main File Copy Section -->  			<filename>index.html</filename>  			<filename>helloworld.php</filename>  			<!-- SQL files section -->  			<folder>sql</folder>  		</files>  	</administration>     </extension>  

You can test this variable request by putting index.php?option=com_helloworld&id=1 or index.php?option=com_helloworld&id=2 in your browser address.

Packaging the component

Content of your code directory

Create a compressed file of this directory or directly download the archive and install it using the extension manager of Joomla!1.6. You can add a menu item of this component using the menu manager in the backend.

Developing a Model-View-Controller (MVC) Component for Joomla!1.6 – Part 04

http://docs.joomla.org

Introduction

This tutorial is part of the Developing a Model-View-Controller (MVC) Component for Joomla!1.6 tutorial. You are encouraged to read the previous parts of the tutorial before reading this.

Adding a model

In the Joomla!1.6 framework, models are responsible for managing the data. The first function that has to be written for a model is a get function. It returns data to the caller. In our case, the caller will be the HelloWorldViewHelloWorld view. By default, the model named HelloWorldModelHelloWorld is the main model associated to this view. with your favorite file manager and editor put a site/models/helloworld.php file containing:

site/models/helloworld.php

<?php  // No direct access to this file  defined('_JEXEC') or die('Restricted access');     // import Joomla modelitem library  jimport('joomla.application.component.modelitem');     /**   * HelloWorld Model   */  class HelloWorldModelHelloWorld extends JModelItem  {  	/**  	 * @var string msg  	 */  	protected $msg;     	/**  	 * Get the message  	 * @return string The message to be displayed to the user  	 */  	public function getMsg()   	{  		if (!isset($this->msg))   		{  			$this->msg = 'Hello World!';  		}  		return $this->msg;  	}  }  

The HelloWorldViewHelloWorld class asks the model for data using the get method of the JView class:

site/views/helloworld/view.html.php

<?php  // No direct access to this file  defined('_JEXEC') or die('Restricted access');     // import Joomla view library  jimport('joomla.application.component.view');     /**   * HTML View class for the HelloWorld Component   */  class HelloWorldViewHelloWorld extends JView  {  	// Overwriting JView display method  	function display($tpl = null)   	{  		// Assign data to the view  		$this->msg = $this->get('Msg');     		// Check for errors.  		if (count($errors = $this->get('Errors')))   		{  			JError::raiseError(500, implode('<br />', $errors));  			return false;  		}  		// Display the view  		parent::display($tpl);  	}  }  

Also modify your helloworld.xml file to indicate use of models and the new version:

helloworld.xml

<?xml version="1.0" encoding="utf-8"?>  <extension type="component" version="1.6.0" method="upgrade">     	<name>Hello World!</name>  	<!-- The following elements are optional and free of formatting conttraints -->  	<creationDate>November 2009</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>0.0.4</version>  	<!-- The description is optional and defaults to the name -->  	<description>Description of the Hello World component ...</description>     	<update> <!-- Runs on update; New in 1.6 -->  		<schemas>  			<schemapath type="mysql">sql/updates/mysql</schemapath>  		</schemas>  	</update>     	<!-- 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>helloworld.php</filename>  		<filename>controller.php</filename>  		<folder>views</folder>  		<folder>models</folder>  	</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">  			<!-- Admin Main File Copy Section -->  			<filename>index.html</filename>  			<filename>helloworld.php</filename>  			<!-- SQL files section -->  			<folder>sql</folder>  		</files>  	</administration>     </extension>  

Packaging the component

Content of your code directory

Create a compressed file of this directory or directly download the archive and install it using the extension manager of Joomla!1.6. You can add a menu item of this component using the menu manager in the backend.