Archived

Difference between revisions of "Developing a MVC Component/Adding configuration"

From Joomla! Documentation

< Archived:Developing a MVC Component
Line 17: Line 17:
 
<config>
 
<config>
 
<fieldset
 
<fieldset
group="greetings"
+
name="greetings"
 
label="com_helloworld_Config_Greeting_Settings_Label"
 
label="com_helloworld_Config_Greeting_Settings_Label"
 
description="com_helloworld_Config_Greeting_Settings_Desc">
 
description="com_helloworld_Config_Greeting_Settings_Desc">

Revision as of 08:19, 28 September 2010

This page has been archived. This page contains information for an unsupported Joomla! version or is no longer relevant. It exists only as a historical reference, it will not be improved and its content may be incomplete and/or contain broken links.

Documentation all together tranparent small.png
Under Construction

This article or section is in the process of an expansion or major restructuring. You are welcome to assist in its construction by editing it as well. If this article or section has not been edited in several days, please remove this template.
This article was last edited by Pwiseman (talk| contribs) 13 years ago. (Purge)

Template:Future

Articles in this series[edit]


Introduction[edit]

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 configuration parameters[edit]

The Joomla!1.6 framework allows the use of parameters stored in each component. With your favorite file manager and editor, put a file admin/config.xml file containing these lines:

admin/config.xml

<?xml version="1.0" encoding="utf-8"?>
<config>
	<fieldset
		name="greetings"
		label="com_helloworld_Config_Greeting_Settings_Label"
		description="com_helloworld_Config_Greeting_Settings_Desc">

		<field
			name="show_category"
			type="radio"
			label="com_helloworld_Params_Show_Category_Label"
			description="com_helloworld_Params_Show_Category_Desc"
			default="0">
			<option value="0">Hide</option>
			<option value="1">Show</option>
		</field>
	</fieldset>
</config>

This file will be read by the com_config component of the Joola!1.6 core. For the moment, we defined only one parameter: is the category title displayed or not in the frontend?.

the best way to set the parameters is to put a Preferences button in a toolbar.

With your favorite editor, put these lines in admin/views/helloworldlist/view.html.php

admin/views/helloworldlist/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');
/**
 * HelloWorldList View
 */
class HelloWorldViewHelloWorldList extends JView {
	/**
	 * items to be displayed
	 */
	protected $items;
	/**
	 * pagination for the items
	 */
	protected $pagination;
	/**
	 * HelloWorldList view display method
	 * @return void
	 */
	function display($tpl = null)
	{
		// Get data from the model
		$items = $this->get('Items');
		$pagination = $this->get('Pagination');
		// Assign data to the view
		$this->items = $items;
		$this->pagination = $pagination;
		// Set the toolbar
		$this->_setToolBar();
		// Display the template
		parent::display($tpl);
		// Set the document
		$this->_setDocument();
	}
	/**
	 * Setting the toolbar
	 */
	protected function _setToolBar()
	{
		JToolBarHelper::title(JText::_('com_helloworld_Manager'), 'helloworld');
		JToolBarHelper::deleteListX('com_helloworld_HelloWorldList_Are_you_sure_you_want_to_delete_these_greetings', 'helloworldlist.remove');
		JToolBarHelper::editListX('helloworld.edit');
		JToolBarHelper::addNewX('helloworld.add');
		JToolBarHelper::preferences('com_helloworld');
	}
	/**
	 * Method to set up the document properties
	 *
	 * @return void
	 */
	protected function _setDocument() 
	{
		$document = &JFactory::getDocument();
		$document->setTitle(JText::_('com_helloworld_Administration'));
	}
}

Using configuration parameters as default value[edit]

We want to define this parameter individually on all HelloWorld data. With your favorite editor, put these lines into the admin/models/forms/helloworld.xml

admin/models/forms/helloworld.xml

<?xml version="1.0" encoding="utf-8"?>
<!-- $Id: helloworld.xml 30 2009-11-14 10:56:17Z chdemko $ -->
<form>
	<fields>
		<field
			id="id"
			name="id"
			type="hidden"
		/>
		<field
			id="greeting"
			name="greeting"
			type="text"
			size="40"
			class="inputbox validate-greeting"
			validate="greeting"
			required="true"
			default=""
			label="com_helloworld_HelloWorld_Greeting"
			description="com_helloworld_HelloWorld_Greeting_Desc"
		/>
		<field
			id="catid"
			name="catid"
			type="Categories"
			extension="com_helloworld"
			allow_none="true"
			class="inputbox"
			default=""
			label="com_helloworld_HelloWorld_Category"
			description="com_helloworld_HelloWorld_Category_Desc"
			required="true"
		>
			<option value="0">JOption_No_Category</option>
		</field>
	</fields>
	<fields
		group="params"
		array="true"
		label="com_helloworld_Options">
		<field
			name="show_category"
			type="list"
			label="com_helloworld_Params_Show_Category_Label"
			description="com_helloworld_Params_Show_Category_Desc"
			default="">
			<option value="">Use Global</option>
			<option value="0">Hide</option>
			<option value="1">Show</option>
		</field>
	</fields>
</form>

We define the same parameter for each message with an additional value: Use global. The array="true" xml field means that parameters in this group will be grouped in the params array.

Modifying the SQL[edit]

Data now contains a new parameter: params. The SQL structure has to be modified.

With your favorite editor, put these lines into admin/sql/install.mysql.utf8.sql:

admin/sql/install.mysql.utf8.sql

DROP TABLE IF EXISTS `#__helloworld`;

CREATE TABLE `#__helloworld` (
  `id` int(11) NOT NULL auto_increment,
  `greeting` varchar(25) NOT NULL,
  `catid` int(11) NOT NULL default '0',
  `params` TEXT NOT NULL default '',
   PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;

INSERT INTO `#__helloworld` (`greeting`) VALUES
	('Hello World!'),
	('Good bye World!');

With your favorite editor, put these lines into admin/sql/update.mysql.utf8.sql:

admin/sql/update.mysql.utf8.sql

ALTER TABLE `#__helloworld` ADD `params` TEXT NOT NULL default '';

The TableHelloWorld has to be modified in order to deal with these parameters: they will be stored in a JSON format and get in a JParameter class. We have to overload the bind and the load method. With your favorite editor, put these lines into admin/tables/helloworld.php

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 TableHelloWorld extends JTable
{
	/**
	 * Primary Key
	 *
	 * @var int
	 */
	var $id = null;
	/**
	 * @var string
	 */
	var $greeting = null;
	/**
	 * @var int
	 */
	var $catid = null;
	/**
	 * @var string
	 */
	var $params = null;
	/**
	 * Constructor
	 *
	 * @param object Database connector object
	 */
	function TableHelloWorld(&$db) 
	{
		parent::__construct('#__helloworld', 'id', $db);
	}
	/**
	 * Overloaded bind function
	 *
	 * @param	array		$hash named array
	 * @return	null|string	null is operation was satisfactory, otherwise returns an error
	 * @see JTable:bind
	 * @since 1.5
	 */
	public function bind($array, $ignore = '') 
	{
		if (isset($array['params']) && is_array($array['params'])) 
		{
			// Convert the params field to an string.
			$parameter = new JParameter;
			$parameter->loadArray($array['params']);
			$array['params'] = $parameter->toString();
		}
		return parent::bind($array, $ignore);
	}
	/**
	 * Overloaded load function
	 *
	 * @param	int $pk primary key
	 * @param	boolean $reset reset data
	 * @return	boolean
	 * @see JTable:load
	 */
	public function load($pk = null, $reset = true) 
	{
		if (parent::load($pk, $reset)) 
		{
			// Convert the params field to a parameter.
			$parameter = new JParameter;
			$parameter->loadJSON($this->params);
			$this->params = $parameter;
			return true;
		}
		else
		{
			return false;
		}
	}
}

Modifying the backend[edit]

The backend model has to used the load method of the TableHelloWorld class. With your favorite editor, put these lines into the admin/models/helloworld.php file:

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.modelform');
/**
 * HelloWorld Model
 */
class HelloWorldModelHelloWorld extends JModelForm
{
	/**
	 * @var array data
	 */
	protected $data = null;
	/**
	 * Method to auto-populate the model state.
	 */
	protected function _populateState() 
	{
		$app = JFactory::getApplication('administrator');
		// Load the User state.
		if (!($pk = (int)$app->getUserState('com_helloworld.edit.helloworld.id'))) 
		{
			$pk = (int)JRequest::getInt('id');
		}
		$this->setState('helloworld.id', $pk);
	}
	/**
	 * Method to get the data.
	 *
	 * @access	public
	 * @return	array of string
	 * @since	1.0
	 */
	public function &getData() 
	{
		if (empty($this->data)) 
		{
			$data = & JRequest::getVar('jform');
			if (empty($data)) 
			{
				$selected = $this->getState('helloworld.id');
				$data = $this->getTable();
				$data->load((int)$selected);
			}
			$this->data = $data;
		}
		return $this->data;
	}
	/**
	 * Method to get the HelloWorld form.
	 *
	 * @access	public
	 * @return	mixed	JForm object on success, false on failure.
	 * @since	1.0
	 */
	public function &getForm() 
	{
		$form = & parent::getForm('helloworld', 'form', array(
			'array' => 'jform'
		) , false);
		return $form;
	}
	/**
	 * Method to get the javascript attached to the form
	 *
	 * @return string URL to the script.
	 */
	function getScript() 
	{
		return 'administrator/components/com_helloworld/models/forms/helloworld.js';
	}
	/**
	 * Method to save a record
	 *
	 * @param array $data array of data
	 * @access	public
	 * @return	boolean	True on success
	 */
	function save($data) 
	{
		// Database processing
		$row = & $this->getTable();
		// Bind the form fields to the hello table
		if (!$row->save($data)) 
		{
			$this->setError($row->getErrorMsg());
			return false;
		}
		return true;
	}
}

The backend edit view has to display the options to the administrator. With your favorite editor, put these lines into the admin/views/helloworld/tmpl/edit.php file:

admin/views/helloworld/tmpl/edit.php

<?php
// No direct access
defined('_JEXEC') or die('Restricted access');
JHTML::_('behavior.tooltip');
JHTML::_('behavior.formvalidation');
?>
<form action="<?php echo JRoute::_('index.php?option=com_helloworld'); ?>" method="post" name="adminForm" id="adminForm" class="form-validate">
	<div class="width-60 fltlft">
		<fieldset class="adminform">
			<legend><?php echo JText::_( 'com_helloworld_HelloWorld_Details' ); ?></legend>
			<?php foreach($this->form->getFields() as $field): ?>
				<?php if (!$field->hidden): ?>
					<?php echo $field->label; ?>
				<?php endif; ?>
				<?php echo $field->input; ?>
			<?php endforeach; ?>
		</fieldset>
	</div>
	<div class="width-40 fltrt">
		<fieldset class="adminform">
			<legend><?php echo JText::_( 'com_helloworld_HelloWorld_Options' ); ?></legend>
			<?php foreach($this->form->getFields('params') as $field): ?>
				<?php if (!$field->hidden): ?>
					<?php echo $field->label; ?>
				<?php endif; ?>
				<?php echo $field->input; ?>
			<?php endforeach; ?>
		</fieldset>
	</div>
	<input type="hidden" name="task" value="helloworld.edit" />
	<?php echo JHtml::_('form.token'); ?>
</form>

Modifying the frontend[edit]

The frontend has to be modified according to the new show_category parameter.

We have to modified the model:

  • it has to merge global parameters and individual parameters
  • it has to provide the category

With your favorite editor, put these lines into 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 object $item
	 */
	protected $item;
	/**
	 * @var object $category
	 */
	protected $category;
	/**
	 * Get the message
	 * @return object The message to be displayed to the user
	 */
	public function getItem() 
	{
		if (!isset($this->item)) 
		{
			$id = JRequest::getInt('id');
			// Get a TableHelloWorld instance
			$table = $this->getTable();
			// Load the message
			$table->load($id);
			// Add global parameters
			$params = clone JFactory::getApplication('site')->getParams();
			$params->merge($table->params);
			$table->params = $params;
			// Assign the message
			$this->item = $table;
		}
		return $this->item;
	}
	/**
	 * Get the category
	 * @return object The category assigned to the message
	 */
	public function getCategory() 
	{
		if (!isset($this->category)) 
		{
			$catid = $this->getItem()->catid;
			// Get a TableHelloWorld instance
			$table = $this->getTable('Category', 'JTable');
			// Load the category
			$table->load($catid);
			// Assign the category
			$this->category = $table;
		}
		return $this->category;
	}
}

The view has to ask the model for the category. With your favorite editor, put these lines into the site/views/helloworld/view.html.php

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
{
	protected $item = null;
	protected $category = null;
	// Overwriting JView display method
	function display($tpl = null) 
	{
		// Assign data to the view
		$this->item = $this->get('Item');
		// Assign data to the view
		$this->category = $this->get('Category');
		// Display the view
		parent::display($tpl);
	}
}

The layout can now display correctly the category or not. With your favorite editor, put these lines into site/views/helloworld/tmpl/default.php

site/views/helloworld/tmpl/default.php

<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
?>

<h1>
	<?php echo $this->item->greeting;?>
	<?php if ($this->item->params->get('show_category') && !empty($this->category->title)):?>
		(<?php echo $this->category->title;?>)
	<?php endif;?>
</h1>

Adding some translation strings[edit]

Some strings have to be added in the admin/language/en-GB/en-GB.com_helloworld.ini file

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

# Joomla16.Tutorials
# Copyright (C) 2005 - 2009 Open Source Matters. All rights reserved.
# License GNU General Public License version 2 or later; see LICENSE.txt, see LICENSE.php
# Note : All ini files need to be saved as UTF-8 - No BOM

COM_HELLOWORLD_ADMINISTRATION=HelloWorld administration
COM_HELLOWORLD_CATEGORIES=Categories
COM_HELLOWORLD_MANAGER=HelloWorld manager
COM_HELLOWORLD_MESSAGES=Messages
COM_HELLOWORLD_HELLOWORLD_CATEGORY=Category
COM_HELLOWORLD_HELLOWORLD_CATEGORY_DESC=Category of the message
COM_HELLOWORLD_HELLOWORLD_CREATING=Creating
COM_HELLOWORLD_HELLOWORLD_DETAILS=Details
COM_HELLOWORLD_HELLOWORLD_OPTIONS=Options
COM_HELLOWORLD_HELLOWORLD_EDITING=Editing
COM_HELLOWORLD_HELLOWORLD_ERROR_SOME_VALUES_ARE_UNACCEPTABLE=Some values are unacceptable
COM_HELLOWORLD_HELLOWORLD_GREETING_DESC=Message to be displayed
COM_HELLOWORLD_HELLOWORLD_GREETING=Greeting
COM_HELLOWORLD_HELLOWORLDLIST_ARE_YOU_SURE_YOU_WANT_TO_DELETE_THESE_GREETINGS=Are you sure you want to delete these greetings?
COM_HELLOWORLD_HELLOWORLDLIST_GREETING=Greeting
COM_HELLOWORLD_HELLOWORLDLIST_GREETINGS_REMOVED=Greetings removed
COM_HELLOWORLD_HELLOWORLDLIST_ID=Id
COM_HELLOWORLD_HELLOWORLDLIST_ONE_OR_MORE_GREETINGS_COULD_NOT_BE_DELETED=One or more greetings could not be deleted: %s
COM_HELLOWORLD_HELLOWORLD_VIEW_DEFAULT_MSG_DESC=This message will be displayed
COM_HELLOWORLD_HELLOWORLD_VIEW_DEFAULT_MSG_LABEL=Message

COM_HELLOWORLD_CONFIGURATION=Configuration
COM_HELLOWORLD_CONFIG_GREETING_SETTINGS_LABEL=Greeting settings
COM_HELLOWORLD_CONFIG_GREETING_SETTINGS_DESC=Greetings settings description
COM_HELLOWORLD_PARAMS_SHOW_CATEGORY_LABEL=Show category
COM_HELLOWORLD_PARAMS_SHOW_CATEGORY_DESC=Display the category after the message

Packaging the component[edit]

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.13</version>
	<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 -->
		<sql>
			<file driver="mysql" charset="utf8">sql/update.mysql.utf8.sql</file>
		</sql>
	</update>

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

	<media destination="com_helloworld" folder="media">
		<filename>index.html</filename>
		<folder>images</folder>
	</media>
	
	<administration>
		<menu img="../media/com_helloworld/images/tux-16x16.png">Hello World!</menu>
		<files folder="admin">
			<filename>index.html</filename>
			<filename>config.xml</filename>
			<filename>helloworld.php</filename>
			<filename>controller.php</filename>
			<folder>sql</folder>
			<folder>tables</folder>
			<folder>models</folder>
			<folder>views</folder>
			<folder>controllers</folder>
			<folder>helpers</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.menu.ini</language>
		</languages>
	</administration>
</extension>

Contributors[edit]