When version 1.7 of CodeIgniter was released, they introduced a new form validation class that vastly simplified things. I particularly liked the new way in which any errors that occurred during form validation were displayed on screen.
Where as before, an error message for a field was displayed as follows:
<?=$this->validation->myfield_error?> |
It seemed much neater with the new validation class:
<?=form_error('myfield');?> |
What I found however, was there was no simple way to style a particular field if it it had an error. I wanted a similar method to displaying the error message but which would output the error css class name, if there was an error with the field.
After poking around the new validation code, I discovered that creating such a function would require the extension of two of the base files – the helper form_helper.php would be the place to put the function that I could call from the view and the library form_validation.php would be the place where I could put a function that checks whether a particular field is valid or not.
CodeIgniter provides a way to extend these files easily by placing a file of the same name with the prefix ‘MY_’ inside the appropriate folder in the application directory. So, to create the functionality I wanted, I created a MY_form_helper.php and put the following code into it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); if ( ! function_exists('error_class')) { function error_class($field = '') { if (FALSE === ($OBJ =& _get_validation_object())) { return ''; } return $OBJ->errorclass($field); } } ?> |
Then I created a MY_Form_Validation.php file and placed the following in it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class MY_Form_validation extends CI_Form_validation { function errorclass($field = '') { if ( !isset($this->_field_data[$field]['error']) OR $this->_field_data[$field]['error'] == '') { return ''; } else { return ' invalid'; } } } ?> |
With these two changes, I was then able to set the classes of my field as follows:
<input type="text" name="myfield" value="<?=set_value('myfield');?>" class="<?=error_class('myfield');?>" /> |
This kept the method in line with the set_value and the form_error functions and set the class to ‘invalid’ when an error occurred.
Thank you for this! It saved me a great frustration!
‘class’=>form_error(‘usuario_nombre’)?’invalid’:”
Thank you. I tried that solution, then I note an alternative way:
class=