Actions

J2.5

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

From Joomla! Documentation

< J2.5:Developing a MVC Component
(Zips)
m (Managing the submenu)
(7 intermediate revisions by 5 users not shown)
Line 1: Line 1:
This tutorial is for {{JVer|1.6}} {{JVer|1.7}} {{JVer|2.5}}
+
{{version/tutor|2.5}}
 
+
== Articles in this series ==
+
 
{{Chunk:Developing a Model-View-Controller (MVC) Component for Joomla!2.5 - Contents}}
 
{{Chunk:Developing a Model-View-Controller (MVC) Component for Joomla!2.5 - Contents}}
  
Line 184: Line 182:
 
</source>
 
</source>
 
</span>
 
</span>
 +
'''NOTE:''' You MUST use your component name (without com_) for the helper file name, or else your submenus won't show in category view.
  
 
This function will be automatically called by the ''com_categories'' component. Note that it will
 
This function will be automatically called by the ''com_categories'' component. Note that it will
Line 455: Line 454:
  
 
[[Category:Development]]
 
[[Category:Development]]
[[category:Joomla! 1.6]]
+
[[Category:Joomla! 1.6]]
[[category:Joomla! 1.7]]
+
[[Category:Joomla! 1.7]]
[[category:Joomla! 2.5]]
+
[[Category:Joomla! 2.5]]
[[category:Manual]]
+

Revision as of 12:21, 11 January 2013


Introduction

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

The Joomla framework has implemented the use of categories for all components. Adding categorized ability to a component is fairly simple.

Modifying the SQL

In order to manage categories, we have to change the SQL tables.

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

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',
   PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
 
INSERT INTO `#__helloworld` (`greeting`) VALUES
        ('Hello World!'),
        ('Good bye World!');

admin/sql/updates/mysql/0.0.12.sql

ALTER TABLE `#__helloworld` ADD `catid` int(11) NOT NULL DEFAULT '0'

Modifying the form

A HelloWorld message can now belong to a category. We have to modify the editing form. In the admin/models/forms/helloworld.xml file, put these lines:

admin/models/forms/helloworld.xml

<?xml version="1.0" encoding="utf-8"?>
<form
        addrulepath="/administrator/components/com_helloworld/models/rules"
>
        <fieldset>
                <field
                        name="id"
                        type="hidden"
                />
                <field
                        name="greeting"
                        type="text"
                        label="COM_HELLOWORLD_HELLOWORLD_FIELD_GREETING_LABEL"
                        description="COM_HELLOWORLD_HELLOWORLD_FIELD_GREETING_DESC"
                        size="40"
                        class="inputbox validate-greeting"
                        validate="greeting"
                        required="true"
                        default=""
                />
                <field
                        name="catid"
                        type="category"
                        extension="com_helloworld"
                        class="inputbox"
                        default=""
                        label="COM_HELLOWORLD_HELLOWORLD_FIELD_CATID_LABEL"
                        description="COM_HELLOWORLD_HELLOWORLD_FIELD_CATID_DESC"
                        required="true"
                >
                        <option value="0">JOPTION_SELECT_CATEGORY</option>
                </field>
        </fieldset>
</form>

Note that the category can be 0 (representing no category).

Modifying the menu type

The HelloWorld menu type displays a drop down list of all messages. If the message is categorized, we have to add the category in this display.

In the admin/models/fields/helloworld.php file, put these lines:

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 = new JDatabaseQuery; WARNING - There's an error in this line, JDatabaseQuery is an abstract class
                $query = $db->getQuery(true); // THIS IS THE FIX, WARNING IT MUST BE FIXED IN THE ZIP FILES
 
                $query->select('#__helloworld.id as id,greeting,#__categories.title as category,catid');
                $query->from('#__helloworld');
                $query->leftJoin('#__categories on catid=#__categories.id');
                $db->setQuery((string)$query);
                $messages = $db->loadObjectList();
                $options = array();
                if ($messages)
                {
                        foreach($messages as $message) 
                        {
                                $options[] = JHtml::_('select.option', $message->id, $message->greeting .
                                                      ($message->catid ? ' (' . $message->category . ')' : ''));
                        }
                }
                $options = array_merge(parent::getOptions(), $options);
                return $options;
        }
}

It will now display the category between parenthesis.

Managing the submenu

The com_categories component allows to set the submenu using a helper file. With your favorite file manager and editor, put a admin/helpers/helloworld.php file containing these lines:

admin/helpers/helloworld.php

<?php
// No direct access to this file
defined('_JEXEC') or die;
 
/**
 * HelloWorld component helper.
 */
abstract class HelloWorldHelper
{
        /**
         * Configure the Linkbar.
         */
        public static function addSubmenu($submenu) 
        {
                JSubMenuHelper::addEntry(JText::_('COM_HELLOWORLD_SUBMENU_MESSAGES'),
                                         'index.php?option=com_helloworld', $submenu == 'messages');
                JSubMenuHelper::addEntry(JText::_('COM_HELLOWORLD_SUBMENU_CATEGORIES'),
                                         'index.php?option=com_categories&view=categories&extension=com_helloworld',
                                         $submenu == 'categories');
                // set some global property
                $document = JFactory::getDocument();
                $document->addStyleDeclaration('.icon-48-helloworld ' .
                                               '{background-image: url(../media/com_helloworld/images/tux-48x48.png);}');
                if ($submenu == 'categories') 
                {
                        $document->setTitle(JText::_('COM_HELLOWORLD_ADMINISTRATION_CATEGORIES'));
                }
        }
}

NOTE: You MUST use your component name (without com_) for the helper file name, or else your submenus won't show in category view.

This function will be automatically called by the com_categories component. Note that it will

  • change the submenu
  • change some css properties (for displaying icons)
  • change the browser title if the submenu is categories
  • change the title and add a preferences button

We have to change the general controller to call this function and modify the component entry point (the .icon-48-helloworld css class is now set in the addSubmenu function)

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
                $input = JFactory::getApplication()->input;
                $input->set('view', $input->getCmd('view', 'HelloWorlds'));
 
                // call parent behavior
                parent::display($cachable);
 
                // Set the submenu
                HelloWorldHelper::addSubmenu('messages');
        }
}

admin/helloworld.php

<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
 
// require helper file
JLoader::register('HelloWorldHelper', dirname(__FILE__) . DS . 'helpers' . DS . 'helloworld.php');
 
// 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
$input = JFactory::getApplication()->input;
$controller->execute($input->getCmd('task'));
 
// Redirect if set by the controller
$controller->redirect();

Adding some translation strings

Some strings have to be translated. In the admin/language/en-GB/en-GB.com_helloworld.ini file, put these lines:

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

COM_HELLOWORLD="Hello World!"
COM_HELLOWORLD_ADMINISTRATION="HelloWorld - Administration"
COM_HELLOWORLD_ADMINISTRATION_CATEGORIES="HelloWorld - Categories"
COM_HELLOWORLD_HELLOWORLD_CREATING="HelloWorld - Creating"
COM_HELLOWORLD_HELLOWORLD_DETAILS="Details"
COM_HELLOWORLD_HELLOWORLD_EDITING="HelloWorld - Editing"
COM_HELLOWORLD_HELLOWORLD_ERROR_UNACCEPTABLE="Some values are unacceptable"
COM_HELLOWORLD_HELLOWORLD_FIELD_CATID_DESC="The category the messages belongs to"
COM_HELLOWORLD_HELLOWORLD_FIELD_CATID_LABEL="Category"
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"
COM_HELLOWORLD_MANAGER_HELLOWORLD_EDIT="HelloWorld manager: Edit Message"
COM_HELLOWORLD_MANAGER_HELLOWORLD_NEW="HelloWorld manager: New Message"
COM_HELLOWORLD_MANAGER_HELLOWORLDS="HelloWorld manager"
COM_HELLOWORLD_N_ITEMS_DELETED_1="One message deleted"
COM_HELLOWORLD_N_ITEMS_DELETED_MORE="%d messages deleted"
COM_HELLOWORLD_SUBMENU_MESSAGES="Messages"
COM_HELLOWORLD_SUBMENU_CATEGORIES="Categories"

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. 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>COM_HELLOWORLD</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.12</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>
 
        <media destination="com_helloworld" folder="media">
                <filename>index.html</filename>
                <folder>images</folder>
        </media>
 
        <administration>
                <!-- Administration Menu Section -->
                <menu img="../media/com_helloworld/images/tux-16x16.png">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>
                        <!-- helpers files section -->
                        <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.sys.ini</language>
                </languages>
        </administration>
 
</extension>

Zips

Download the zip file for this Part: [1]

Navigate

Prev: Adding verifications Next: Adding configuration

Contributors