Validating form dropdown in CodeIgniter Validating form dropdown in CodeIgniter codeigniter codeigniter

Validating form dropdown in CodeIgniter


Are you doing this in a view? I'll show you have I handle this, but it all happens in a controller:

// first, we can set a validation rule for the input 'country' (our dropdown), in this case it is required, and must be a natural number. You can look up more rules in the CI user guide, and you can write your own functions as well and add them to the 3rd parameter here. I believe some native PHP functions can be used as well.$this->form_validation->set_rules('country', 'Country', 'required|is_natural');// the form is not valid! we'll enter this block whenever the form validation rules above are not met, as well as when first going to this controller-action.if ($this->form_validation->run() == FALSE) {    // buid your form, there's some CI functions to help with this that I'm using    $my_form = form_open('user/edit', 'class="superform"')        . form_fieldset()        . '<ol>'        . '<li>'        . form_label('Country<br/>', 'country')        // so here is the dropdown, matching the name given to the validation rule we've set, the second parameter takes an array, which I am grabbing from a model, the last parameter is the 'selected; value, which I am grabbing from some variable, if it's not present the first item in the dropdown will obviously be selected        . form_dropdown('country', $this->Country_model->get_countries_dropdown(), $user->country) . form_error('country', ' <em>', '</em>'        . form_submit('mysubmit', 'Save', 'class="button"')        . '</li>'        . '</ol>'        . form_fieldset_close()        . form_close()    );    // sending the form variable to my view, where i will simply <?=$my_form?> it    $this->load->view('user_edit', $my_form);} else {    // form has validated! do something!}

The form_dropdown() function takes an array that is setup like: $key => $valueWhere the key in my case is a country id, and the value is the countries name. I have the pair '0' => 'NONE' at the start of my country array, so the user cannot choose one. If i wanted to make this required like your situation, I could set it to '-1' => 'Please select...' and it would not validate, as -1 is not a natural number.

Hope my rambling helps!

Edit:

Okay, so before you create the dropdown with form_dropdown(), what you'll want to do is check for a selected value from coming from the POST array.

In the case of CI, you can use the function set_value($input), so in my example form I might do something like:

$selected = (!empty(set_value('country'))) ? set_value($country) : '';form_dropdown('country', $this->Country_model->get_countries_dropdown(), $selected)

So now the selected value of the dropdown will be set to what was selected on the last post. You might want to check that value to make sure it's valid. If nothing was selected, then you could set $selected as something like the value currently in the database, or a default value you've chosen.


In you line:

echo form_dropdown('events', $options, '', $firstItem);

Just make it:

echo form_dropdown('events', $options, set_value('events'), $firstItem);


Personally, I REALLY like building my form in the view rather than mixing the presentation into the controller. But that's just my opinion. I understand having to pre-load data if it's a large list but I don't think you really need to build the entire form just for a drop down list. I had the same issue and actually did a little doc digging to figure out a good solution.

To Validate the Selection Choices
All I did for that was provide a custom method in the controller class that looks something like this

function select_validate($selectValue){    // 'none' is the first option and the text says something like "-Choose one-"    if($selectValue == 'none')    {        $this->form_validation->set_message('select_validate', 'Please pick one.');        return false;    }    else // user picked something    {        return true;    }}

In your index() (or whichever method is processing the data and loading the view) you set your validation code for the drop down.

$this->form_validation->set_rules('select', 'Select', 'callback_select_validate');

It's imperative that you prefix your custom function with "callback_".

Maintaining User SelectionRetaining the selection choices is super simple too if you use what CI gives you. You just need to use the set_select() function for each option in the selection list.

So let's say you have a drop down with two options to make it easy. This is all you do.

<select name="select">    <option value="none" <?php echo set_select('select', 'none', true);?> >- Select One -</option>    <option value="one" <?php echo set_select('select', 'one');?> >Option one</option>    <option value="two" <?php echo set_select('select', 'two');?> >Option two</option></select>

What's nice about using this function is that it pre-selects the first "dummy" option and then if the user makes a selection but fails other validations, the selection will be retained and pre-selected after the form is posted and prompts the user to correct the other errors.

Again, this may not satisfy everyone but it's a pretty straight forward solution for drop down validation with CodeIgniter.