J3.x

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

From Joomla! Documentation

< J3.x:Developing an MVC Component
Line 401: Line 401:
 
* ''[[#admin/language/en-GB/index.html|admin/language/en-GB/index.html]]''
 
* ''[[#admin/language/en-GB/index.html|admin/language/en-GB/index.html]]''
 
* ''[[J3.x:Developing a MVC Component/Adding language management#admin.2Flanguage.2Fen-GB.2Fen-GB.com_helloworld.ini|admin/language/en-GB/en-GB.com_helloworld.ini]]''
 
* ''[[J3.x:Developing a MVC Component/Adding language management#admin.2Flanguage.2Fen-GB.2Fen-GB.com_helloworld.ini|admin/language/en-GB/en-GB.com_helloworld.ini]]''
* ''[[J3.x:Developing a MVC Component/Adding language management##admin.2Flanguage.2Fen-GB.2Fen-GB.com_helloworld.sys.ini|admin/language/en-GB/en-GB.com_helloworld.sys.ini]]''
+
* ''[[J3.x:Developing a MVC Component/Adding language management#admin.2Flanguage.2Fen-GB.2Fen-GB.com_helloworld.sys.ini|admin/language/en-GB/en-GB.com_helloworld.sys.ini]]''
* ''[[J3.x:Developing a MVC Component/Adding language management##admin.2Flanguage.2Fen-GB.2Fen-GB.com_helloworld.sys.ini|language/en-GB/en-GB.com_helloworld.sys.ini]]''
+
* ''[[J3.x:Developing a MVC Component/Adding language management#admin.2Flanguage.2Fen-GB.2Fen-GB.com_helloworld.sys.ini|language/en-GB/en-GB.com_helloworld.sys.ini]]''
  
 
Create a compressed file of this directory or directly download the [https://github.com/joomla/Joomla-3.2-Hello-World-Component/archive/step-9-adding-backend-actions.zip archive] and install it using the extension manager of Joomla. You can add a menu item of this component using the menu manager in the backend.
 
Create a compressed file of this directory or directly download the [https://github.com/joomla/Joomla-3.2-Hello-World-Component/archive/step-9-adding-backend-actions.zip archive] and install it using the extension manager of Joomla. You can add a menu item of this component using the menu manager in the backend.

Revision as of 06:35, 14 August 2014

Joomla! 
3.x
<translate> Tutorial</translate>
<translate> Developing an MVC Component</translate>

{{Chunk:Developing a Model-View-Controller (MVC) Component for Joomla!3.1 - Contents/<translate> en</translate>}} <translate> This is a multiple-article series of tutorials on how to develop a Model-View-Controller Component for Joomla! VersionJoomla 3.x.</translate>

<translate> Begin with the Introduction, and navigate the articles in this series by using the navigation button at the bottom or the box to the right (the Articles in This series).</translate>



Copyedit.png
This Page Needs Your Help

This page is tagged because it NEEDS REVIEW. You can help the Joomla! Documentation Wiki by contributing to it.
More pages that need help similar to this one are here. NOTE-If you feel the need is satistified, please remove this notice.


Introduction[edit]

This tutorial is part of the Developing a MVC Component for Joomla! 3.2 tutorial. You are encouraged to read the previous parts of the tutorial before reading this.

Adding a toolbar[edit]

In Joomla, 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.

The arguments used in, for example, JToolBarHelper::addNew is used to set a controller instance which will be used after button is clicked. Further details below in the adding specific controllers section.

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 JViewLegacy
{
	/**
	 * HelloWorlds view display method
	 * @param   string  $tpl  The name of the template file to parse; automatically searches through the template paths.
	 *
	 * @return  mixed  A string if successful, otherwise a JError object.
	 */
	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 other classic backend actions in the administrator/includes/toolbar.php file of your Joomla 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" id="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[edit]

Three actions have been added:

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

read more about subcontrollers...

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	2.5
	 */
	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[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 JViewLegacy
{
	/**
	 * 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() 
	{
		$input = JFactory::getApplication()->input;
		$input->set('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="adminForm">
    <div class="form-horizontal">
        <fieldset class="adminform">
            <legend><?php echo JText::_('COM_HELLOWORLD_HELLOWORLD_DETAILS'); ?></legend>
            <div class="row-fluid">
                <div class="span6">
                    <?php foreach ($this->form->getFieldset() as $field): ?>
                        <div class="control-group">
                            <div class="control-label"><?php echo $field->label; ?></div>
                            <div class="controls"><?php echo $field->input; ?></div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </fieldset>
    </div>
    <input type="hidden" name="task" value="helloworld.edit" />
    <?php echo JHtml::_('form.token'); ?>
</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 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	2.5
	 */
	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	2.5
	 */
	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	2.5
	 */
	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[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. 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="2.5.0" method="upgrade">

	<name>Hello World!</name>
	<!-- The following elements are optional and free of formatting constraints -->
	<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 2.5 -->
		<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>
                        <!-- admin languages files section -->
                        <folder>language</folder>
			<!-- controllers files section -->
			<folder>controllers</folder>
		</files>	
	</administration>
</extension>

Info non-talk.png
General Information

Please create a pull request or issue at https://github.com/joomla/Joomla-3.2-Hello-World-Component for any code descprepancies or if editing any of the source code on this page.

J3.x:Developing a MVC Component/Navigate

Contributors[edit]