Adding Form and Field Validations: Difference between revisions

From IHRIS Wiki
No edit summary
No edit summary
 
(3 intermediate revisions by 2 users not shown)
Line 1: Line 1:
<p>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.
When editing a form in iHRIS, iHRIS can perform validations that the data make sense. For example, you can mark a field as being required or unique. You may also have more complicated logic that you want to ensure is in place, for example that the start date of a position does not come after its end date.  This article describes how to add custom validations for forms and fields.
</p><p>Este documento se refiere a iHRIS 4.0.9 y después.
 
</p><p>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.
This document refers to iHRIS 4.0.9 and later.
</p><p>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.   
 
</p>
In some cases you may want to have additional validations on existing forms or fields, or you may need to add validations to new forms or fields you are creatingYou can do this using hooks in the module for your site or the form/field customization module you have created.
<h2> Crear la clase del modulo </h2>
 
<p>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.
You can add a validation to a single field or do the entire form to compare multiple fields. The first step is to create the hooks in the module class.
</p>
 
<h3> Agreggar una Clase de Módulo </h3>
== Create the Module Class ==
<p>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) .
 
</p><p><span class="fck_mw_source" lang="xml">fckLR    &lt;className&gt;iHRIS_Module_$moduleName&lt;/className&gt;fckLR</span>
You create hooks in the class code for your module. This file will be in the classes path (usually ./lib) for your module.
</p><p>You would replace <b>$moduleName</b> with a unique name for your module class.  For example, in the iHRIS Manage Person Position module, the following class is used:
 
</p><p><span class="fck_mw_source" lang="xml">fckLR  &lt;metadata&gt;fckLR    &lt;displayName&gt;iHRIS Manage Person Position&lt;/displayName&gt;fckLR    &lt;className&gt;iHRIS_Module_PersonPosition&lt;/className&gt;fckLR    ...fckLR  &lt;/metadata&gt;fckLR</span>
=== Add a Module Class ===
</p>
 
<h3> Create the PHP Class File </h3>
If your module doesn't currently have a class you will need to add one.  You can add the className node to the metadata in your module (or site) configuration file.
<p>Then in the module classes directory (./lib) you would create the file iHRIS_Module_<b>$moduleName</b>.php, replacing <b>$moduleName</b> with the class name you entered in the configuration file.
 
</p><p><span class="fck_mw_source" lang="bash">fckLRgedit ./lib/iHRIS_Module_$moduleName.phpfckLR</span>
<source lang="xml">
</p><p>You should fill in additional comments, but the default blank file (which we'll fill out later).
    <className>iHRIS_Module_$moduleName</className>
</p><p><span class="fck_mw_source" lang="php">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: &quot;bsd&quot;fckLR# indent-tabs-mode: nilfckLR# c-basic-offset: 4fckLR# End:fckLR</span>
</source>
</p>
 
<h3> Add the getHooks Method </h3>
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:
<p>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 &lt;a href="#Adding_the_Hooks"&gt;Adding the Hooks&lt;/a&gt;.
 
</p><p><span class="fck_mw_source" lang="php">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</span>
<source lang="xml">
</p><p>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.
  <metadata>
</p>
    <displayName>iHRIS Manage Person Position</displayName>
<h2> Adding the Hooks </h2>
    <className>iHRIS_Module_PersonPosition</className>
<p>There are two types of hooks that can be added.  A field validation (for one field) and a form validation (for multiple fields).
    ...
</p>
  </metadata>
<h3> Adding a Field Validation Hook </h3>
</source>
<p>For field hooks, you use the form and field names:  valdate_form_<b>$form</b>_field_<b>$field</b>. You replace <b>$form</b> and <b>$field</b> with the.  For example the iHRIS Common Person Contact module adds a validation hook for the contact email field as:  validate_form_<b>contact</b>_field_<b>email</b>. 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.
 
</p><p>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.
=== Create the PHP Class File ===
</p><p><span class="fck_mw_source" lang="php">fckLR    public static function getHooks() {fckLR        return array(fckLR              'validate_form_$form_field_$field' =&gt; '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</span>
 
</p><p>In this method you will perform any checks necessary and if it fails then you will need to call setInvalidMessage on the $formfieldSee the &lt;a _fcknotitle="true" href="Using Translateable Invalid Messages"&gt;Using Translateable Invalid Messages&lt;/a&gt; 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.
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.
</p><p><span class="fck_mw_source" lang="php">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-&gt;getValue();fckLR        if ( I2CE_Validate::checkString( $value ) fckLR                &amp;&amp;&#160;!I2CE_Validate::checkEmail( $value ) ) { fckLR            $formfield-&gt;setInvalidMessage('invalid_email');fckLR        fckLR    fckLR</span>
 
</p>
<source lang="bash">
<h3> Adding a Form Validation Hook </h3>
gedit ./lib/iHRIS_Module_$moduleName.php
<p>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_<b>$form</b>.  You replace <b>$form</b> with the form name you wish to validate.  For example, the person_position form has a validation hook called:  validate_form_<b>person_position</b>.  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.
</source>
</p><p><span class="fck_mw_source" lang="php">fckLR    public static function getHooks() {fckLR        return array(fckLR              'validate_form_$form' =&gt; '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</span>
 
</p><p>In this method you can check the values of multiple fields and call setInvalidMessage for any fields that don't validate.  See the &lt;a _fcknotitle="true" href="Using Translateable Invalid Messages"&gt;Using Translateable Invalid Messages&lt;/a&gt; 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.
You should fill in additional comments, but the default blank file (which we'll fill out later).
</p><p><span class="fck_mw_source" lang="php">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-&gt;start_date-&gt;isValid() &amp;&amp; $form-&gt;end_date-&gt;isValid() ) {fckLR            if ( $form-&gt;start_date-&gt;compare( $form-&gt;end_date ) &lt; 1 ) {fckLR                $form-&gt;setInvalidMessage('end_date','bad_date');fckLR            }fckLR        }fckLR    }fckLR</span>
 
</p>&lt;a _fcknotitle="true" href="Category:Tutorial"&gt;Tutorial&lt;/a&gt; &lt;a _fcknotitle="true" href="Category:Forms"&gt;Forms&lt;/a&gt; &lt;a _fcknotitle="true" href="Category:Review2013"&gt;Review2013&lt;/a&gt; &lt;a _fcknotitle="true" href="Category:Needs_Intro"&gt;Needs_Intro&lt;/a&gt;
<source lang="php">
/**
* Class iHRIS_Module_$moduleName
*
* @access public
*/
class iHRIS_Module_$moduleName extends I2CE_Module {
 
}
# Local Variables:
# mode: php
# c-default-style: "bsd"
# indent-tabs-mode: nil
# c-basic-offset: 4
# End:
</source>
 
=== 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 [[#Adding the Hooks|Adding the Hooks]].
 
<source lang="php">
class iHRIS_Module_$moduleName extends I2CE_Module {
 
    /**
    * Return the array of hooks available in this module.
    * @return array
    */
    public static function getHooks() {
        return array(
              );
    }
 
}
</source>
 
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 calledIt takes a single form field object as an argument.
 
<source lang="php">
    public static function getHooks() {
        return array(
              'validate_form_$form_field_$field' => 'validate_form_$form_field_$field',
              );
    }
 
    /**
    * Validate the $field in the $form form.
    * @param I2CE_FormField $formfield
    */
    public function validate_form_$form_field_$field( $formfield ) {
    }
</source>
 
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 [[Using Translateable Invalid Messages]] 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.
 
<source lang="php">
     /**
    * Validate the email field for contact forms.
    * @param I2CE_FormField $formfield
    */
    public function validate_form_contact_field_email( $formfield ) {  
        $value = $formfield->getValue();
        if ( I2CE_Validate::checkString( $value )  
                && !I2CE_Validate::checkEmail( $value ) ) {  
            $formfield->setInvalidMessage('invalid_email');
        }   
    }   
</source>
 
=== 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.
 
<source lang="php">
    public static function getHooks() {
        return array(
              'validate_form_$form' => 'validate_form_$form',
              );
    }
 
    /**
    * Validate the $form form.
    * @param I2CE_Form $form
    */
    public function validate_form_$form( $form ) {
    }
</source>
 
In this method you can check the values of multiple fields and call setInvalidMessage for any fields that don't validate.  See the [[Using Translateable Invalid Messages]] 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.
 
<source lang="php">
    /**
    * Checks to make sure the end date is after the start date for the person position.
    * @param I2CE_Form $form
    */
    public function validate_form_person_position( $form ) {
        if ( $form->start_date->isValid() && $form->end_date->isValid() ) {
            if ( $form->start_date->compare( $form->end_date ) < 1 ) {
                $form->setInvalidMessage('end_date','bad_date');
            }
        }
    }
</source>
 
[[Category:Fields]][[Category:Review2013]]

Latest revision as of 11:58, 18 November 2013

When editing a form in iHRIS, iHRIS can perform validations that the data make sense. For example, you can mark a field as being required or unique. You may also have more complicated logic that you want to ensure is in place, for example that the start date of a position does not come after its end date. This article describes how to add custom validations for forms and fields.

This document refers to iHRIS 4.0.9 and later.

In some cases you may want to have additional validations on existing forms or fields, or you may need to add validations to new forms or fields you are creating. You can do this using hooks in the module for your site or the form/field customization module you have created.

You can add a validation to a single field or do the entire form to compare multiple fields. The first step is to create the hooks in the module class.

Create the Module Class

You create hooks in the class code for your module. This file will be in the classes path (usually ./lib) for your module.

Add a Module Class

If your module doesn't currently have a class you will need to add one. You can add the className node to the metadata in your module (or site) configuration file.

<source lang="xml">

   <className>iHRIS_Module_$moduleName</className>

</source>

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:

<source lang="xml">

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

</source>

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.

<source lang="bash"> gedit ./lib/iHRIS_Module_$moduleName.php </source>

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

<source lang="php"> /**

* Class iHRIS_Module_$moduleName
*
* @access public
*/

class iHRIS_Module_$moduleName extends I2CE_Module {

}

  1. Local Variables:
  2. mode: php
  3. c-default-style: "bsd"
  4. indent-tabs-mode: nil
  5. c-basic-offset: 4
  6. End:

</source>

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 Adding the Hooks.

<source lang="php"> class iHRIS_Module_$moduleName extends I2CE_Module {

   /**
    * Return the array of hooks available in this module.
    * @return array
    */
   public static function getHooks() {
       return array(
              );
   }

} </source>

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.

<source lang="php">

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

</source>

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 Using Translateable Invalid Messages 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.

<source lang="php">

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

</source>

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.

<source lang="php">

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

</source>

In this method you can check the values of multiple fields and call setInvalidMessage for any fields that don't validate. See the Using Translateable Invalid Messages 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.

<source lang="php">

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

</source>