Archived

Difference between revisions of "Developing a MVC Component/Adding backend actions"

From Joomla! Documentation

< Archived:Developing a MVC Component
Line 22: Line 22:
 
  * HelloWorldList View
 
  * HelloWorldList View
 
  */
 
  */
class HelloWorldViewHelloWorldList extends JView {
+
class HelloWorldViewHelloWorldList extends JView
 +
{
 
/**
 
/**
 
* items to be displayed
 
* items to be displayed

Revision as of 10:36, 19 November 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 Cdemko (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 a toolbar[edit]

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

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);
	}
	/**
	 * Setting the toolbar
	 */
	protected function _setToolBar()
	{
		JToolBarHelper::title(JText::_('com_helloworld_Manager'));
		JToolBarHelper::deleteListX('com_helloworld_HelloWorldList_Are_you_sure_you_want_to_delete_these_greetings', 'helloworldlist.remove');
		JToolBarHelper::editListX('helloworld.edit');
		JToolBarHelper::addNewX('helloworld.add');
	}	
}

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

Adding specific controllers[edit]

Three actions has been added:

  • helloworldlist.remove
  • helloworld.edit
  • helloworld.add

These are compound tasks (controller.task). So a remove task has to be coded in a new HelloWorldControllerHelloworldList controller and edit and add tasks have to be coded in a new HelloWorldControllerHelloWorld controller.

admin/controllers/helloworldlist.php

<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
// import Joomla controller library
jimport('joomla.application.component.controller');

class HelloWorldControllerHelloWorldList extends JController
{
	/**
	 * remove record(s)
	 * @return void
	 */
	function remove() 
	{
		$model = $this->getModel('HelloWorldList');
		if ($model->remove()) 
		{
			$msg = JText::_('com_helloworld_HelloWorldList_Greetings_removed');
			$type = 'message';
		}
		else
		{
			$msg = JText::sprintf('com_helloworld_HelloWorldList_One_or_more_greetings_could_not_be_deleted', implode("<br />", $model->getErrors()));
			$type = 'error';
		}
		$this->setRedirect('index.php?option=com_helloworld', $msg, $type);
	}
}

admin/controllers/helloworld.php

<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
// import Joomla controller library
jimport('joomla.application.component.controller');
/**
 * HelloWorld Controller
 */
class HelloWorldControllerHelloWorld extends JController
{
	/**
	 * constructor (registers additional tasks to methods)
	 * @return void
	 */
	function __construct($config=array()) 
	{
		parent::__construct($config);
		// Register Extra tasks
		$this->registerTask('add', 'edit');
	}
	/**
	 * display the edit form
	 * @return void
	 */
	function edit() 
	{
		$model = & $this->getModel();
		$view = & $this->getView('HelloWorld','html');
		$view->setModel($model, true);
		$view->display();
	}
	/**
	 * save a record (and redirect to main page)
	 * @return void
	 */
	function save() 
	{
		$model = $this->getModel();
		if ($model->save()) 
		{
			$msg = JText::_('com_helloworld_HelloWorld_Greeting_saved');
			$type = 'message';
			$this->setRedirect('index.php?option=com_helloworld', $msg, $type);
		}
		else
		{
			$msg = JText::sprintf('com_helloworld_HelloWorld_Error_Saving_greeting', implode("<br />", $model->getError()));
			$type = 'error';
			$app = & JFactory::getApplication();
			$app->enqueueMessage($msg, $type);
			$view = & $this->getView('HelloWorld','html');
			$view->setModel($model, true);
			$view->display();
		}
	}
	/**
	 * cancel editing a record
	 * @return void
	 */
	function cancel() 
	{
		$msg = JText::_('com_helloworld_HelloWorld_edit_cancelled');
		$this->setRedirect('index.php?option=com_helloworld', $msg);
	}
}

In the previous controller we have introduced two new tasks: cancel and save. They will be used in the new view for editing message. Note that add and edit tasks have same code (see registerTask in the constructor).

Adding an editing view[edit]

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
{
	/**
	 * View form
	 *
	 * @var		form
	 */
	protected $form = null;
	/**
	 * display method of Hello view
	 * @return void
	 */
	public function display($tpl = null) 
	{
		// get the Form
		$form = & $this->get('Form');
		// get the Data
		$data = & $this->get('Data');
		// Bind the Data
		$form->bind($data);
		// Assign the form
		$this->form = $form;
		// Set the toolbar
		$this->_setToolBar();
		// Display the template
		parent::display($tpl);
	}
	/**
	 * Setting the toolbar
	 */
	protected function _setToolBar() 
	{
		JRequest::setVar('hidemainmenu', 1);
		$isNew = ($this->form->getValue('id') < 1);
		JToolBarHelper::title(JText::_('com_helloworld_Manager') . ': <small><small>[ ' . ($isNew ? JText::_('JToolBar_New') : JText::_('JToolBar_Edit')) . ' ]</small></small>');
		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/default.php containing

admin/views/helloworld/tmpl/default.php

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

Adding a model and modifying the existing one[edit]

The HelloWorldViewHelloWorld view asks form and data from a model. This model has to provide a getForm, a getData method and a save method (called from the HelloWorldControllerHelloWorld 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.modelform');
/**
 * HelloWorld Model
 */
class HelloWorldModelHelloWorld extends JModelForm
{
	/**
	 * @var array data
	 */
	protected $data = null;
	/**
	 * Method to get the data.
	 *
	 * @access	public
	 * @return	array of string
	 * @since	1.0
	 */
	public function &getData() 
	{
		if (empty($this->data)) 
		{
			$app = & JFactory::getApplication();
			$data = & JRequest::getVar('jform');
			if (empty($data)) 
			{
				$selected = & JRequest::getVar('cid', 0, '', 'array');	
				$db = JFactory::getDBO();
				$query = $db->getQuery(true);
				// Select all fields from the hello table.
				$query->select('*');
				$query->from('`#__helloworld`');
				$query->where('id = ' . (int)$selected[0]);
				$db->setQuery((string)$query);
				$data = & $db->loadAssoc();
			}
			if (empty($data)) 
			{
				// Check the session for previously entered form data.
				$data = $app->getUserState('com_helloworld.edit.helloworld.data', array());
				unset($data['id']);
			}
			$app->setUserState('com_helloworld.edit.helloworld.data', $data);
			$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($data = array(), $loadData = true) 
	{
		$form = $this->loadForm('com_helloworld.helloworld', 'helloworld', array('control' => 'jform', 'load_data' => $loadData));
		return $form;
	}
	/**
	 * Method to save a record
	 *
	 * @access	public
	 * @return	boolean	True on success
	 */
	function save() 
	{
		$data = & $this->getData();
		// 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;
	}
}

This model inherits from the JModelForm class and uses its getForm 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>
	<fields>
		<field
			id="id"
			name="id"
			type="hidden"
		/>
		<field
			id="greeting"
			name="greeting"
			type="text"
			size="40"
			class="inputbox"
			default=""
			label="com_helloworld_HelloWorld_Greeting"
			description="com_helloworld_HelloWorld_Greeting_Desc"
		/>
	</fields>
</form>

The HelloWorldModelHelloWorldList model has to provide a remove method (called from the HelloWorldControllerHelloWorldList controller). Modify the admin/models/helloworldlist.php file:

admin/models/helloworldlist.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 HelloWorldModelHelloWorldList extends JModelList
{
	/**
	 * Model context string.
	 *
	 * @var		string
	 */
	protected $_context = 'com_helloworld.helloworldlist';
	/**
	 * Method to remove the selected items
	 *
	 * @return	boolean	true of false in case of failure
	 */
	public function remove() 
	{
		// Get the selected items
		$selected = $this->getState('selected');
		// Get a weblink row instance
		$table = $this->getTable('HelloWorld');
		foreach($selected as $id) 
		{
			// Load the row and check for an error.
			if (!$table->load($id)) 
			{
				$this->setError($table->getError());
				return false;
			}
			// Delete the row and check for an error.
			if (!$table->delete()) 
			{
				$this->setError($table->getError());
				return false;
			}
		}
		return true;
	}
	/**
	 * 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;
	}
	/**
	 * Method to auto-populate the model state.
	 *
	 * This method should only be called once per instantiation and is designed
	 * to be called on the first call to the getState() method unless the model
	 * configuration flag to ignore the request is set.
	 *
	 * @return	void
	 */
	protected function populateState() 
	{
		// Initialize variables.
		$app = JFactory::getApplication('administrator');
		// Load the list state.
		$this->setState('list.start', $app->getUserStateFromRequest($this->_context . '.list.start', 'limitstart', 0, 'int'));
		$this->setState('list.limit', $app->getUserStateFromRequest($this->_context . '.list.limit', 'limit', $app->getCfg('list_limit', 25) , 'int'));
		$this->setState('selected', JRequest::getVar('cid', array()));
	}
}

Packaging the component[edit]

Content of your code directory


NOTICE: The following archive does NOT work with Joomla 1.6 as of Beta 7 on August 22, 2010. The getForm() method is not written correctly. See this forum posting for more information. To make the component work, you'll have to unzip the archive, modify lines 67 and 69 of /admin/models/helloworld.php to match the code above, then re-zip the file and upload it to your server.

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

	<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>
			<folder>views</folder>
			<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.menu.ini</language>
		</languages>
	</administration>
</extension>

Contributors[edit]