Joomla 1.6 Добавление параметров конфигурации
Из документации Joomla!
Добавление параметров конфигурации
Joomla!1.6 позволяет в компоненте использовать параметры. Создадим файл параметров admin/config.xml:
admin/config.xml
<?xml version="1.0" encoding="utf-8"?><br /><config><br /> <fieldset<br /> name="greetings"<br /> label="COM_HELLOWORLD_CONFIG_GREETING_SETTINGS_LABEL"<br /> description="COM_HELLOWORLD_CONFIG_GREETING_SETTINGS_DESC"<br /> ><br /> <field<br /> name="show_category"<br /> type="radio"<br /> label="COM_HELLOWORLD_HELLOWORLD_FIELD_SHOW_CATEGORY_LABEL"<br /> description="COM_HELLOWORLD_HELLOWORLD_FIELD_SHOW_CATEGORY_DESC"<br /> default="0"<br /> ><br /> <option value="0">JHIDE</option><br /> <option value="1">JSHOW</option><br /> </field><br /> </fieldset><br /></config></pre><br /><p> </p><br /><p>Этот файл обрабатывается компонентом <em>com</em><em>_</em><em>config</em> ядра Joola!1.6. Пока он содержит только один параметр: отображать название категории?.</p><br /><p>Оптимальный способ установки параметров – это добавить кнопку <em>Preferences</em> на панель инструментов.</p><br /><p>Для этого изменим файл <em>admin</em><em>/</em><em>views</em><em>/</em><em>helloworlds</em><em>/</em><em>view</em><em>.</em><em>html</em><em>.</em><em>php</em></p><br /><p><em>admin/views/helloworlds/view.html.php</em></p><br /><pre style="margin: 5px; border: 1px solid #000080; background-color: #ececfc;"><?php<br />// No direct access to this file<br />defined('_JEXEC') or die('Restricted access');<br /> <br />// import Joomla view library<br />jimport('joomla.application.component.view');<br /> <br />/**<br /> * HelloWorlds View<br /> */<br />class HelloWorldViewHelloWorlds extends JView<br />{<br /> /**<br /> * HelloWorlds view display method<br /> * @return void<br /> */<br /> function display($tpl = null) <br /> {<br /> // Get data from the model<br /> $items = $this->get('Items');<br /> $pagination = $this->get('Pagination');<br /> <br /> // Check for errors.<br /> if (count($errors = $this->get('Errors'))) <br /> {<br /> JError::raiseError(500, implode('<br />', $errors));<br /> return false;<br /> }<br /> // Assign data to the view<br /> $this->items = $items;<br /> $this->pagination = $pagination;<br /> <br /> // Set the toolbar<br /> $this->addToolBar();<br /> <br /> // Display the template<br /> parent::display($tpl);<br /> <br /> // Set the document<br /> $this->setDocument();<br /> }<br /> <br /> /**<br /> * Setting the toolbar<br /> */<br /> protected function addToolBar() <br /> {<br /> JToolBarHelper::title(JText::_('COM_HELLOWORLD_MANAGER_HELLOWORLDS'), 'helloworld');<br /> JToolBarHelper::deleteListX('', 'helloworlds.delete');<br /> JToolBarHelper::editListX('helloworld.edit');<br /> JToolBarHelper::addNewX('helloworld.add');<br /> JToolBarHelper::preferences('com_helloworld');<br /> }<br /> /**<br /> * Method to set up the document properties<br /> *<br /> * @return void<br /> */<br /> protected function setDocument() <br /> {<br /> $document = JFactory::getDocument();<br /> $document->setTitle(JText::_('COM_HELLOWORLD_ADMINISTRATION'));<br /> }<br />}</pre><br /><p> </p><br /><div><br /><p><strong>Использование параметров конфигурации по умолчанию</strong></p><br /></div><br /><p>Например, мы хотим определить этот параметр индивидуально для всех данных HelloWorld. Изменим файл <em>admin/models/forms/helloworld.xml</em></p><br /><p><em>admin/models/forms/helloworld.xml</em></p><br /><pre style="margin: 5px; border: 1px solid #000080; background-color: #ececfc;"><?xml version="1.0" encoding="utf-8"?><br /><form<br /> addrulepath="/administrator/components/com_helloworld/models/rules"<br />><br /> <fieldset name="details"><br /> <field<br /> name="id"<br /> type="hidden"<br /> /><br /> <field<br /> name="greeting"<br /> type="text"<br /> label="COM_HELLOWORLD_HELLOWORLD_FIELD_GREETING_LABEL"<br /> description="COM_HELLOWORLD_HELLOWORLD_FIELD_GREETING_DESC"<br /> size="40"<br /> class="inputbox validate-greeting"<br /> validate="greeting"<br /> required="true"<br /> default=""<br /> /><br /> <field<br /> name="catid"<br /> type="category"<br /> extension="com_helloworld"<br /> class="inputbox"<br /> default=""<br /> label="COM_HELLOWORLD_HELLOWORLD_FIELD_CATID_LABEL"<br /> description="COM_HELLOWORLD_HELLOWORLD_FIELD_CATID_DESC"<br /> required="true"<br /> ><br /> <option value="0">JOPTION_SELECT_CATEGORY</option><br /> </field><br /> </fieldset><br /> <fields name="params"><br /> <fieldset<br /> name="params"<br /> label="JGLOBAL_FIELDSET_DISPLAY_OPTIONS"<br /> ><br /> <field<br /> name="show_category"<br /> type="list"<br /> label="COM_HELLOWORLD_HELLOWORLD_FIELD_SHOW_CATEGORY_LABEL"<br /> description="COM_HELLOWORLD_HELLOWORLD_FIELD_SHOW_CATEGORY_DESC"<br /> default=""<br /> ><br /> <option value="">JGLOBAL_USE_GLOBAL</option><br /> <option value="0">JHIDE</option><br /> <option value="1">JSHOW</option><br /> </field><br /> </fieldset><br /> </fields><br /></form></pre><br /><p> </p><br /><p>В нем определим параметры для каждого сообщения с дополнительным значением: <em>Use</em><em> </em><em>global</em>.</p><br /><p> </p><br /><div><br /><p><strong>Изменение SQL</strong></p><br /></div><br /><p>Добавим в таблицу новое поле: <em>params</em>. Для этого изменим файл <em>admin</em><em>/</em><em>sql</em><em>/</em><em>install</em><em>.</em><em>mysql</em><em>.</em><em>utf</em><em>8.</em><em>sql</em>:</p><br /><p><em>admin/sql/install.mysql.utf8.sql</em></p><br /><pre style="margin: 5px; border: 1px solid #000080; background-color: #ececfc;">DROP TABLE IF EXISTS `#__helloworld`;<br /> <br />CREATE TABLE `#__helloworld` (<br /> `id` int(11) NOT NULL AUTO_INCREMENT,<br /> `greeting` varchar(25) NOT NULL,<br /> `catid` int(11) NOT NULL DEFAULT '0',<br /> `params` TEXT NOT NULL DEFAULT '',<br /> PRIMARY KEY (`id`)<br />) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;<br /> <br />INSERT INTO `#__helloworld` (`greeting`) VALUES<br /> ('Hello World!'),<br /> ('Good bye World!');</pre><br /><p> </p><br /><p>Создадим файл <em>admin/sql/updates/mysql/0.0.13.sql</em>:</p><br /><p><em>admin/sql/updates/mysql/0.0.13.sql</em></p><br /><pre style="margin: 5px; border: 1px solid #000080; background-color: #ececfc;">ALTER TABLE `#__helloworld` ADD `params` VARCHAR(1024) NOT NULL DEFAULT '';</pre><br /><p> </p><br /><p>Для работы с параметрами нужно изменить файл таблицы <em>TableHelloWorld</em><em>. </em>Параметры будут храниться в формате JSON и получить их можно будет с помощью класса <em>JParameter</em>. Нам нужно переопределить методы <em>bind</em> и <em>load</em>. Для этого изменим файл <em>admin</em><em>/</em><em>tables</em><em>/</em><em>helloworld</em><em>.</em><em>php</em></p><br /><p><em>admin/tables/helloworld.php</em></p><br /><pre style="margin: 5px; border: 1px solid #000080; background-color: #ececfc;"><?php<br />// No direct access<br />defined('_JEXEC') or die('Restricted access');<br /> <br />// import Joomla table library<br />jimport('joomla.database.table');<br /> <br />/**<br /> * Hello Table class<br /> */<br />class HelloWorldTableHelloWorld extends JTable<br />{<br /> /**<br /> * Constructor<br /> *<br /> * @param object Database connector object<br /> */<br /> function __construct(&$db) <br /> {<br /> parent::__construct('#__helloworld', 'id', $db);<br /> }<br /> /**<br /> * Overloaded bind function<br /> *<br /> * @param array named array<br /> * @return null|string null is operation was satisfactory, otherwise returns an error<br /> * @see JTable:bind<br /> * @since 1.5<br /> */<br /> public function bind($array, $ignore = '') <br /> {<br /> if (isset($array['params']) && is_array($array['params'])) <br /> {<br /> // Convert the params field to a string.<br /> $parameter = new JRegistry;<br /> $parameter->loadArray($array['params']);<br /> $array['params'] = (string)$parameter;<br /> }<br /> return parent::bind($array, $ignore);<br /> }<br /> <br /> /**<br /> * Overloaded load function<br /> *<br /> * @param int $pk primary key<br /> * @param boolean $reset reset data<br /> * @return boolean<br /> * @see JTable:load<br /> */<br /> public function load($pk = null, $reset = true) <br /> {<br /> if (parent::load($pk, $reset)) <br /> {<br /> // Convert the params field to a registry.<br /> $params = new JRegistry;<br /> $params->loadJSON($this->params);<br /> $this->params = $params;<br /> return true;<br /> }<br /> else<br /> {<br /> return false;<br /> }<br /> }<br />}</pre><br /><p> </p><br /><div><br /><p><strong>Изменения в административной части</strong></p><br /></div><br /><p>Нам нужно изменить представление редактирования для отображения параметров. Изменим файл <em>admin/views/helloworld/tmpl/edit.php</em>:</p><br /><p><em>admin/views/helloworld/tmpl/edit.php</em></p><br /><pre style="margin: 5px; border: 1px solid #000080; background-color: #ececfc;"><?php<br />// No direct access<br />defined('_JEXEC') or die('Restricted access');<br />JHtml::_('behavior.tooltip');<br />JHtml::_('behavior.formvalidation');<br />$params = $this->form->getFieldsets('params');<br />?><br /><form action="" method="post" name="adminForm" id="helloworld-form" class="form-validate"><br /> <br /> <div class="width-60 fltlft"><br /> <fieldset class="adminform"><br /> <legend><?php echo JText::_( 'COM_HELLOWORLD_HELLOWORLD_DETAILS' ); ?></legend><br /> <ul class="adminformlist"><br /><?php foreach($this->form->getFieldset('details') as $field): ?><br /> <li><?php echo $field->label;echo $field->input;?></li><br /><?php endforeach; ?><br /> </ul><br /> </div><br /> <br /> <div class="width-40 fltrt"><br /> <?php echo JHtml::_('sliders.start', 'helloworld-slider'); ?><br /><?php foreach ($params as $name => $fieldset): ?><br /> <?php echo JHtml::_('sliders.panel', JText::_($fieldset->label), $name.'-params');?><br /> <?php if (isset($fieldset->description) && trim($fieldset->description)): ?><br /> <p class="tip"><?php echo $this->escape(JText::_($fieldset->description));?></p><br /> <?php endif;?><br /> <fieldset class="panelform" >
<ul class="adminformlist"><br /> <?php foreach ($this->form->getFieldset($name) as $field) : ?><br /> <li><?php echo $field->label; ?><?php echo $field->input; ?></li><br /> <?php endforeach; ?><br /> </ul><br /> </fieldset><br /><?php endforeach; ?><br /> <br /> <?php echo JHtml::_('sliders.end'); ?><br /> </div><br /> <br /> <div><br /> <input type="hidden" name="task" value="helloworld.edit" />
<?php echo JHtml::_('form.token'); ?>
</div>
</form>
Изменения в общей части
Теперь нам необходимо внести изменения в общую часть для работы с параметром show_category.
Теперь наша модель:
- должна объединять глобальные и индивидуальные параметры
- должна использовать категорию
Изменим файл site/models/helloworld.php file:
site/models/helloworld.php
<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
// import Joomla modelitem library
jimport('joomla.application.component.modelitem');
/**
* HelloWorld Model
*/
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 1.6
*/
protected function populateState()
{
$app = JFactory::getApplication();
// Get the message id
$id = JRequest::getInt('id');
$this->setState('message.id', $id);
// Load the parameters.
$params = $app->getParams();
$this->setState('params', $params);
parent::populateState();
}
/**
* 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 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');
$this->_db->setQuery($this->_db->getQuery(true)
->from('#__helloworld as h')
->leftJoin('#__categories as c ON h.catid=c.id')
->select('h.greeting, h.params, c.title as category')
->where('h.id=' . (int)$id));
if (!$this->item = $this->_db->loadObject())
{
$this->setError($this->_db->getError());
}
else
{
// Load the JSON string
$params = new JRegistry;
$params->loadJSON($this->item->params);
$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;
}
}
Представление должно получить модель для конкретной категории. Изменим файл site/views/helloworld/view.html.php
site/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');
/**
* HTML View class for the HelloWorld Component
*/
class HelloWorldViewHelloWorld extends JView
{
// Overwriting JView display method
function display($tpl = null)
{
// Assign data to the view
$this->item = $this->get('Item');
// Check for errors.
if (count($errors = $this->get('Errors')))
{
JError::raiseError(500, implode('<br />', $errors));
return false;
}
// Display the view
parent::display($tpl);
}
}
Изменим файл site/views/helloworld/tmpl/default.php
site/views/helloworld/tmpl/default.php
<?php
// 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>
Добавление строк перевода
В файл admin/language/en-GB/en-GB.com_helloworld.ini добавим строки:
admin/language/en-GB/en-GB.com_helloworld.ini
COM_HELLOWORLD="Hello World!"<br />COM_HELLOWORLD_ADMINISTRATION="HelloWorld - Administration"<br />COM_HELLOWORLD_ADMINISTRATION_CATEGORIES="HelloWorld - Categories"<br />COM_HELLOWORLD_HELLOWORLD_CREATING="HelloWorld - Creating"<br />COM_HELLOWORLD_HELLOWORLD_DETAILS="Details"<br />COM_HELLOWORLD_HELLOWORLD_EDITING="HelloWorld - Editing"<br />COM_HELLOWORLD_HELLOWORLD_ERROR_UNACCEPTABLE="Some values are unacceptable"<br />COM_HELLOWORLD_HELLOWORLD_FIELD_CATID_DESC="The category the messages belongs to"<br />COM_HELLOWORLD_HELLOWORLD_FIELD_CATID_LABEL="Category"<br />COM_HELLOWORLD_HELLOWORLD_FIELD_GREETING_DESC="This message will be displayed"<br />COM_HELLOWORLD_HELLOWORLD_FIELD_GREETING_LABEL="Message"<br />COM_HELLOWORLD_HELLOWORLD_FIELD_SHOW_CATEGORY_LABEL="Show category"<br />COM_HELLOWORLD_HELLOWORLD_FIELD_SHOW_CATEGORY_DESC="If set to Show, the title of the message’s category will show."<br />COM_HELLOWORLD_HELLOWORLD_HEADING_GREETING="Greeting"<br />COM_HELLOWORLD_HELLOWORLD_HEADING_ID="Id"<br />COM_HELLOWORLD_MANAGER_HELLOWORLD_EDIT="HelloWorld manager: Edit Message"<br />COM_HELLOWORLD_MANAGER_HELLOWORLD_NEW="HelloWorld manager: New Message"<br />COM_HELLOWORLD_MANAGER_HELLOWORLDS="HelloWorld manager"<br />COM_HELLOWORLD_N_ITEMS_DELETED_1="One message deleted"<br />COM_HELLOWORLD_N_ITEMS_DELETED_MORE="%d messages deleted"<br />COM_HELLOWORLD_SUBMENU_MESSAGES="Messages"<br />COM_HELLOWORLD_SUBMENU_CATEGORIES="Categories"<br />COM_HELLOWORLD_CONFIGURATION="HelloWorld Configuration"<br />COM_HELLOWORLD_CONFIG_GREETING_SETTINGS_LABEL="Messages settings"<br />COM_HELLOWORLD_CONFIG_GREETING_SETTINGS_DESC="Settings that will be applied to all messages by default"</pre><br /><p> </p><br /><div><br /><p><strong>Установочный пакет</strong></p><br /></div><br /><ul><br /><li><em>helloworld.xml</em></li><br /><li><em>site/index.html</em></li><br /><li><em>site/helloworld.php</em></li><br /><li><em>site/controller.php</em></li><br /><li><em>site/views/index.html</em></li><br /><li><em>site/views/helloworld/index.html</em></li><br /><li><em>site/views/helloworld/view.html.php</em></li><br /><li><em>site/views/helloworld/tmpl/index.html</em></li><br /><li><em>site/views/helloworld/tmpl/default.xml</em></li><br /><li><em>site/views/helloworld/tmpl/default.php</em></li><br /><li><em>site/models/index.html</em></li><br /><li><em>site/models/helloworld.php</em></li><br /><li><em>site/language/index.html</em></li><br /><li><em>site/language/en-GB/index.html</em></li><br /><li><em>site/language/en-GB/en-GB.com_helloworld.ini</em></li><br /><li><em>admin/index.html</em></li><br /><li><em>admin/config.xml</em></li><br /><li><em>admin/helloworld.php</em></li><br /><li><em>admin/controller.php</em></li><br /><li><em>admin/sql/index.html</em></li><br /><li><em>admin/sql/install.mysql.utf8.sql</em></li><br /><li><em>admin/sql/uninstall.mysql.utf8.sql</em></li><br /><li><em>admin/sql/updates/index.html</em></li><br /><li><em>admin/sql/updates/mysql/index.html</em></li><br /><li><em>admin/sql/updates/mysql/0.0.1.sql</em></li><br /><li><em>admin/sql/updates/mysql/0.0.6.sql</em></li><br /><li><em>admin/sql/updates/mysql/0.0.12.sql</em></li><br /><li><em>admin/sql/updates/mysql/0.0.13.sql</em></li><br /><li><em>admin/models/index.html</em></li><br /><li><em>admin/models/fields/index.html</em></li><br /><li><em>admin/models/fields/helloworld.php</em></li><br /><li><em>admin/models/forms/index.html</em></li><br /><li><em>admin/models/forms/helloworld.xml</em></li><br /><li><em>admin/models/forms/helloworld.js</em></li><br /><li><em>admin/models/rules/index.html</em></li><br /><li><em>admin/models/rules/greeting.php</em></li><br /><li><em>admin/models/helloworld.php</em></li><br /><li><em>admin/models/helloworlds.php</em></li><br /><li><em>admin/views/index.html</em></li><br /><li><em>admin/views/helloworlds/index.html</em></li><br /><li><em>admin/views/helloworlds/view.html.php</em></li><br /><li><em>admin/views/helloworlds/tmpl/index.html</em></li><br /><li><em>admin/views/helloworlds/tmpl/default.php</em></li><br /><li><em>admin/views/helloworlds/tmpl/default_head.php</em></li><br /><li><em>admin/views/helloworlds/tmpl/default_body.php</em></li><br /><li><em>admin/views/helloworlds/tmpl/default_foot.php</em></li><br /><li><em>admin/views/helloworld/index.html</em></li><br /><li><em>admin/views/helloworld/view.html.php</em></li><br /><li><em>admin/views/helloworld/submitbutton.js</em></li><br /><li><em>admin/views/helloworld/tmpl/index.html</em></li><br /><li><em>admin/views/helloworld/tmpl/edit.php</em></li><br /><li><em>admin/helpers/index.html</em></li><br /><li><em>admin/helpers/helloworld.php</em></li><br /><li><em>admin/tables/index.html</em></li><br /><li><em>admin/tables/helloworld.php</em></li><br /><li><em>admin/language/en-GB/en-GB.com_helloworld.ini</em></li><br /><li><em>admin/language/en-GB/en-GB.com_helloworld.sys.ini</em></li><br /><li><em>admin/controllers/index.html</em></li><br /><li><em>admin/controllers/helloworld.php</em></li><br /><li><em>admin/controllers/helloworlds.php</em></li><br /><li><em>language/en-GB/en-GB.ini</em></li><br /><li><em>media/index.html</em></li><br /><li><em>media/images/index.html</em></li><br /><li><em>media/images/tux-16x16.png</em></li><br /><li><em>media/images/tux-48x48.png</em></li><br /></ul><br /><p>Создайте установочний файл ZIP или загрузите пакет из архива <strong><a href="http://nik1957.kiev.ua/images/stories/joomla_mvc/joomla16/com_helloworld-1.6-part13.zip">archive, и установите пакет с помощью менеджера расширений Joomla!1.6.<br /><p><em>helloworld.xm</em></p> <pre style="margin: 5px; border: 1px solid #000080; background-color: #ececfc;"><ul class="pagenav"><br /> <br /> </pre><br /><p><span style="font-size: xx-small;"><strong> </strong><strong> </strong><p> </p></pre>"</pre>"Joomla 1.6 Добавление параметров конфигурации - Генератор расширений Joomla и многое другое на нашем сайте посвященном работе расширений, компонентов, модулей, плагинов для линейки Joomla. Отправляйте ссылку на страницу своим друзьям и в социальные сети воспользовавшись графическими иконками выше.