Difference between revisions of "Developing an MVC Component/Adding verifications/es"
From Joomla! Documentation
< J3.x:Developing an MVC Component
(17 intermediate revisions by 2 users not shown) | |||
Line 1: | Line 1: | ||
<noinclude><languages /></noinclude> | <noinclude><languages /></noinclude> | ||
− | |||
{{:J3.1:Developing an MVC Component/es}} | {{:J3.1:Developing an MVC Component/es}} | ||
== Introducción == | == Introducción == | ||
Este artículo es parte del tutorial [[S:MyLanguage/J3.2:Developing an MVC Component|Desarrollo de un Componente MVC para Joomla! 3.2]]. Te invitamos a leer las partes anteriores del tutorial antes de leer esto. | Este artículo es parte del tutorial [[S:MyLanguage/J3.2:Developing an MVC Component|Desarrollo de un Componente MVC para Joomla! 3.2]]. Te invitamos a leer las partes anteriores del tutorial antes de leer esto. | ||
Ver [[S:MyLanguage/Form validation|Validación de un Formulario]] para más información general sobre la validación de formularios (reglas). | Ver [[S:MyLanguage/Form validation|Validación de un Formulario]] para más información general sobre la validación de formularios (reglas). | ||
+ | |||
+ | Puedes ver un vídeo (en inglés) asociado con este paso en [https://youtu.be/xzYRI3R--CE Paso 11, agregando verificaciones]. Este y los siguientes vídeos están grabados en HD; Has clic en la rueda de configuración de YouTube para ver la mejor resolución. | ||
+ | |||
+ | {{#widget:YouTube|id=xzYRI3R--CE}} | ||
== Verificación del formulario (lado del cliente) == | == Verificación del formulario (lado del cliente) == | ||
+ | Consulta [[S:MyLanguage/Client-side_form_validation|Formulario de validación del lado del cliente]] para obtener más información del tutorial relacionado con la verificación del lado del cliente. | ||
Los formularios pueden ser verificados en el lado del cliente mediante código javascript. | Los formularios pueden ser verificados en el lado del cliente mediante código javascript. | ||
− | En el archivo ''[[#admin/views/helloworld/tmpl/edit.php | + | En el archivo ''[[#admin/views/helloworld/tmpl/edit.php|admin/views/helloworld/tmpl/edit.php]]'', coloca estas líneas: |
<span id="admin/views/helloworld/tmpl/edit.php"> | <span id="admin/views/helloworld/tmpl/edit.php"> | ||
<tt>admin/views/helloworld/tmpl/edit.php</tt> | <tt>admin/views/helloworld/tmpl/edit.php</tt> | ||
− | <source lang="php" highlight=" | + | <source lang="php" highlight="15"> |
<?php | <?php | ||
/** | /** | ||
Line 17: | Line 21: | ||
* @subpackage com_helloworld | * @subpackage com_helloworld | ||
* | * | ||
− | * @copyright Copyright (C) 2005 - | + | * @copyright Copyright (C) 2005 - 2018 Open Source Matters, Inc. All rights reserved. |
* @license GNU General Public License version 2 or later; see LICENSE.txt | * @license GNU General Public License version 2 or later; see LICENSE.txt | ||
*/ | */ | ||
Line 23: | Line 27: | ||
// No direct access | // No direct access | ||
defined('_JEXEC') or die('Restricted access'); | defined('_JEXEC') or die('Restricted access'); | ||
− | |||
?> | ?> | ||
<form action="<?php echo JRoute::_('index.php?option=com_helloworld&layout=edit&id=' . (int) $this->item->id); ?>" | <form action="<?php echo JRoute::_('index.php?option=com_helloworld&layout=edit&id=' . (int) $this->item->id); ?>" | ||
Line 49: | Line 52: | ||
</span> | </span> | ||
− | Puedes haber notado que el código html del formulario que figura en el archivo ''[[#admin/views/helloworld/tmpl/edit.php|admin/views/helloworld/tmpl/edit.php]]'' tiene ahora la clase css ''form-validate'' | + | Puedes haber notado que el código html del formulario que figura en el archivo ''[[#admin/views/helloworld/tmpl/edit.php|admin/views/helloworld/tmpl/edit.php]]'' tiene ahora la clase css ''form-validate''. |
Modifica el archivo <tt>admin/models/forms/helloworld.xml</tt> para indicar que el campo ''greeting'' tiene que ser verificado: | Modifica el archivo <tt>admin/models/forms/helloworld.xml</tt> para indicar que el campo ''greeting'' tiene que ser verificado: | ||
Line 116: | Line 119: | ||
if (action[1] != 'cancel' && action[1] != 'close') | if (action[1] != 'cancel' && action[1] != 'close') | ||
{ | { | ||
− | var forms = | + | var forms = jQuery('form.form-validate'); |
− | for (var i=0;i<forms.length;i++) | + | for (var i = 0; i < forms.length; i++) |
{ | { | ||
if (!document.formvalidator.isValid(forms[i])) | if (!document.formvalidator.isValid(forms[i])) | ||
Line 143: | Line 146: | ||
</span> | </span> | ||
− | Esta función se encargará de verificar que todos los formularios que tienen la clase css ''"form-validate"' son válidos. Ten en cuenta que se mostrará un mensaje de alerta traducido por | + | Esta función se encargará de verificar que todos los formularios que tienen la clase css ''"form-validate"' son válidos. Ten en cuenta que se mostrará un mensaje de alerta traducido por el framework de Joomla. |
La clase ''HelloWorldViewHelloWorld'' de la vista tiene que ser modificada para usar estos archivos javascript: | La clase ''HelloWorldViewHelloWorld'' de la vista tiene que ser modificada para usar estos archivos javascript: | ||
Line 149: | Line 152: | ||
<span id="admin/views/helloworld/view.html.php"> | <span id="admin/views/helloworld/view.html.php"> | ||
<tt>admin/views/helloworld/view.html.php</tt> | <tt>admin/views/helloworld/view.html.php</tt> | ||
− | <source lang="php" highlight="39, | + | <source lang="php" highlight="39,100-101,107-110"> |
<?php | <?php | ||
/** | /** | ||
Line 155: | Line 158: | ||
* @subpackage com_helloworld | * @subpackage com_helloworld | ||
* | * | ||
− | * @copyright Copyright (C) 2005 - | + | * @copyright Copyright (C) 2005 - 2018 Open Source Matters, Inc. All rights reserved. |
* @license GNU General Public License version 2 or later; see LICENSE.txt | * @license GNU General Public License version 2 or later; see LICENSE.txt | ||
*/ | */ | ||
Line 234: | Line 237: | ||
} | } | ||
− | + | JToolbarHelper::title($title, 'helloworld'); | |
− | + | JToolbarHelper::save('helloworld.save'); | |
− | + | JToolbarHelper::cancel( | |
'helloworld.cancel', | 'helloworld.cancel', | ||
$isNew ? 'JTOOLBAR_CANCEL' : 'JTOOLBAR_CLOSE' | $isNew ? 'JTOOLBAR_CANCEL' : 'JTOOLBAR_CLOSE' | ||
Line 248: | Line 251: | ||
protected function setDocument() | protected function setDocument() | ||
{ | { | ||
+ | |||
+ | JHtml::_('behavior.framework'); | ||
+ | JHtml::_('behavior.formvalidator'); | ||
+ | |||
$isNew = ($this->item->id < 1); | $isNew = ($this->item->id < 1); | ||
$document = JFactory::getDocument(); | $document = JFactory::getDocument(); | ||
Line 266: | Line 273: | ||
* agrega dos archivos javascript; | * agrega dos archivos javascript; | ||
* inyecta la traducción javascript usando la función Joomla <tt>JText::script</tt>. | * inyecta la traducción javascript usando la función Joomla <tt>JText::script</tt>. | ||
+ | |||
+ | You will also notice our two lines adding additional behaviors when injecting our scripts. By default, Joomla injects the Javascript we specify into the page <i>before</i> its own global Javascript libraries, such as jQuery and Joomla Core. As our Javascript code directly utilises the <tt>Joomla</tt> object, loading it onto the page before the global Javascript libraries will result in immediate failure, and the form validation will not run. | ||
+ | |||
+ | By specifying these two behaviors via the JHtml helper class prior to injecting our own Javascript, we ensure they are loaded first on the page, and our code will execute correctly. You would normally see JHtml used inside a template, but as our Javascript is added for each child template, it's better to specify the external dependency here. | ||
El paso final es implementar una función <tt>getScript</tt> en el modelo "HelloWorldModelHelloWorld": | El paso final es implementar una función <tt>getScript</tt> en el modelo "HelloWorldModelHelloWorld": | ||
Line 277: | Line 288: | ||
* @subpackage com_helloworld | * @subpackage com_helloworld | ||
* | * | ||
− | * @copyright Copyright (C) 2005 - | + | * @copyright Copyright (C) 2005 - 2018 Open Source Matters, Inc. All rights reserved. |
* @license GNU General Public License version 2 or later; see LICENSE.txt | * @license GNU General Public License version 2 or later; see LICENSE.txt | ||
*/ | */ | ||
Line 373: | Line 384: | ||
== Verificación del formulario (lado del servidor) == | == Verificación del formulario (lado del servidor) == | ||
+ | Consulta [[S:MyLanguage/Server-side_form_validation|Formulario de validación del lado del servidor]] para obtener más información del tutorial relacionada con la verificación del lado del servidor. | ||
La verificación del formulario en el lado del servidor se realiza por medio de la herencia de la clase <tt>JControllerForm</tt>. Hemos especificado en el archivo ''[[#admin/models/forms/helloworld.xml|admin/models/forms/helloworld.xml]]'' la función de validación que el servidor utilizará en el archivo <tt>greeting.php</tt>. | La verificación del formulario en el lado del servidor se realiza por medio de la herencia de la clase <tt>JControllerForm</tt>. Hemos especificado en el archivo ''[[#admin/models/forms/helloworld.xml|admin/models/forms/helloworld.xml]]'' la función de validación que el servidor utilizará en el archivo <tt>greeting.php</tt>. | ||
− | Con | + | Con tu administrador y editor de archivos favoritos coloca un archivo en <tt>admin/models/rules/greeting.php</tt> que contenga: |
<span id="admin/models/rules/greeting.php"> | <span id="admin/models/rules/greeting.php"> | ||
Line 385: | Line 397: | ||
* @subpackage com_helloworld | * @subpackage com_helloworld | ||
* | * | ||
− | * @copyright Copyright (C) 2005 - | + | * @copyright Copyright (C) 2005 - 2018 Open Source Matters, Inc. All rights reserved. |
* @license GNU General Public License version 2 or later; see LICENSE.txt | * @license GNU General Public License version 2 or later; see LICENSE.txt | ||
*/ | */ | ||
Line 413: | Line 425: | ||
== Empaquetado del componente == | == Empaquetado del componente == | ||
− | + | Contenido de su directorio de código. Cada enlace a un 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|helloworld.xml]]'' | * ''[[#helloworld.xml|helloworld.xml]]'' | ||
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Adding_a_view_to_the_site_part#site/helloworld.php|site/helloworld.php]]'' | * ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Adding_a_view_to_the_site_part#site/helloworld.php|site/helloworld.php]]'' | ||
Line 430: | Line 442: | ||
* [[S:MyLanguage/J3.x:Developing an MVC Component/Adding language management#site.2Flanguage.2Fen-GB.2Fen-GB.com_helloworld.ini|site/language/en-GB/en-GB.com_helloworld.ini]] | * [[S:MyLanguage/J3.x:Developing an MVC Component/Adding language management#site.2Flanguage.2Fen-GB.2Fen-GB.com_helloworld.ini|site/language/en-GB/en-GB.com_helloworld.ini]] | ||
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/index.html]]'' | * ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/index.html]]'' | ||
− | * ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/ | + | * ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Adding_decorations_to_the_backend#admin/helloworld.php|admin/helloworld.php]]'' |
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Basic_backend#admin/controller.php|admin/controller.php]]'' | * ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Basic_backend#admin/controller.php|admin/controller.php]]'' | ||
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/sql/index.html]]'' | * ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/sql/index.html]]'' | ||
Line 442: | Line 454: | ||
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/models/fields/index.html]]'' | * ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/models/fields/index.html]]'' | ||
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Using_the_database#admin/models/fields/helloworld.php|admin/models/fields/helloworld.php]]'' | * ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Using_the_database#admin/models/fields/helloworld.php|admin/models/fields/helloworld.php]]'' | ||
− | * ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/ | + | * ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Adding_decorations_to_the_backend#admin/models/helloworlds.php|admin/models/helloworlds.php]]'' |
− | * ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/ | + | * ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Adding_verifications#admin/models/helloworld.php|admin/models/helloworld.php]]'' |
+ | * ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Adding decorations to the backend#admin/models/forms/filter_helloworlds.xml|admin/models/forms/filter_helloworlds.xml]]'' | ||
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/models/forms/index.html]]'' | * ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/models/forms/index.html]]'' | ||
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Adding_verifications#admin/models/forms/helloworld.js|admin/models/forms/helloworld.js]]'' | * ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Adding_verifications#admin/models/forms/helloworld.js|admin/models/forms/helloworld.js]]'' | ||
− | * ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/ | + | * ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Adding_verifications#admin/models/forms/helloworld.xml|admin/models/forms/helloworld.xml]]'' |
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Adding_verifications#admin/models/rules/greeting.php|admin/models/rules/greeting.php]]'' | * ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Adding_verifications#admin/models/rules/greeting.php|admin/models/rules/greeting.php]]'' | ||
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/models/rules/index.html]]'' | * ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/models/rules/index.html]]'' | ||
Line 454: | Line 467: | ||
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/views/index.html]]'' | * ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/views/index.html]]'' | ||
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/views/helloworld/index.html]]'' | * ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/views/helloworld/index.html]]'' | ||
− | * ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/ | + | * ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Adding_verifications#admin/views/helloworld/view.html.php|admin/views/helloworld/view.html.php]]'' |
− | * ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/ | + | * ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/views/helloworld/tmpl/index.html]]'' |
+ | * ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Adding_verifications#admin/views/helloworld/tmpl/edit.php|admin/views/helloworld/tmpl/edit.php]]'' | ||
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Adding_verifications#admin/views/helloworld/submitbutton.js|admin/views/helloworld/submitbutton.js]]'' | * ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Adding_verifications#admin/views/helloworld/submitbutton.js|admin/views/helloworld/submitbutton.js]]'' | ||
* ''[[J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/views/helloworlds/index.html]]'' | * ''[[J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/views/helloworlds/index.html]]'' | ||
− | * ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/ | + | * ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Adding_decorations_to_the_backend#admin/views/helloworlds/view.html.php|admin/views/helloworlds/view.html.php]]'' |
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/views/helloworlds/tmpl/index.html]]'' | * ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/views/helloworlds/tmpl/index.html]]'' | ||
− | * ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/ | + | * ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Adding_decorations_to_the_backend#admin/views/helloworlds/tmpl/default.php|admin/views/helloworlds/tmpl/default.php]]'' |
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/tables/index.html]]'' | * ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/tables/index.html]]'' | ||
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Using_the_database#admin/tables/helloworld.php|admin/tables/helloworld.php]]'' | * ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Using_the_database#admin/tables/helloworld.php|admin/tables/helloworld.php]]'' | ||
* ''[[#admin/language/index.html|admin/language/index.html]]'' | * ''[[#admin/language/index.html|admin/language/index.html]]'' | ||
* ''[[#admin/language/en-GB/index.html|admin/language/en-GB/index.html]]'' | * ''[[#admin/language/en-GB/index.html|admin/language/en-GB/index.html]]'' | ||
− | * ''[[S:MyLanguage/J3.x:Developing an MVC Component/ | + | * ''[[S:MyLanguage/J3.x:Developing an MVC Component/Adding_decorations_to_the_backend#admin.2Flanguage.2Fen-GB.2Fen-GB.com_helloworld.ini|admin/language/en-GB/en-GB.com_helloworld.ini]]'' |
− | * ''[[S:MyLanguage/J3.x:Developing an MVC Component/ | + | * ''[[S:MyLanguage/J3.x:Developing an MVC Component/Adding_decorations_to_the_backend#admin.2Flanguage.2Fen-GB.2Fen-GB.com_helloworld.sys.ini|admin/language/en-GB/en-GB.com_helloworld.sys.ini]]'' |
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|media/index.html]]'' | * ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|media/index.html]]'' | ||
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|media/images/index.html]]'' | * ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|media/images/index.html]]'' | ||
Line 480: | Line 494: | ||
<source lang="xml" highlight="13"> | <source lang="xml" highlight="13"> | ||
<?xml version="1.0" encoding="utf-8"?> | <?xml version="1.0" encoding="utf-8"?> | ||
− | <extension type="component" version="3 | + | <extension type="component" version="3.0" method="upgrade"> |
<name>COM_HELLOWORLD</name> | <name>COM_HELLOWORLD</name> | ||
<!-- The following elements are optional and free of formatting constraints --> | <!-- The following elements are optional and free of formatting constraints --> | ||
− | <creationDate>January | + | <creationDate>January 2018</creationDate> |
<author>John Doe</author> | <author>John Doe</author> | ||
<authorEmail>john.doe@example.org</authorEmail> | <authorEmail>john.doe@example.org</authorEmail> | ||
Line 565: | Line 579: | ||
</span> | </span> | ||
− | == | + | == Colaboradores == |
*[[User:cdemko|Christophe Demko]] | *[[User:cdemko|Christophe Demko]] | ||
*[[User:oaksu|Ozgur Aksu]] | *[[User:oaksu|Ozgur Aksu]] | ||
Line 571: | Line 585: | ||
<div class="row"> | <div class="row"> | ||
− | <div class="large-6 columns">{{Basic button|S:MyLanguage/J3.x:Developing_an_MVC_Component/Adding | + | <div class="large-6 columns">{{Basic button|S:MyLanguage/J3.x:Developing_an_MVC_Component/Adding decorations to the backend|Prev: Agregar decoraciones al lado servidor|class=expand success}}</div> |
− | <div class="large-6 columns">{{Basic button|S:MyLanguage/J3.x:Developing_an_MVC_Component/Adding | + | <div class="large-6 columns">{{Basic button|S:MyLanguage/J3.x:Developing_an_MVC_Component/Adding categories|Sig: Agregar categorías|class=expand}}</div> |
</div> | </div> | ||
__NOTOC__ | __NOTOC__ |
Latest revision as of 06:24, 4 May 2020
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. Ver Validación de un Formulario para más información general sobre la validación de formularios (reglas).
Puedes ver un vídeo (en inglés) asociado con este paso en Paso 11, agregando verificaciones. Este y los siguientes vídeos están grabados en HD; Has clic en la rueda de configuración de YouTube para ver la mejor resolución.
Verificación del formulario (lado del cliente)
Consulta Formulario de validación del lado del cliente para obtener más información del tutorial relacionado con la verificación del lado del cliente. Los formularios pueden ser verificados en el lado del cliente mediante código javascript. En el archivo admin/views/helloworld/tmpl/edit.php, coloca estas líneas: 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" class="form-validate">
<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): ?>
<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>
</div>
<input type="hidden" name="task" value="helloworld.edit" />
<?php echo JHtml::_('form.token'); ?>
</form>
Puedes haber notado que el código html del formulario que figura en el archivo admin/views/helloworld/tmpl/edit.php tiene ahora la clase css form-validate.
Modifica el archivo admin/models/forms/helloworld.xml para indicar que el campo greeting tiene que ser verificado:
<?xml version="1.0" encoding="utf-8"?>
<form
addrulepath="/administrator/components/com_helloworld/models/rules"
>
<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 validate-greeting"
validate="greeting"
required="true"
default=""
/>
</fieldset>
</form>
Nota que por el momento la clase css es ahora "inputbox validate-greeting" y que el atributo required se establece en true. Esto significa que este campo es obligatorio y tiene que ser verificado por un controlador del validador de formularios del framework de Joomla.
Con tu administrador y editor de archivos favoritos colcoa un archivo en admin/models/forms/helloworld.js que contenga:
admin/models/forms/helloworld.js
jQuery(function() {
document.formvalidator.setHandler('greeting',
function (value) {
regex=/^[^0-9]+$/;
return regex.test(value);
});
});
Se agrega un controlador para el validador de formularios de Joomla para los campos con la clase css "validate-greeting". Cada vez que el campo greeting es modificado, el controlador realizará la verificación de su validez (sin dígitos). El último paso es verificar el formulario cuando el botón guardar es pulsado. Con tu administrador y editor de archivos favoritos, crea un archivo admin/views/helloworld/submitbutton.js que contenga:
Joomla.submitbutton = function(task)
{
if (task == '')
{
return false;
}
else
{
var isValid=true;
var action = task.split('.');
if (action[1] != 'cancel' && action[1] != 'close')
{
var forms = jQuery('form.form-validate');
for (var i = 0; i < forms.length; i++)
{
if (!document.formvalidator.isValid(forms[i]))
{
isValid = false;
break;
}
}
}
if (isValid)
{
Joomla.submitform(task);
return true;
}
else
{
alert(Joomla.JText._('COM_HELLOWORLD_HELLOWORLD_ERROR_UNACCEPTABLE',
'Some values are unacceptable'));
return false;
}
}
}
Esta función se encargará de verificar que todos los formularios que tienen la clase css "form-validate"' son válidos. Ten en cuenta que se mostrará un mensaje de alerta traducido por el framework de Joomla.
La clase HelloWorldViewHelloWorld de la vista tiene que ser modificada para usar estos archivos javascript:
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');
$this->script = $this->get('Script');
// 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()
{
JHtml::_('behavior.framework');
JHtml::_('behavior.formvalidator');
$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');
}
}
Esta vista ahora:
- verifica si el modelo no tiene error;
- agrega dos archivos javascript;
- inyecta la traducción javascript usando la función Joomla JText::script.
You will also notice our two lines adding additional behaviors when injecting our scripts. By default, Joomla injects the Javascript we specify into the page before its own global Javascript libraries, such as jQuery and Joomla Core. As our Javascript code directly utilises the Joomla object, loading it onto the page before the global Javascript libraries will result in immediate failure, and the form validation will not run.
By specifying these two behaviors via the JHtml helper class prior to injecting our own Javascript, we ensure they are loaded first on the page, and our code will execute correctly. You would normally see JHtml used inside a template, but as our Javascript is added for each child template, it's better to specify the external dependency here.
El paso final es implementar una función getScript en el modelo "HelloWorldModelHelloWorld":
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 script that have to be included on the form
*
* @return string Script files
*/
public function getScript()
{
return 'administrator/components/com_helloworld/models/forms/helloworld.js';
}
/**
* 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;
}
}
Verificación del formulario (lado del servidor)
Consulta Formulario de validación del lado del servidor para obtener más información del tutorial relacionada con la verificación del lado del servidor. La verificación del formulario en el lado del servidor se realiza por medio de la herencia de la clase JControllerForm. Hemos especificado en el archivo admin/models/forms/helloworld.xml la función de validación que el servidor utilizará en el archivo greeting.php.
Con tu administrador y editor de archivos favoritos coloca un archivo en admin/models/rules/greeting.php que contenga:
admin/models/rules/greeting.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 Rule class for the Joomla Framework.
*/
class JFormRuleGreeting extends JFormRule
{
/**
* The regular expression.
*
* @access protected
* @var string
* @since 2.5
*/
protected $regex = '^[^0-9]+$';
}
Nota que no hay ninguna función aquí -esto es heredado desde JFormRule (que se encuentra en: libraries/joomla/form/rule.php). Todo lo que se necesita es la cadena con la expresión regular para la contra prueba.
Empaquetado del componente
Contenido de su directorio de código. Cada enlace a un 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.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
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.11</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>