0
votes

So basically I have been having alot of trouble repopulating my select box during form my form validation check. Below I have put an example of my output, controller, and view. Could someone please help me figure this out. Thank you in advance.

I have multi tag that looks like this:

    <select name="names[]" multiple>
            <option value="1">John Doe</option>
            <option value="2">Michael Scott</option>
            <option value="3">Luke Skywalker</option>
            <option value="4">Princess Arial</option>
    </select>

My Controller validation check:

    $this->form_validation->set_rules('name', 'Name', 'required');
    if ($this->form_validation->run() == FALSE){
        $this->reload_form_view();
    }

My View:

    <select name="names[]" multiple>
            <?php 
                foreach ($users as $user) {
                    $id = intval($user->id, 10);
                    $value = set_value('names[]', $id);
                    $name = $user->full_name;
                    echo '<option value="'.$value.'">'. $name .'</option>';
                }
            ?>
    </select>

When it comes back false I want to repopulate the selected options with options previously selected. I am also populating the select box with users from the database.

Could some please help me on what I am doing wrong, you would help me so much. THANK YOU IN ADVANCE!!!!! :)

2

2 Answers

1
votes

You can give it a try:

foreach ($users as $user) {
    $id     = intval($user->id, 10);
    $value  = set_value('names[]', $id);
    $name   = $user->full_name;
    echo '<option value="'.$id.'" '. set_select("names", $id ) .'>'. $name .'</option>';
}

This is by using the set_select function provided by form helper of CI, you must load the form helper before using it.

0
votes

You can just add a check:

echo '<option value="'.$value.'" '.(in_array($user->id,$this->input->post("names")) ? 'selected':'').'>'. $name .'</option>';

I haven't checked if in_array() works on multiple selects, but its about the idea.