Создайте конфигурационный файл 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>
Этот файл будет прочитан встроенным в Joomla! компонентом com_config. В конфигурации мы описали всего один параметр - отображать или же не отображать название категории в интерфейсе пользователя.
Откройте файл 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 JView { /** * HelloWorlds view display method * @return void */ 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); // Set the document $this->setDocument(); } /** * Setting the toolbar */ protected function addToolBar() { JToolBarHelper::title(JText::_('COM_HELLOWORLD_MANAGER_HELLOWORLDS'), 'helloworld'); JToolBarHelper::deleteListX('', 'helloworlds.delete'); JToolBarHelper::editListX('helloworld.edit'); JToolBarHelper::addNewX('helloworld.add'); 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')); } }
Тем самым мы добавили кнопку для настройки нашего компонента. С помощью этой кнопки мы можем установить значение по умолчанию.
Так же сделаем, что для каждого сообщения можно задавать значение этого параметра индивидуально. Для этого откройте файл admin/models/forms/helloworld.xml и замените в нем код на следующий:
<?xml version="1.0" encoding="utf-8"?> <form addrulepath="/administrator/components/com_helloworld/models/rules" > <fieldset name="details"> <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> <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>
Для хранения этого параметра нужно добавить в таблицу БД еще один столбец.
Откройте файл 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', `params` TEXT NOT NULL DEFAULT '', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8; INSERT INTO `#__helloworld` (`greeting`) VALUES ('Привет МИР! :) я из БД'), ('Прощай МИР! :( я из БД');
Также создайте файл admin/sql/updates/mysql/0.0.13.sql с кодом:
ALTER TABLE `#__helloworld` ADD `params` VARCHAR(1024) NOT NULL DEFAULT '';
Откройте файл admin/tables/helloworld.php и замените в нем код на следующий:
<?php // No direct access defined('_JEXEC') or die('Restricted access'); // import Joomla table library jimport('joomla.database.table'); /** * Hello Table class */ class HelloWorldTableHelloWorld extends JTable { /** * Constructor * * @param object 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); } /** * Overloaded load function * * @param int $pk primary key * @param boolean $reset reset data * @return boolean * @see JTable:load */ public function load($pk = null, $reset = true) { if (parent::load($pk, $reset)) { // Convert the params field to a registry. $params = new JRegistry; // loadJSON is @deprecated 12.1 Use loadString passing JSON as the format instead. $params->loadString($this->params, 'JSON'); //$params->loadJSON($this->item->params); $this->params = $params; return true; } else { return false; } } }
Для того чтобы для каждого сообщения можно было указать свое значение параметра, нам нужно изменить шаблон admin/views/helloworld/tmpl/edit.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 JView { /** * display method of Hello view * @return void */ public function display($tpl = null) { // get the Data $form = $this->get('Form'); $item = $this->get('Item'); $script = $this->get('Script'); // 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; $this->script = $script; // Set the toolbar $this->addToolBar(); // Display the template parent::display($tpl); // Set the document $this->setDocument(); } /** * Setting the toolbar */ protected function addToolBar() { JRequest::setVar('hidemainmenu', true); $isNew = ($this->item->id == 0); JToolBarHelper::title($isNew ? JText::_('COM_HELLOWORLD_MANAGER_HELLOWORLD_NEW') : JText::_('COM_HELLOWORLD_MANAGER_HELLOWORLD_EDIT'), 'helloworld'); JToolBarHelper::save('helloworld.save'); JToolBarHelper::cancel('helloworld.cancel', $isNew ? 'JTOOLBAR_CANCEL' : 'JTOOLBAR_CLOSE'); } /** * Method to set up the document properties * * @return void */ protected function setDocument() { $isNew = ($this->item->id < 1); $document = JFactory::getDocument(); $document->setTitle($isNew ? JText::_('COM_HELLOWORLD_HELLOWORLD_CREATING') : JText::_('COM_HELLOWORLD_HELLOWORLD_EDITING')); $document->addScript(JURI::root() . $this->script); $document->addScript(JURI::root() . "/administrator/components/com_helloworld" . "/views/helloworld/submitbutton.js"); JText::script('COM_HELLOWORLD_HELLOWORLD_ERROR_UNACCEPTABLE'); } }
Откройте файл admin/views/helloworld/tmpl/edit.php и замените код на следующий:
<?php // No direct access defined('_JEXEC') or die('Restricted access'); JHtml::_('behavior.tooltip'); JHtml::_('behavior.formvalidation'); $params = $this->form->getFieldsets('params'); ?> <form action="<?php echo JRoute::_('index.php?option=com_helloworld&layout=edit&id='.(int) $this->item->id); ?>" method="post" name="adminForm" id="helloworld-form" class="form-validate"> <div class="width-60 fltlft"> <fieldset class="adminform"> <legend><?php echo JText::_( 'COM_HELLOWORLD_HELLOWORLD_DETAILS' ); ?></legend> <ul class="adminformlist"> <?php foreach($this->form->getFieldset('details') as $field): ?> <li><?php echo $field->label;echo $field->input;?></li> <?php endforeach; ?> </ul> </fieldset> </div> <div class="width-40 fltrt"> <?php echo JHtml::_('sliders.start', 'helloworld-slider'); foreach ($params as $name => $fieldset): echo JHtml::_('sliders.panel', JText::_($fieldset->label), $name.'-params'); if (isset($fieldset->description) && trim($fieldset->description)): ?> <p class="tip"><?php echo $this->escape(JText::_($fieldset->description));?></p> <?php endif;?> <fieldset class="panelform" > <ul class="adminformlist"> <?php foreach ($this->form->getFieldset($name) as $field) : ?> <li><?php echo $field->label; ?><?php echo $field->input; ?></li> <?php endforeach; ?> </ul> </fieldset> <?php endforeach; ?> <?php echo JHtml::_('sliders.end'); ?> </div> <div> <input type="hidden" name="task" value="helloworld.edit" /> <?php echo JHtml::_('form.token'); ?> </div> </form>
Интерфейс пользователя так же нужно изменить.
Откройте файл 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 2.5 */ 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 2.5 */ 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; // loadJSON is @deprecated 12.1 Use loadString passing JSON as the format instead. //$params->loadString($this->item->params, 'JSON'); $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
<?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 на следующий:
<?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
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_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_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" 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"
admin/language/ru-RU/ru-RU.com_helloworld.ini
COM_HELLOWORLD="Привет МИР!" COM_HELLOWORLD_HELLOWORLD_FIELD_GREETING_DESC="Сообщение для отображения" COM_HELLOWORLD_HELLOWORLD_FIELD_GREETING_LABEL="Сообщение" COM_HELLOWORLD_HELLOWORLD_HEADING_GREETING="Приветствие" COM_HELLOWORLD_HELLOWORLD_HEADING_ID="Id" COM_HELLOWORLD_ADMINISTRATION="Привет МИР! - Администрирование" COM_HELLOWORLD_ADMINISTRATION_CATEGORIES="Привет МИР! - Категории" COM_HELLOWORLD_HELLOWORLD_CREATING="Привет МИР! - Приветствие" COM_HELLOWORLD_HELLOWORLD_DETAILS="Подробно" COM_HELLOWORLD_HELLOWORLD_EDITING="Привет МИР! - Изменить" COM_HELLOWORLD_MANAGER_HELLOWORLD_EDIT="Привет Мир!: Изменить сообщение" COM_HELLOWORLD_MANAGER_HELLOWORLD_NEW="Привет Мир!: Добавить сообщение" COM_HELLOWORLD_MANAGER_HELLOWORLDS="Привет МИР! управление" COM_HELLOWORLD_N_ITEMS_DELETED_1="Одно сообщение удалено" COM_HELLOWORLD_N_ITEMS_DELETED_MORE="%d сообщений удалено" COM_HELLOWORLD_HELLOWORLD_GREETING_LABEL="Сообщение" COM_HELLOWORLD_HELLOWORLD_GREETING_DESC="Введите сообщение для отображения" COM_HELLOWORLD_HELLOWORLD_ERROR_UNACCEPTABLE="Некоторые значения недопустимы" COM_HELLOWORLD_HELLOWORLD_FIELD_CATID_DESC="Сообщение в категории" COM_HELLOWORLD_HELLOWORLD_FIELD_CATID_LABEL="Категория" COM_HELLOWORLD_SUBMENU_MESSAGES="Сообщения" COM_HELLOWORLD_SUBMENU_CATEGORIES="Категории" COM_HELLOWORLD_CONFIGURATION="Конфигурация" COM_HELLOWORLD_CONFIG_GREETING_SETTINGS_LABEL="Параметры сообщения" COM_HELLOWORLD_CONFIG_GREETING_SETTINGS_DESC="Параметры вступят в силу для всех сообщений" COM_HELLOWORLD_HELLOWORLD_FIELD_SHOW_CATEGORY_LABEL="Выводить категорию" COM_HELLOWORLD_HELLOWORLD_FIELD_SHOW_CATEGORY_DESC="Если показать, то будет показываться и категория."
Ну и наконец в файле helloworld.xml измените версию компонента на 0.0.13 и в секцию
<files folder="admin">
добавьте строки:
<filename>config.xml</filename>
Создайте архив с компонентом, установите его на сайт.