Desarrollo de un Componente MVC/Agregar acciones 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.
Hay una serie de 5 videos (en inglés) asociados con este paso del tutorial, que cubren (1) Cambios en la vista y el diseño de Helloworlds, (2) manejo de eliminaciones, y luego tres sobre la funcionalidad requerida para soportar Nuevo y Editar: (3) Manejo de redirección de Nuevo/Editar, (4) Muestra el formulario de edición de mensajes Helloworld y (5) Manejo de Guardar y Cancelar.
In conjunction with this step, you will probably find it useful to read this description of Joomla's implementation of MVC
Agregar una barra de herramientas
En Joomla, el administrador interactúa en general con los componentes mediante el uso de una barra de herramientas. En el archivo admin/views/helloworlds/view.html.php coloca este contenido. Se creará una barra de herramientas básica y un título para el componente.
Los argumentos utilizados en, por ejemplo, JToolbarHelper::addNew se utilizan para establecer una instancia del controlador que se utilizará después del clic en el botón. Más detalles a continuación en la sección agregar controladores específicos.
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 data from the model
$this->items = $this->get('Items');
$this->pagination = $this->get('Pagination');
// 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);
}
/**
* Add the page title and toolbar.
*
* @return void
*
* @since 1.6
*/
protected function addToolBar()
{
JToolbarHelper::title(JText::_('COM_HELLOWORLD_MANAGER_HELLOWORLDS'));
JToolbarHelper::addNew('helloworld.add');
JToolbarHelper::editList('helloworld.edit');
JToolbarHelper::deleteList('', 'helloworlds.delete');
}
}
Puedes encontrar otras acciones clásicas del lado servidor en el archivo administrator/includes/toolbar.php de la instalación de Joomla.
Dado que la vista puede realizar algunas acciones, tenemos que añadir algunos datos de entrada. Con tu administrador y editor de archivos favoritos, coloca en el archivo admin/views/helloworlds/tmpl/default.php
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');
?>
<form action="index.php?option=com_helloworld&view=helloworlds" method="post" id="adminForm" name="adminForm">
<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 JText::_('COM_HELLOWORLD_HELLOWORLDS_NAME') ;?>
</th>
<th width="5%">
<?php echo JText::_('COM_HELLOWORLD_PUBLISHED'); ?>
</th>
<th width="2%">
<?php echo JText::_('COM_HELLOWORLD_ID'); ?>
</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"/>
<?php echo JHtml::_('form.token'); ?>
</form>
La función de subrayado de JRoute se usa para que el sitio muestre las URL SEF; mira Admitir las URL SEF en tu componente.
El campo "task" se utiliza para definir el parámetro controller.task que se enviará al servidor en la solicitud POST cuando se envíe el formulario.
El campo "boxchecked" se utiliza para realizar un seguimiento del número de casillas marcadas.
El uso del token de formulario ayuda a evitar ataques CSRF.
Agregar controladores específicos
Tres acciones han sido agregadas:
- helloworlds.delete
- helloworld.edit
- helloworld.add
Estas están compuestas por tareas (controlador.tarea). Por lo tanto, dos nuevos controladores HelloWorldControllerHelloWorlds y HelloWorldControllerHelloWorld tienen que ser codificados. (Para entender la diferencia entre los dos tipos de sub-controladores leer más en este artículo: sub-controladores...).
admin/controllers/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');
/**
* HelloWorlds Controller
*
* @since 0.0.1
*/
class HelloWorldControllerHelloWorlds extends JControllerAdmin
{
/**
* Proxy for getModel.
*
* @param string $name The model name. Optional.
* @param string $prefix The class prefix. Optional.
* @param array $config Configuration array for model. Optional.
*
* @return object The model.
*
* @since 1.6
*/
public function getModel($name = 'HelloWorld', $prefix = 'HelloWorldModel', $config = array('ignore_request' => true))
{
$model = parent::getModel($name, $prefix, $config);
return $model;
}
}
admin/controllers/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 Controller
*
* @package Joomla.Administrator
* @subpackage com_helloworld
* @since 0.0.9
*/
class HelloWorldControllerHelloWorld extends JControllerForm
{
}
Agregar una vista de edición
Con tu administrador y editor de archivos favoritos, crea un archivo admin/views/helloworld/view.html.php que contenga:
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);
}
/**
* 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'
);
}
}
Esta vista mostrará los datos utilizando un diseño.
Pon un archivo admin/views/helloworld/tmpl/edit.php que contenga:
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');
?>
<form action="<?php echo JRoute::_('index.php?option=com_helloworld&layout=edit&id=' . (int) $this->item->id); ?>"
method="post" name="adminForm" id="adminForm">
<div class="form-horizontal">
<fieldset class="adminform">
<legend><?php echo JText::_('COM_HELLOWORLD_HELLOWORLD_DETAILS'); ?></legend>
<div class="row-fluid">
<div class="span6">
<?php
foreach($this->form->getFieldset() as $field) {
echo $field->renderField();
}
?>
</div>
</div>
</fieldset>
</div>
<input type="hidden" name="task" value="helloworld.edit" />
<?php echo JHtml::_('form.token'); ?>
</form>
Agregar un modelo y modificar el existente
La vista HelloWorldViewHelloWorld pide el formulario y los datos a un modelo. Este modelo ha de proporcionar los métodos getTable, getForm y loadData (llamado desde el controlador JModelAdmin).
admin/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 JModelAdmin
{
/**
* 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);
}
/**
* Method to get the record form.
*
* @param array $data Data for the form.
* @param boolean $loadData True if the form is to load its own data (default case), false if not.
*
* @return mixed A JForm object on success, false on failure
*
* @since 1.6
*/
public function getForm($data = array(), $loadData = true)
{
// Get the form.
$form = $this->loadForm(
'com_helloworld.helloworld',
'helloworld',
array(
'control' => 'jform',
'load_data' => $loadData
)
);
if (empty($form))
{
return false;
}
return $form;
}
/**
* Method to get the data that should be injected in the form.
*
* @return mixed The data for the form.
*
* @since 1.6
*/
protected function loadFormData()
{
// Check the session for previously entered form data.
$data = JFactory::getApplication()->getUserState(
'com_helloworld.edit.helloworld.data',
array()
);
if (empty($data))
{
$data = $this->getItem();
}
return $data;
}
}
Este modelo hereda de la clase JModelAdmin y utiliza su método loadForm. Este método busca formularios en la carpeta forms. Con tu administrador y editor de archivos favoritos, coloca un archivo admin/models/forms/helloworld.xml que contenga:
admin/models/forms/helloworld.xml
<?xml version="1.0" encoding="utf-8"?>
<form>
<fieldset>
<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"
default=""
/>
</fieldset>
</form>
Nota: COM_HELLOWORLD_HELLOWORLD_GREETING_LABEL y COM_HELLOWORLD_HELLOWORLD_GREETING_DESC son un alias para COM_HELLOWORLD_HELLOWORLD_FIELD_GREETING_LABEL y COM_HELLOWORLD_HELLOWORLD_FIELD_GREETING_DESC, respectivamente.
Aquí estamos utilizando diferentes etiquetas y descripciones para transmitir dos significados diferentes en dos secciones diferentes, pero pueden ser fácilmente mantenidas igual.
Empaquetado del componente
El contenido de tu directorio de código
- 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/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/edit.php
- admin/views/helloworld/tmpl/index.html
- 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
Crea un archivo comprimido de este directorio o descargar 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.9</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>
<administration>
<!-- Administration Menu Section -->
<menu link='index.php?option=com_helloworld'>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>
Por favor, crea una petición o tema en https://github.com/joomla/Joomla-3.2-Hello-World-Component para cualquier discrepancia en el código o para la edición de cualquier parte del código fuente de esta página.