x
 
Create New Page
 View Previous Changes    ( Last updated by vinci )

Form Validation in modules

Recently I needed to use the Codeigniter custom form validation callback function in a custom module using templates.

Unfortunately, while the EE_form_validation extends the CI_form_validation class, it checks the $CI super object for the callback method.

Line 637 of EE_form_validation.php

// Call the function that corresponds to the rule
if ($callback === TRUE)
{
     
if ( ! method_exists($this->CI$rule))
     

          
continue;
     
}
... 

The way I found around the issue is to add your errors to the $this->EE->form_validation->error_array manually.
So first, in your module, physically check for validation of the data, and then add the error message to the error array. eg:

...

if (
$mystuff == false)
{
    $this
->EE->form_validation->_error_array['mystuff''Mystuff is not valid';
}

... 

Then you will need to replace the error message in your template, which would look like:

{exp:stuff:stuff_form}
{form_data}

...

<
input type="text" name="mystuff" value="{mystuff}" />
{if mystuff_error}<class="validationError">{mystuff_error}</p>{/if}

...

{/form_data}
{
/exp:stuff:stuff_form} 

In your stuff_form module method, you need to loop through the error array and add ‘_error’ to the end of the field names being validated, to be replaced in the template with corresponding tags.
In this case, $this->form_data is the multidimensional array of data that includes the form’s default field data.

....


if (
$this->EE->form_validation->run() === FALSE)
{
    
if(isset($this->EE->form_validation->_error_array) && !empty($this->EE->form_validation->_error_array))
    
{
        
foreach($this->EE->form_validation->_error_array as $k => $v)
        
{
             $this
->form_data[$k.'_error'$v;
        
}
    }
}

...

$output $this->EE->TMPL->parse_variables($tagdata, array($this->form_data)); 
return 
$output

The idea is to add $field_name.‘_error’ to your array of variables before parsing it with the template parser.

 

Just one problem that I had, was that sometimes (randomly it appears) EE2’s template parser will not recognize differences in field tags and field_error tags ...

{phone}
{if phone_error}{phone_error}{
/if} 

This produced an exception in the EE Functions class.
The way around this was to look specifically for this field and make an error field with named more different that the original field. I think this has something to do with EE’s template tag replace regex.

...

foreach(
$this->EE->form_validation->_error_array as $k => $v)
{
     
if($k == 'phone')
     
{
          $this
->edit_data['fone_error'$v;
     
}
     
else
     
{
          $this
->edit_data[$k.'_error'$v;
     
}
}
....

and 
in the template:

<
input type="text" name="phone" value="{phone}" />
{if fone_error}<class="validationError">{fone_error}</p>{/if} 

A bit rough but at least it works.

Hope that helps anyone with the same dilemma!