dtechplus
dtechplus

Reputation: 599

Repopulating Select form fields in CodeIgniter

I want to re-populate (i.e refill) values posted from a select form field after validation. I know codeigniter user guide proposed using set_select() function but their example from the guide assume you've hard-coded (in HTML) the array of values for the 'select' form element. In my case I used the Form Helper and my select field values are pulled from an array() like so:


$allstates = array('blah','blah2','blah3','blah4','blah5');
echo form_label('Select State Affiliate', 'state'); 
echo form_dropdown('state', $allstates);

Needless to say, $allstates array is dynamic and changes over time. So how do I code such that my select field can be re-populated with the value the user selected?

Upvotes: 2

Views: 8058

Answers (2)

user290102
user290102

Reputation:

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.

Upvotes: 2

stef
stef

Reputation: 27749

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>

Upvotes: 5

Related Questions