set_select() helper function is not working set_select() helper function is not working codeigniter codeigniter

set_select() helper function is not working


Before using set_value(), set_select(),set_checkbox(), set_radio(), you have to pass those fields to validation even if not required / validated.


TL;DR

There are only two cases when you use CodeIgnIter set_* form helper functions:

  1. The Form_validation library is not loaded.
  2. Validation object is instantiated (you are using Form_validation library).

In order to use set_* helper functions, you don't have to use Form validation library necessarily, But if you're using the validation library, You MUST set at least a validation rule for that field.

Long Answer (set_* Anatomy)

The following is true for all of the set_* form helper functions. But I'll try to describe how set_select() works:

Syntax: set_select($field = '', $value = '', $default = FALSE)

1. Without using Form validation

When you use set_select() function, CodeIgniter uses the _get_validation_object() function to look for the validation object.

The _get_validation_object() returns either the object or FALSE (if the validation is not loaded yet).

When it returns FALSE, The set_select() function search through $_POST variable to find the specified field name in the array, and in the following by checking function argouments such as $value and $default, it determines whether to return the selected="selected" attribute/value or an empty string ''.

So, it works without using the Form validation library.

2. While using Form validation

But if the validation library is loaded before, the set_select() function will pass the arguments to the Form_validation::set_select() method, and returns the result.

In the Form_validation class, there is a private property called _field_data which is an array containing all the field names/values (those you've set validation rules for them).

Form_validation::set_select() method checks the existence of the field in _field_data array, and returns an empty string on failure.

The _field_data array is populated by validation set_rules() method.

Hence, if you're using the validation library, you have to set at least a validation rule for your field to get set_select() form helper function to work.

That's why you couldn't get it to work.

I hope this answer helps get a good understanding of set_* functions.


Try this:

Modify the set_select function in the form helper from:

if (count($_POST) === 0){    return ' selected="selected"';} 

to

if (count($_POST) === 0){    if ($default)    {        return ' selected="selected"';    }    else    {        return '';    }}