Adding Form and Field Validations

From IHRIS Wiki
Revision as of 21:33, 29 September 2013 by Karla Matus (talk | contribs)

Al editar un formulario en iHRIS, este puede realizar validaciones a los datos. Por ejemplo, puede marcar un campo como requerido o único. También puede utilizar una lógica más complicada para verificar que esta establecida correctamente. Por ejemplo, que la fecha de inicio de un puesto no se da despues de la fecha de finalización. Este artículo describe cómo agregar validaciones personalizadas para formularios y campos.

Este documento se refiere a iHRIS 4.0.9 y después.

En algunos casos podría necesitar validaciones adicionales en formularios y campos que ya existen o agregar validaciones a campos y formularios nuevos que ueste creando. Esto puede hacerlo utilizando ganchos en el módulo de su sitio en el módulo de personalización de formularios y campos que ha creado.

Puede agregar una validación a un solo campo o hacer el formulario completo para comparar múltiples campos. El primer paso es crear los ganchos en la clase del módulo.

Crear la clase del modulo

Puede crear ganchos en el código de la clase para su módulo. Este archivo estará en la ruta de la clase (generalmente ./lib) para su módulo.

Agreggar una Clase de Módulo

Si su módulo no tiene una clase, sera necesario agregar una. Puede agregar el nodo className a los archivos de configuración de los metadatos en su módulo (o sitio) .

fckLR <className>iHRIS_Module_$moduleName</className>fckLR

You would replace $moduleName with a unique name for your module class. For example, in the iHRIS Manage Person Position module, the following class is used:

fckLR <metadata>fckLR <displayName>iHRIS Manage Person Position</displayName>fckLR <className>iHRIS_Module_PersonPosition</className>fckLR ...fckLR </metadata>fckLR

Create the PHP Class File

Then in the module classes directory (./lib) you would create the file iHRIS_Module_$moduleName.php, replacing $moduleName with the class name you entered in the configuration file.

fckLRgedit ./lib/iHRIS_Module_$moduleName.phpfckLR

You should fill in additional comments, but the default blank file (which we'll fill out later).

fckLR/**fckLR * Class iHRIS_Module_$moduleNamefckLR *fckLR * @access publicfckLR */fckLRclass iHRIS_Module_$moduleName extends I2CE_Module {fckLRfckLR}fckLR# Local Variables:fckLR# mode: phpfckLR# c-default-style: "bsd"fckLR# indent-tabs-mode: nilfckLR# c-basic-offset: 4fckLR# End:fckLR

Add the getHooks Method

Now we need to define the getHooks method which tells the module factory which hooks this module supports. If your module already had a class then you would only need to add the getHooks method to the existing code. If it already has a getHooks method then skip this step and go to <a href="#Adding_the_Hooks">Adding the Hooks</a>.

fckLRclass iHRIS_Module_$moduleName extends I2CE_Module {fckLRfckLR /**fckLR * Return the array of hooks available in this module.fckLR * @return arrayfckLR */fckLR public static function getHooks() {fckLR return array(fckLR );fckLR }fckLRfckLR}fckLR

This is simply a place holder until we add in the actual hooks we want to define. Those will go in the array that is being returned.

Adding the Hooks

There are two types of hooks that can be added. A field validation (for one field) and a form validation (for multiple fields).

Adding a Field Validation Hook

For field hooks, you use the form and field names: valdate_form_$form_field_$field. You replace $form and $field with the. For example the iHRIS Common Person Contact module adds a validation hook for the contact email field as: validate_form_contact_field_email. Now we add this hook to the getHooks method as an associative array with the value being the method in the module class to be called to validate the field. The method name can be anything, for clarity we will use the same name as the hook.

We will also create this method so it can be called by the module factory when the hook is called. It takes a single form field object as an argument.

fckLR public static function getHooks() {fckLR return array(fckLR 'validate_form_$form_field_$field' => 'validate_form_$form_field_$field',fckLR );fckLR }fckLRfckLR /**fckLR * Validate the $field in the $form form.fckLR * @param I2CE_FormField $formfieldfckLR */fckLR public function validate_form_$form_field_$field( $formfield ) {fckLR }fckLR

In this method you will perform any checks necessary and if it fails then you will need to call setInvalidMessage on the $formfield. See the <a _fcknotitle="true" href="Using Translateable Invalid Messages">Using Translateable Invalid Messages</a> for how to define the messages in a way that allows for multiple translations. This is the example function from the iHRIS Common Person Contact module.

fckLR /** fckLR * Validate the email field for contact forms.fckLR * @param I2CE_FormField $formfieldfckLR */fckLR public function validate_form_contact_field_email( $formfield ) { fckLR $value = $formfield->getValue();fckLR if ( I2CE_Validate::checkString( $value ) fckLR && !I2CE_Validate::checkEmail( $value ) ) { fckLR $formfield->setInvalidMessage('invalid_email');fckLR } fckLR } fckLR

Adding a Form Validation Hook

Adding a validation hook for a form is very similar to adding a validation hook for a field. The hook name will be: validate_form_$form. You replace $form with the form name you wish to validate. For example, the person_position form has a validation hook called: validate_form_person_position. You add this hook to the getHooks method just like for field validation. The method will take a single argument of the form object being validated.

fckLR public static function getHooks() {fckLR return array(fckLR 'validate_form_$form' => 'validate_form_$form',fckLR );fckLR }fckLRfckLR /**fckLR * Validate the $form form.fckLR * @param I2CE_Form $formfckLR */fckLR public function validate_form_$form( $form ) {fckLR }fckLR

In this method you can check the values of multiple fields and call setInvalidMessage for any fields that don't validate. See the <a _fcknotitle="true" href="Using Translateable Invalid Messages">Using Translateable Invalid Messages</a> for how to define the messages in a way that allows for multiple translations. This is an example from the iHRIS Manage Person Position module that validate the person_position form by comparing the start and end dates to make sure the end date is after the start date.

fckLR /**fckLR * Checks to make sure the end date is after the start date for the person position.fckLR * @param I2CE_Form $formfckLR */fckLR public function validate_form_person_position( $form ) {fckLR if ( $form->start_date->isValid() && $form->end_date->isValid() ) {fckLR if ( $form->start_date->compare( $form->end_date ) < 1 ) {fckLR $form->setInvalidMessage('end_date','bad_date');fckLR }fckLR }fckLR }fckLR

<a _fcknotitle="true" href="Category:Tutorial">Tutorial</a> <a _fcknotitle="true" href="Category:Forms">Forms</a> <a _fcknotitle="true" href="Category:Review2013">Review2013</a> <a _fcknotitle="true" href="Category:Needs_Intro">Needs_Intro</a>