開發一個 Model-View-Controller 元件/新增設定介面
From Joomla! Documentation
< J3.x:Developing an MVC Component
在選單類型中新增一個變數請求
使用資料庫
基本的後台
新增語言管理
新增後台行為
新增後台的佈置
新增表單驗證
新增類別
新增設定介面
新增一個安裝/移除/更新程式碼檔案
新增一個前台表單
使用語言過濾功能
新增更新伺服器
這是一系列的多篇文章,旨在介紹如何開發一個 Joomla! Version Model-View-Controller 元件
讓我們從簡介開始,您可以使用底下的導覽按鈕來瀏覽文章,或是右側的方塊中的連結(列出所有的文章)。
介紹
- 本教學是 開發Joomla! 3.x MVC 元件 系列文章的一部分,閱讀本文之前,您應該先看過前面幾篇文章。
In this step we provide the ability for administrator to control the display of the category on the front end. We'll do this by specifying a global configuration parameter which can be set to Show or Hide, but also allow the administrator to override this setting on an individual Helloworld message basis. To enable this, we'll introduce a params field in the database record, which will be a string in JSON format (as is common in many Joomla core components), and we'll need to change the accompanying code to handle this.
您可以觀賞和此步驟教學有關的影片 Step 13. 新增設定介面.
新增設定參數
The Joomla framework allows the use of parameters stored in each component. With your favourite 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_HELLOWORLD_FIELD_SHOW_CATEGORY_LABEL"
description="COM_HELLOWORLD_HELLOWORLD_FIELD_SHOW_CATEGORY_DESC"
default="0"
>
<option value="0">JHIDE</option>
<option value="1">JSHOW</option>
</field>
</fieldset>
</config>
This file will be read by the com_config component of the Joomla 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 favourite editor, put these lines in admin/views/helloworlds/view.html.php.
admin/views/helloworlds/view.html.php
<?php
/**
* @package Joomla.Administrator
* @subpackage com_helloworld
*
* @copyright Copyright (C) 2005 - 2018 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');
/**
* HelloWorlds View
*
* @since 0.0.1
*/
class HelloWorldViewHelloWorlds extends JViewLegacy
{
/**
* Display the Hello World view
*
* @param string $tpl The name of the template file to parse; automatically searches through the template paths.
*
* @return void
*/
function display($tpl = null)
{
// Get application
$app = JFactory::getApplication();
$context = "helloworld.list.admin.helloworld";
// Get data from the model
$this->items = $this->get('Items');
$this->pagination = $this->get('Pagination');
$this->state = $this->get('State');
$this->filter_order = $app->getUserStateFromRequest($context.'filter_order', 'filter_order', 'greeting', 'cmd');
$this->filter_order_Dir = $app->getUserStateFromRequest($context.'filter_order_Dir', 'filter_order_Dir', 'asc', 'cmd');
$this->filterForm = $this->get('FilterForm');
$this->activeFilters = $this->get('ActiveFilters');
// Check for errors.
if (count($errors = $this->get('Errors')))
{
JError::raiseError(500, implode('<br />', $errors));
return false;
}
// Set the submenu
HelloWorldHelper::addSubmenu('helloworlds');
// Set the toolbar and number of found items
$this->addToolBar();
// Display the template
parent::display($tpl);
// Set the document
$this->setDocument();
}
/**
* Add the page title and toolbar.
*
* @return void
*
* @since 1.6
*/
protected function addToolBar()
{
$title = JText::_('COM_HELLOWORLD_MANAGER_HELLOWORLDS');
if ($this->pagination->total)
{
$title .= "<span style='font-size: 0.5em; vertical-align: middle;'>(" . $this->pagination->total . ")</span>";
}
JToolBarHelper::title($title, 'helloworld');
JToolBarHelper::addNew('helloworld.add');
JToolBarHelper::editList('helloworld.edit');
JToolBarHelper::deleteList('', 'helloworlds.delete');
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
We want to define this parameter individually on all HelloWorld data. With your favourite editor, put these lines into the admin/models/forms/helloworld.xml
admin/models/forms/helloworld.xml
<?xml version="1.0" encoding="utf-8"?>
<form
addrulepath="/administrator/components/com_helloworld/models/rules"
>
<fieldset
name="details"
label="COM_HELLOWORLD_HELLOWORLD_DETAILS"
>
<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 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>
<fields name="params">
<fieldset
name="params"
label="JGLOBAL_FIELDSET_DISPLAY_OPTIONS"
>
<field
name="show_category"
type="list"
label="COM_HELLOWORLD_HELLOWORLD_FIELD_SHOW_CATEGORY_LABEL"
description="COM_HELLOWORLD_HELLOWORLD_FIELD_SHOW_CATEGORY_DESC"
default=""
>
<option value="">JGLOBAL_USE_GLOBAL</option>
<option value="0">JHIDE</option>
<option value="1">JSHOW</option>
</field>
</fieldset>
</fields>
</form>
We define the same parameter for each message with an additional value: Use global.
Note: The details fieldset now has a label too (the same that was set in the edit view before).
修改 SQL
Data now contains a new parameter: params. The SQL structure has to be modified. With your favourite 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,
`published` tinyint(4) NOT NULL,
`catid` int(11) NOT NULL DEFAULT '0',
`params` VARCHAR(1024) 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 favourite editor, put these lines into admin/sql/updates/mysql/0.0.13.sql:
admin/sql/updates/mysql/0.0.13.sql
ALTER TABLE `#__helloworld` ADD `params` VARCHAR(1024) NOT NULL DEFAULT '';
The TableHelloWorld has to be modified in order to deal with these parameters; they will be stored in a JSON format. We have to overload the bind method to convert the array of these parameters into a JSON string for saving in the database. With your favourite editor, put these lines into admin/tables/helloworld.php.
admin/tables/helloworld.php
<?php
/**
* @package Joomla.Administrator
* @subpackage com_helloworld
*
* @copyright Copyright (C) 2005 - 2018 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);
}
/**
* Overloaded bind function
*
* @param array 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 a string.
$parameter = new JRegistry;
$parameter->loadArray($array['params']);
$array['params'] = (string)$parameter;
}
return parent::bind($array, $ignore);
}
}
修改後台
The backend edit view has to display the options to the administrator. With your favourite editor, put these lines into the admin/views/helloworld/tmpl/edit.php file:
admin/views/helloworld/tmpl/edit.php
<?php
/**
* @package Joomla.Administrator
* @subpackage com_helloworld
*
* @copyright Copyright (C) 2005 - 2018 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');
JHtml::_('behavior.formvalidator');
?>
<form action="<?php echo JRoute::_('index.php?option=com_helloworld&layout=edit&id=' . (int) $this->item->id); ?>"
method="post" name="adminForm" id="adminForm" class="form-validate">
<div class="form-horizontal">
<?php foreach ($this->form->getFieldsets() as $name => $fieldset): ?>
<fieldset class="adminform">
<legend><?php echo JText::_($fieldset->label); ?></legend>
<div class="row-fluid">
<div class="span6">
<?php foreach ($this->form->getFieldset($name) 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>
<?php endforeach; ?>
</div>
<input type="hidden" name="task" value="helloworld.edit" />
<?php echo JHtml::_('form.token'); ?>
</form>
Note: The outer foreach retrieves all of the form fieldsets while the inner one gets the selected fieldset fields.
This is the result of the $this->form->getFieldsets() command:
Array
(
[details] => stdClass Object
(
[name] => details
[label] => COM_HELLOWORLD_HELLOWORLD_DETAILS
[description] =>
)
[params] => stdClass Object
(
[name] => params
[label] => JGLOBAL_FIELDSET_DISPLAY_OPTIONS
[description] =>
)
)
Modifying the frontend
The frontend has to be modified according to the new show_category parameter.
We have to modify the model:
- it has to merge global parameters and individual parameters
- it has to provide the category
With your favourite editor, put these lines into the site/models/helloworld.php file:
site/models/helloworld.php
<?php
/**
* @package Joomla.Administrator
* @subpackage com_helloworld
*
* @copyright Copyright (C) 2005 - 2018 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 object item
*/
protected $item;
/**
* 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.
*
* Note. Calling getState in this method will result in recursion.
*
* @return void
* @since 2.5
*/
protected function populateState()
{
// Get the message id
$jinput = JFactory::getApplication()->input;
$id = $jinput->get('id', 1, 'INT');
$this->setState('message.id', $id);
// Load the parameters.
$this->setState('params', JFactory::getApplication()->getParams());
parent::populateState();
}
/**
* 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
* @return object The message to be displayed to the user
*/
public function getItem()
{
if (!isset($this->item))
{
$id = $this->getState('message.id');
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('h.greeting, h.params, c.title as category')
->from('#__helloworld as h')
->leftJoin('#__categories as c ON h.catid=c.id')
->where('h.id=' . (int)$id);
$db->setQuery((string)$query);
if ($this->item = $db->loadObject())
{
// Load the JSON string
$params = new JRegistry;
$params->loadString($this->item->params, 'JSON');
$this->item->params = $params;
// Merge global params with item params
$params = clone $this->getState('params');
$params->merge($this->item->params);
$this->item->params = $params;
}
}
return $this->item;
}
}
The view has to ask the model for the category. With your favourite editor, put these lines into the site/views/helloworld/view.html.php
site/views/helloworld/view.html.php
<?php
/**
* @package Joomla.Administrator
* @subpackage com_helloworld
*
* @copyright Copyright (C) 2005 - 2018 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');
/**
* HTML View class for the HelloWorld Component
*
* @since 0.0.1
*/
class HelloWorldViewHelloWorld extends JViewLegacy
{
/**
* Display the Hello World view
*
* @param string $tpl The name of the template file to parse; automatically searches through the template paths.
*
* @return void
*/
function display($tpl = null)
{
// Assign data to the view
$this->item = $this->get('Item');
// Check for errors.
if (count($errors = $this->get('Errors')))
{
JLog::add(implode('<br />', $errors), JLog::WARNING, 'jerror');
return false;
}
// Display the view
parent::display($tpl);
}
}
The layout can now display correctly the category or not. With your favourite editor, put these lines into site/views/helloworld/tmpl/default.php
site/views/helloworld/tmpl/default.php
<?php
/**
* @package Joomla.Administrator
* @subpackage com_helloworld
*
* @copyright Copyright (C) 2005 - 2018 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');
?>
<h1><?php echo $this->item->greeting.(($this->item->category and $this->item->params->get('show_category'))
? (' ('.$this->item->category.')') : ''); ?>
</h1>
Adding some translation strings
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
; Joomla! Project
; Copyright (C) 2005 - 2018 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
COM_HELLOWORLD_ADMINISTRATION="HelloWorld - Administration"
COM_HELLOWORLD_ADMINISTRATION_CATEGORIES="HelloWorld - Categories"
COM_HELLOWORLD_NUM="#"
COM_HELLOWORLD_HELLOWORLDS_FILTER="Filters"
COM_HELLOWORLD_PUBLISHED="Published"
COM_HELLOWORLD_HELLOWORLDS_NAME="Name"
COM_HELLOWORLD_ID="Id"
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_FIELD_SHOW_CATEGORY_LABEL="Show category"
COM_HELLOWORLD_HELLOWORLD_FIELD_SHOW_CATEGORY_DESC="If set to Show, the title of the message’s category will show."
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_EDIT_HELLOWORLD="Edit message"
COM_HELLOWORLD_N_ITEMS_DELETED_1="One message deleted"
COM_HELLOWORLD_N_ITEMS_DELETED_MORE="%d messages deleted"
COM_HELLOWORLD_N_ITEMS_PUBLISHED="%d message(s) published"
COM_HELLOWORLD_N_ITEMS_UNPUBLISHED="%d message(s) unpublished"
COM_HELLOWORLD_HELLOWORLD_GREETING_LABEL="Greeting"
COM_HELLOWORLD_HELLOWORLD_GREETING_DESC="Add Hello World Greeting"
COM_HELLOWORLD_SUBMENU_MESSAGES="Messages"
COM_HELLOWORLD_SUBMENU_CATEGORIES="Categories"
COM_HELLOWORLD_CONFIGURATION="HelloWorld Configuration"
COM_HELLOWORLD_CONFIG_GREETING_SETTINGS_LABEL="Messages settings"
COM_HELLOWORLD_CONFIG_GREETING_SETTINGS_DESC="Settings that will be applied to all messages by default"
包裝元件
Content of your code directory. Each file link below takes you to the step in the tutorial which has the latest version of that source code file.
- helloworld.xml
- site/helloworld.php
- site/index.html
- site/controller.php
- site/views/index.html
- site/views/helloworld/index.html
- site/views/helloworld/view.html.php
- site/views/helloworld/tmpl/index.html
- site/views/helloworld/tmpl/default.xml
- site/views/helloworld/tmpl/default.php
- site/models/index.html
- site/models/helloworld.php
- site/language/index.html
- site/language/en-GB/index.html
- site/language/en-GB/en-GB.com_helloworld.ini
- admin/index.html
- admin/helloworld.php
- admin/config.xml
- admin/controller.php
- admin/access.xml
- admin/helpers/helloworld.php
- admin/helpers/index.html
- admin/sql/index.html
- admin/sql/install.mysql.utf8.sql
- admin/sql/uninstall.mysql.utf8.sql
- admin/sql/updates/index.html
- admin/sql/updates/mysql/index.html
- admin/sql/updates/mysql/0.0.1.sql
- admin/sql/updates/mysql/0.0.6.sql
- admin/sql/updates/mysql/0.0.12.sql
- admin/sql/updates/mysql/0.0.13.sql
- admin/models/index.html
- admin/models/fields/index.html
- admin/models/fields/helloworld.php
- admin/models/helloworlds.php
- admin/models/helloworld.php
- admin/models/forms/filter_helloworlds.xml
- admin/models/forms/index.html
- admin/models/forms/helloworld.js
- admin/models/forms/helloworld.xml
- admin/models/rules/greeting.php
- admin/models/rules/index.html
- admin/controllers/helloworld.php
- admin/controllers/helloworlds.php
- admin/controllers/index.html
- admin/views/index.html
- admin/views/helloworld/index.html
- admin/views/helloworld/view.html.php
- admin/views/helloworld/tmpl/index.html
- admin/views/helloworld/tmpl/edit.php
- admin/views/helloworld/submitbutton.js
- admin/views/helloworlds/index.html
- admin/views/helloworlds/view.html.php
- admin/views/helloworlds/tmpl/index.html
- admin/views/helloworlds/tmpl/default.php
- admin/tables/index.html
- admin/tables/helloworld.php
- admin/language/index.html
- admin/language/en-GB/index.html
- admin/language/en-GB/en-GB.com_helloworld.ini
- admin/language/en-GB/en-GB.com_helloworld.sys.ini
- media/index.html
- media/images/index.html
- media/images/tux-16x16.png
- media/images/tux-48x48.png
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="3.0" method="upgrade">
<name>COM_HELLOWORLD</name>
<!-- The following elements are optional and free of formatting constraints -->
<creationDate>January 2018</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.13</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 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>
<languages folder="site/language">
<language tag="en-GB">en-GB/en-GB.com_helloworld.ini</language>
</languages>
<media destination="com_helloworld" folder="media">
<filename>index.html</filename>
<folder>images</folder>
</media>
<administration>
<!-- Administration Menu Section -->
<menu link='index.php?option=com_helloworld' 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>config.xml</filename>
<filename>helloworld.php</filename>
<filename>controller.php</filename>
<filename>access.xml</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">
<language tag="en-GB">en-GB/en-GB.com_helloworld.ini</language>
<language tag="en-GB">en-GB/en-GB.com_helloworld.sys.ini</language>
</languages>
</administration>
</extension>