Repopulating Select form fields in CodeIgniter Repopulating Select form fields in CodeIgniter codeigniter codeigniter

Repopulating Select form fields in CodeIgniter


You can set the value that should be preselected via the third paramater of form_dropdown. The value that the user selected in the previous step is in $this->input->post('state'). So you would use:

echo form_dropdown('state', $allstates, $this->input->post('state'));

From the user guide:

The first parameter will contain the name of the field, the second parameter will contain an associative array of options, and the third parameter will contain the value you wish to be selected

$options = array(              'small'  => 'Small Shirt',              'med'    => 'Medium Shirt',              'large'   => 'Large Shirt',              'xlarge' => 'Extra Large Shirt',            );$shirts_on_sale = array('small', 'large');echo form_dropdown('shirts', $options, 'large');// Would produce:<select name="shirts"><option value="small">Small Shirt</option><option value="med">Medium Shirt</option><option value="large" selected="selected">Large Shirt</option><option value="xlarge">Extra Large Shirt</option></select>


Sometimes, especially when working with objects, it might be easier to do this without the form helper:

<select name="my_select>    <?php foreach ( $my_object_with_data as $row ): ?>    <option value="" <?php if ( isset( $current_item->title ) AND $row->title == $current_item->title ) { echo 'selected="selected"';} ?> >        <?php echo $row->title; ?>    </option>    <?php endforeach; ?></select>

I know it's very ugly, but in a lot of cases this was the easiest way of doing it when working with objects instead of an associative array.