Desarrollo de un Componente MVC/Agregar decoraciones del lado servidor
From Joomla! Documentation
< J3.x:Developing an MVC Component
Artículos de esta Serie
Agregar un tipo de menú a la parte del sitio
Agregar un modelo a la parte del sitio
Agregar una variable de petición en el tipo de menú
Utilizando la base de datos
Lado servidor básico
Agregar gestión de idioma
Agregar acciones del lado servidor
Agregar decoraciones del lado servidor
Agregar verificaciones
Agregar categorías
Agregar configuración
Agregar un archivo de secuencia de comandos instalar-desinstalar-actualizar
Agregar un formulario del lado cliente
Usar la facilidad filtro de idioma
- Agregar una Modal
- Agregar Asociaciones
- Agregar Comprobación
- Agregar Ordenamiento
- Agregar Niveles
- Agregar Control de Versiones
- Agregar Etiquetas
- Agregar Accesos
- Agregar procesos por lote
- Agregar Caché
- Agregar un Canal de Noticias
Agregar un servidor de actualización
Esta es una serie multi-artículos de tutoriales sobre cómo desarrollar un Componente Modelo-Vista-Controlador para Joomla! Versión.
Comenzar con la Introducción, y navegar por los artículos de esta serie usando el botón de navegación en la parte inferior o en el cuadro de la derecha (los "Artículos de esta serie").
Introducción
Este artículo es parte del tutorial Desarrollo de un Componente MVC para Joomla! 3.2. Te invitamos a leer las partes anteriores del tutorial antes de leer esto. La funcionalidad que se cubre en este paso incluye hacer que las columnas sean ordenables, y puedes encontrar un tutorial que describe este aspecto en Agregar columnas ordenables a una tabla en un componente.
Puedes ver un video (en inglés) asociado con este paso del tutorial en Paso 10, Agregar decoraciones del lado servidor.
Agregar algunos iconos
Con tu administrador de archivos favorito coloca una imagen de 16x16 y una 48x48 (yo elegí "Tux") en una carpeta media/images/ y agrega una etiqueta media en el archivo de instalación. Modifica la etiqueta del menú con el fin de utilizar el nuevo icono.
Ten en cuenta que de forma predeterminada la plantilla del admin (isis) desactiva los iconos del menú! Una posible solución es el uso de icoMoon en su cadena de idioma:
admin/language/en-GB/en-GB.com_helloworld.sys.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="Hello World!"
COM_HELLOWORLD_DESCRIPTION="This is the Hello World description"
COM_HELLOWORLD_HELLOWORLD_VIEW_DEFAULT_TITLE="Hello World"
COM_HELLOWORLD_HELLOWORLD_VIEW_DEFAULT_DESC="This view displays a selected message"
COM_HELLOWORLD_MENU=" <i class="icon-smiley-2"></i>Hello World!"
La lista de iconos se puede encontrar aquí: Tipografía Estándar Icomoon para Joomla!.
Modificar las vistas
En el archivo admin/views/helloworlds/view.html.php poner estas líneas:
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 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::deleteList('', 'helloworlds.delete');
JToolBarHelper::editList('helloworld.edit');
JToolBarHelper::addNew('helloworld.add');
}
/**
* Method to set up the document properties
*
* @return void
*/
protected function setDocument()
{
$document = JFactory::getDocument();
$document->setTitle(JText::_('COM_HELLOWORLD_ADMINISTRATION'));
}
}
$this->filter_order y $this->filter_order_Dir guarda el orden activo de la columna y la dirección del orden respectivamente. Esas variables son obtenidas desde las variables de estado de la aplicación.
Ver Cómo usar las variables de estado del usuario para más información sobre el uso de las variables de estado.
Esta vista utiliza un segundo parámetro para la función JToolBarHelper::title. Será utilizado para construir la clase css para el título. El método _setDocument establece el título del navegador.
En el archivo admin/views/helloworlds/tmpl/default.php coloca estas líneas:
admin/views/helloworlds/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');
JHtml::_('formbehavior.chosen', 'select');
$listOrder = $this->escape($this->filter_order);
$listDirn = $this->escape($this->filter_order_Dir);
?>
<form action="index.php?option=com_helloworld&view=helloworlds" method="post" id="adminForm" name="adminForm">
<div class="row-fluid">
<div class="span6">
<?php echo JText::_('COM_HELLOWORLD_HELLOWORLDS_FILTER'); ?>
<?php
echo JLayoutHelper::render(
'joomla.searchtools.default',
array('view' => $this)
);
?>
</div>
</div>
<table class="table table-striped table-hover">
<thead>
<tr>
<th width="1%"><?php echo JText::_('COM_HELLOWORLD_NUM'); ?></th>
<th width="2%">
<?php echo JHtml::_('grid.checkall'); ?>
</th>
<th width="90%">
<?php echo JHtml::_('grid.sort', 'COM_HELLOWORLD_HELLOWORLDS_NAME', 'greeting', $listDirn, $listOrder); ?>
</th>
<th width="5%">
<?php echo JHtml::_('grid.sort', 'COM_HELLOWORLD_PUBLISHED', 'published', $listDirn, $listOrder); ?>
</th>
<th width="2%">
<?php echo JHtml::_('grid.sort', 'COM_HELLOWORLD_ID', 'id', $listDirn, $listOrder); ?>
</th>
</tr>
</thead>
<tfoot>
<tr>
<td colspan="5">
<?php echo $this->pagination->getListFooter(); ?>
</td>
</tr>
</tfoot>
<tbody>
<?php if (!empty($this->items)) : ?>
<?php foreach ($this->items as $i => $row) :
$link = JRoute::_('index.php?option=com_helloworld&task=helloworld.edit&id=' . $row->id);
?>
<tr>
<td><?php echo $this->pagination->getRowOffset($i); ?></td>
<td>
<?php echo JHtml::_('grid.id', $i, $row->id); ?>
</td>
<td>
<a href="<?php echo $link; ?>" title="<?php echo JText::_('COM_HELLOWORLD_EDIT_HELLOWORLD'); ?>">
<?php echo $row->greeting; ?>
</a>
</td>
<td align="center">
<?php echo JHtml::_('jgrid.published', $row->published, $i, 'helloworlds.', true, 'cb'); ?>
</td>
<td align="center">
<?php echo $row->id; ?>
</td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>
<input type="hidden" name="task" value=""/>
<input type="hidden" name="boxchecked" value="0"/>
<input type="hidden" name="filter_order" value="<?php echo $listOrder; ?>"/>
<input type="hidden" name="filter_order_Dir" value="<?php echo $listDirn; ?>"/>
<?php echo JHtml::_('form.token'); ?>
</form>
En el archivo admin/views/helloworld/view.html.php coloca estas líneas:
admin/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');
/**
* HelloWorld View
*
* @since 0.0.1
*/
class HelloWorldViewHelloWorld extends JViewLegacy
{
/**
* View form
*
* @var form
*/
protected $form = null;
/**
* Display the Hello World view
*
* @param string $tpl The name of the template file to parse; automatically searches through the template paths.
*
* @return void
*/
public function display($tpl = null)
{
// Get the Data
$this->form = $this->get('Form');
$this->item = $this->get('Item');
// Check for errors.
if (count($errors = $this->get('Errors')))
{
JError::raiseError(500, implode('<br />', $errors));
return false;
}
// Set the toolbar
$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()
{
$input = JFactory::getApplication()->input;
// Hide Joomla Administrator Main menu
$input->set('hidemainmenu', true);
$isNew = ($this->item->id == 0);
if ($isNew)
{
$title = JText::_('COM_HELLOWORLD_MANAGER_HELLOWORLD_NEW');
}
else
{
$title = JText::_('COM_HELLOWORLD_MANAGER_HELLOWORLD_EDIT');
}
JToolBarHelper::title($title, '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'));
}
}
Esta vista también utiliza el segundo parámetro de la función JToolBarHelper::título y establece el título del navegador.
Agregar los filtros
En admin/models/helloworlds.php, coloca estas líneas:
admin/models/helloworlds.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');
/**
* HelloWorldList Model
*
* @since 0.0.1
*/
class HelloWorldModelHelloWorlds extends JModelList
{
/**
* Constructor.
*
* @param array $config An optional associative array of configuration settings.
*
* @see JController
* @since 1.6
*/
public function __construct($config = array())
{
if (empty($config['filter_fields']))
{
$config['filter_fields'] = array(
'id',
'greeting',
'published'
);
}
parent::__construct($config);
}
/**
* Method to build an SQL query to load the list data.
*
* @return string An SQL query
*/
protected function getListQuery()
{
// Initialize variables.
$db = JFactory::getDbo();
$query = $db->getQuery(true);
// Create the base select statement.
$query->select('*')
->from($db->quoteName('#__helloworld'));
// Filter: like / search
$search = $this->getState('filter.search');
if (!empty($search))
{
$like = $db->quote('%' . $search . '%');
$query->where('greeting LIKE ' . $like);
}
// Filter by published state
$published = $this->getState('filter.published');
if (is_numeric($published))
{
$query->where('published = ' . (int) $published);
}
elseif ($published === '')
{
$query->where('(published IN (0, 1))');
}
// Add the list ordering clause.
$orderCol = $this->state->get('list.ordering', 'greeting');
$orderDirn = $this->state->get('list.direction', 'asc');
$query->order($db->escape($orderCol) . ' ' . $db->escape($orderDirn));
return $query;
}
}
Con tu administrador y editor de archivos favoritos coloca un archivo en admin/models/forms/filter_helloworlds.xml que contenga:
admin/models/forms/filter_helloworlds.xml
<?xml version="1.0" encoding="utf-8"?>
<form>
<fields name="filter">
<field
name="search"
type="text"
label="COM_BANNERS_SEARCH_IN_TITLE"
hint="JSEARCH_FILTER"
class="js-stools-search-string"
/>
<field
name="published"
type="status"
label="JOPTION_SELECT_PUBLISHED"
description="JOPTION_SELECT_PUBLISHED_DESC"
onchange="this.form.submit();"
>
<option value="">JOPTION_SELECT_PUBLISHED</option>
</field>
</fields>
<fields name="list">
<field
name="limit"
type="limitbox"
class="input-mini"
default="25"
label="COM_CONTENT_LIST_LIMIT"
description="COM_HELLOWORLD_LIST_LIMIT_DESC"
onchange="this.form.submit();"
/>
</fields>
</form>
Modificando el archivo de entrada principal
En el archivo admin/helloworld.php, coloca estas líneas con el fin de utilizar el icono 48x48:
<?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');
// Set some global property
$document = JFactory::getDocument();
$document->addStyleDeclaration('.icon-helloworld {background-image: url(../media/com_helloworld/images/Tux-16x16.png);}');
// Get an instance of the controller prefixed by HelloWorld
$controller = JControllerLegacy::getInstance('HelloWorld');
// Perform the Request task
$input = JFactory::getApplication()->input;
$controller->execute($input->getCmd('task'));
// Redirect if set by the controller
$controller->redirect();
Agregar algunas cadenas de texto en el archivo de idioma
Modifica el archivo admin/language/en-GB/en-GB.com_helloworld.ini y coloca estas líneas
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_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_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_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"
Empaquetado del componente
Contenido de tu directorio de código. Cada enlace de archivo a continuación te lleva al paso en el tutorial que tiene la última versión de ese archivo de código fuente.
- 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/controller.php
- 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/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.xml
- 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/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
Crea un archivo comprimido de este directorio o descarga directamente el archivo e instálalo con el gestor de extensiones de Joomla. Puedes agregar un elemento de menú de este componente usando el gestor de menús en el lado del servidor.
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.10</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>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>
</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>