J3.x

Difference between revisions of "Developing an MVC Component/Using the database"

From Joomla! Documentation

< J3.x:Developing an MVC Component
Line 15: Line 15:
  
 
CREATE TABLE `#__helloworld` (
 
CREATE TABLE `#__helloworld` (
  `id` int(11) NOT NULL auto_increment,
+
`id`       INT(11)     NOT NULL AUTO_INCREMENT,
  `greeting` varchar(25) NOT NULL,
+
`greeting` VARCHAR(25) NOT NULL,
  PRIMARY KEY (`id`)
+
`published` tinyint(4) NOT NULL,
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
+
PRIMARY KEY (`id`)
 +
)
 +
ENGINE =MyISAM
 +
AUTO_INCREMENT =0
 +
DEFAULT CHARSET =utf8;
  
 
INSERT INTO `#__helloworld` (`greeting`) VALUES
 
INSERT INTO `#__helloworld` (`greeting`) VALUES
('Hello World!'),
+
('Hello World!'),
('Good bye World!');
+
('Good bye World!');
 +
 
 
</source>
 
</source>
 
</span>
 
</span>
Line 63: Line 68:
 
</sql>
 
</sql>
 
</uninstall>
 
</uninstall>
<update> <!-- Runs on update; New in 2.5 -->
+
<update> <!-- Runs on update; New since J2.5 -->
 
<schemas>
 
<schemas>
 
<schemapath type="mysql">sql/updates/mysql</schemapath>
 
<schemapath type="mysql">sql/updates/mysql</schemapath>
Line 83: Line 88:
 
<administration>
 
<administration>
 
<!-- Administration Menu Section -->
 
<!-- Administration Menu Section -->
<menu>Hello World!</menu>
+
<menu link='index.php?option=com_helloworld'>Hello World!</menu>
 
<!-- Administration Main File Copy Section -->
 
<!-- Administration Main File Copy Section -->
 
<!-- Note the folder attribute: This attribute describes the folder
 
<!-- Note the folder attribute: This attribute describes the folder
Line 127: Line 132:
 
<metadata>
 
<metadata>
 
<layout title="COM_HELLOWORLD_HELLOWORLD_VIEW_DEFAULT_TITLE">
 
<layout title="COM_HELLOWORLD_HELLOWORLD_VIEW_DEFAULT_TITLE">
<message>
+
<message>COM_HELLOWORLD_HELLOWORLD_VIEW_DEFAULT_DESC</message>
<![CDATA[COM_HELLOWORLD_HELLOWORLD_VIEW_DEFAULT_DESC]]>
 
</message>
 
 
</layout>
 
</layout>
 
<fields
 
<fields
name="request"
+
name="request"
addfieldpath="/administrator/components/com_helloworld/models/fields"
+
addfieldpath="/administrator/components/com_helloworld/models/fields"
>
+
>
 
<fieldset name="request">
 
<fieldset name="request">
 
<field
 
<field
name="id"
+
name="id"
type="helloworld"
+
type="helloworld"
label="COM_HELLOWORLD_HELLOWORLD_FIELD_GREETING_LABEL"
+
label="COM_HELLOWORLD_HELLOWORLD_FIELD_GREETING_LABEL"
description="COM_HELLOWORLD_HELLOWORLD_FIELD_GREETING_DESC"
+
description="COM_HELLOWORLD_HELLOWORLD_FIELD_GREETING_DESC"
/>
+
/>
 
</fieldset>
 
</fieldset>
 
</fields>
 
</fields>
Line 156: Line 159:
 
<source lang="php">
 
<source lang="php">
 
<?php
 
<?php
 +
/**
 +
* @package    Joomla.Administrator
 +
* @subpackage  com_helloworld
 +
*
 +
* @copyright  Copyright (C) 2005 - 2015 Open Source Matters, Inc. All rights reserved.
 +
* @license    GNU General Public License version 2 or later; see LICENSE.txt
 +
*/
 +
 
// No direct access to this file
 
// No direct access to this file
 
defined('_JEXEC') or die('Restricted access');
 
defined('_JEXEC') or die('Restricted access');
  
// import the list field type
 
jimport('joomla.form.helper');
 
 
JFormHelper::loadFieldClass('list');
 
JFormHelper::loadFieldClass('list');
  
 
/**
 
/**
 
  * HelloWorld Form Field class for the HelloWorld component
 
  * HelloWorld Form Field class for the HelloWorld component
 +
*
 +
* @since  0.0.1
 
  */
 
  */
 
class JFormFieldHelloWorld extends JFormFieldList
 
class JFormFieldHelloWorld extends JFormFieldList
Line 171: Line 182:
 
* The field type.
 
* The field type.
 
*
 
*
* @var string
+
* @var         string
 
*/
 
*/
 
protected $type = 'HelloWorld';
 
protected $type = 'HelloWorld';
Line 178: Line 189:
 
* Method to get a list of options for a list input.
 
* Method to get a list of options for a list input.
 
*
 
*
* @return array An array of JHtml options.
+
* @return array An array of JHtml options.
 
*/
 
*/
 
protected function getOptions()
 
protected function getOptions()
 
{
 
{
$db = JFactory::getDBO();
+
$db   = JFactory::getDBO();
 
$query = $db->getQuery(true);
 
$query = $db->getQuery(true);
 
$query->select('id,greeting');
 
$query->select('id,greeting');
 
$query->from('#__helloworld');
 
$query->from('#__helloworld');
$db->setQuery((string)$query);
+
$db->setQuery((string) $query);
 
$messages = $db->loadObjectList();
 
$messages = $db->loadObjectList();
$options = array();
+
$options = array();
 +
 
 
if ($messages)
 
if ($messages)
 
{
 
{
Line 196: Line 208:
 
}
 
}
 
}
 
}
 +
 
$options = array_merge(parent::getOptions(), $options);
 
$options = array_merge(parent::getOptions(), $options);
 +
 
return $options;
 
return $options;
 
}
 
}
 
}
 
}
 +
 
</source>
 
</source>
 
</span>
 
</span>
Line 214: Line 229:
 
<source lang="php">
 
<source lang="php">
 
<?php
 
<?php
 +
/**
 +
* @package    Joomla.Administrator
 +
* @subpackage  com_helloworld
 +
*
 +
* @copyright  Copyright (C) 2005 - 2015 Open Source Matters, Inc. All rights reserved.
 +
* @license    GNU General Public License version 2 or later; see LICENSE.txt
 +
*/
 +
 
// No direct access to this file
 
// No direct access to this file
 
defined('_JEXEC') or die('Restricted access');
 
defined('_JEXEC') or die('Restricted access');
 
// import Joomla modelitem library
 
jimport('joomla.application.component.modelitem');
 
  
 
/**
 
/**
 
  * HelloWorld Model
 
  * HelloWorld Model
 +
*
 +
* @since  0.0.1
 
  */
 
  */
 
class HelloWorldModelHelloWorld extends JModelItem
 
class HelloWorldModelHelloWorld extends JModelItem
Line 231: Line 253:
  
 
/**
 
/**
* Returns a reference to the a Table object, always creating it.
+
* Method to get a table object, load it if necessary.
 +
*
 +
* @param  string  $type    The table name. Optional.
 +
* @param  string  $prefix  The class prefix. Optional.
 +
* @param  array  $config  Configuration array for model. Optional.
 +
*
 +
* @return  JTable  A JTable object
 
*
 
*
* @param type The table type to instantiate
+
* @since   1.6
* @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())
 
public function getTable($type = 'HelloWorld', $prefix = 'HelloWorldTable', $config = array())
Line 243: Line 267:
 
return JTable::getInstance($type, $prefix, $config);
 
return JTable::getInstance($type, $prefix, $config);
 
}
 
}
 +
 
/**
 
/**
 
* Get the message
 
* Get the message
* @param  int    The corresponding id of the message to be retrieved
+
*
* @return string The message to be displayed to the user
+
* @param   integer $id Greeting Id
 +
*
 +
* @return string       Fetched String from Table for relevant Id
 
*/
 
*/
 
public function getMsg($id = 1)
 
public function getMsg($id = 1)
Line 257: Line 284:
 
if (!isset($this->messages[$id]))
 
if (!isset($this->messages[$id]))
 
{
 
{
//request the selected id
+
// Request the selected id
 
$jinput = JFactory::getApplication()->input;
 
$jinput = JFactory::getApplication()->input;
$id = $jinput->get('id', 1, 'INT' );
+
$id     = $jinput->get('id', 1, 'INT');
  
 
// Get a TableHelloWorld instance
 
// Get a TableHelloWorld instance
Line 274: Line 301:
 
}
 
}
 
}
 
}
 +
 
</source>
 
</source>
 
</span>
 
</span>
Line 283: Line 311:
 
<source lang="php">
 
<source lang="php">
 
<?php
 
<?php
 +
/**
 +
* @package    Joomla.Administrator
 +
* @subpackage  com_helloworld
 +
*
 +
* @copyright  Copyright (C) 2005 - 2015 Open Source Matters, Inc. All rights reserved.
 +
* @license    GNU General Public License version 2 or later; see LICENSE.txt
 +
*/
 
// No direct access
 
// No direct access
 
defined('_JEXEC') or die('Restricted access');
 
defined('_JEXEC') or die('Restricted access');
 
// import Joomla table library
 
jimport('joomla.database.table');
 
  
 
/**
 
/**
 
  * Hello Table class
 
  * Hello Table class
 +
*
 +
* @since  0.0.1
 
  */
 
  */
 
class HelloWorldTableHelloWorld extends JTable
 
class HelloWorldTableHelloWorld extends JTable
Line 297: Line 331:
 
* Constructor
 
* Constructor
 
*
 
*
* @param object Database connector object
+
* @param   JDatabaseDriver  &$db  A database connector object
 
*/
 
*/
function __construct(&$db)  
+
function __construct(&$db)
 
{
 
{
 
parent::__construct('#__helloworld', 'id', $db);
 
parent::__construct('#__helloworld', 'id', $db);
 
}
 
}
 
}
 
}
 +
 
</source>
 
</source>
 
</span>
 
</span>
Line 339: Line 374:
 
* ''[[#admin/tables/helloworld.php|admin/tables/helloworld.php]]''
 
* ''[[#admin/tables/helloworld.php|admin/tables/helloworld.php]]''
  
Create a compressed file of this directory or directly download the [https://github.com/joomla/Joomla-3.2-Hello-World-Component/archive/step-6-using-the-database.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/scionescire/Joomla-3.2-Hello-World-Component/archive/step-6-using-the-database.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.
  
 
{{notice|Please create a pull request or issue at https://github.com/joomla/Joomla-3.2-Hello-World-Component for any code discrepancies or if editing any of the source code on this page.}}
 
{{notice|Please create a pull request or issue at https://github.com/joomla/Joomla-3.2-Hello-World-Component for any code discrepancies or if editing any of the source code on this page.}}

Revision as of 10:26, 10 February 2015

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>



Introduction[edit]

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

Using the database[edit]

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 create two files called admin/sql/install.mysql.utf8.sql and admin/sql/updates/mysql/0.0.6.sql. They should both have the same content, as follows:

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,
	`published` tinyint(4) NOT NULL,
	PRIMARY KEY (`id`)
)
	ENGINE =MyISAM
	AUTO_INCREMENT =0
	DEFAULT CHARSET =utf8;

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

The file install.mysql.utf8.sql will be executed when you install this component. The file 0.0.6.sql is executed when you do an update.

Important Note: When the component is installed, the files in the SQL updates folder (for example, admin/sql/updates/mysql) are read and the name of the last file alphabetically is used to populate the component's version number in the #__schemas table. This value must be in this table in order for the automatic update to execute the update SQL files for future versions. For this reason, it is good practice to create a SQL update file for each version (even if it is empty or just has a comment). This way the #__schemas version will always match the component version.

Important Note: When saving the SQL files in utf8, be sure to save them as utf8 NOT BOM or the query will fail with MySQL error #1064.

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

helloworld.xml

<?xml version="1.0" encoding="utf-8"?>
<extension type="component" version="3.2.0" method="upgrade">

	<name>Hello World!</name>
	<!-- The following elements are optional and free of formatting constraints -->
	<creationDate>January 2014</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 since J2.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>
	</files>

	<administration>
		<!-- Administration Menu Section -->
		<menu link='index.php?option=com_helloworld'>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[edit]

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
/**
 * @package     Joomla.Administrator
 * @subpackage  com_helloworld
 *
 * @copyright   Copyright (C) 2005 - 2015 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

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

JFormHelper::loadFieldClass('list');

/**
 * HelloWorld Form Field class for the HelloWorld component
 *
 * @since  0.0.1
 */
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[edit]

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
/**
 * @package     Joomla.Administrator
 * @subpackage  com_helloworld
 *
 * @copyright   Copyright (C) 2005 - 2015 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

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

/**
 * HelloWorld Model
 *
 * @since  0.0.1
 */
class HelloWorldModelHelloWorld extends JModelItem
{
	/**
	 * @var array messages
	 */
	protected $messages;

	/**
	 * Method to get a table object, load it if necessary.
	 *
	 * @param   string  $type    The table name. Optional.
	 * @param   string  $prefix  The class prefix. Optional.
	 * @param   array   $config  Configuration array for model. Optional.
	 *
	 * @return  JTable  A JTable object
	 *
	 * @since   1.6
	 */
	public function getTable($type = 'HelloWorld', $prefix = 'HelloWorldTable', $config = array())
	{
		return JTable::getInstance($type, $prefix, $config);
	}

	/**
	 * Get the message
	 *
	 * @param   integer  $id  Greeting Id
	 *
	 * @return  string        Fetched String from Table for relevant Id
	 */
	public function getMsg($id = 1)
	{
		if (!is_array($this->messages))
		{
			$this->messages = array();
		}

		if (!isset($this->messages[$id]))
		{
			// Request the selected id
			$jinput = JFactory::getApplication()->input;
			$id     = $jinput->get('id', 1, 'INT');

			// Get a TableHelloWorld instance
			$table = $this->getTable();

			// Load the message
			$table->load($id);

			// Assign the message
			$this->messages[$id] = $table->greeting;
		}

		return $this->messages[$id];
	}
}

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
/**
 * @package     Joomla.Administrator
 * @subpackage  com_helloworld
 *
 * @copyright   Copyright (C) 2005 - 2015 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */
// No direct access
defined('_JEXEC') or die('Restricted access');

/**
 * Hello Table class
 *
 * @since  0.0.1
 */
class HelloWorldTableHelloWorld extends JTable
{
	/**
	 * Constructor
	 *
	 * @param   JDatabaseDriver  &$db  A 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[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.

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 discrepancies or if editing any of the source code on this page.

J3.x:Developing a MVC Component/Navigate

Contributors[edit]