Category: CodeIgniter

CodeIgniter – Form Validation and Optional Fields

I’ve been doing a bit of work lately with CodeIgniter.  It’s been OK but the framework seems quite wrong in most places.  My main gripe is that the “helpers” define themselves as functions in the global namespace (rather than as objects that hook into the CodeIgniter object) which results in some stupidity like a function called “set_value” which just happens to retrieve the value as validated by the form validation “helper”.  Anyway, that’s a lesson learnt.

I’ve been trying to get the form validation to allow me to use set_value for fields that aren’t required, but unless your rules specify the field and a validation rule for it the value won’t be available when set_value is called.  The trick here is to use “echo” as the rule which means that the validation passes and you get back what you put in.  This is not documented in the CodeIgniter manual (it’s implied by the fact that you can use any PHP function as a “rule”).

Example:

$rules = array(
  array(
    'field' => 'name',
    'label' => 'Name',
    'rules' => 'required'
  ),
  array(
    'field' => 'nickname',
    'label' => 'Nickname',
    'rules' => 'echo'
  )
);
 
$this->form_validation->set_rules( $rules );

In this case any calls to set_value(‘nickname’) will return the correct value, rather than an empty string.

WordPress Themes