views:

42

answers:

2

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?

A: 

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>
stef
Oops! Why did'nt I think of that? Just use the function: $this->input->post('name_of_field')) to back the value of field. Much thanks man! Worked perfectly and I like this solution cause it's straightforward and short.
+1  A: 

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.

Yorick Peterse
This kind of code is better in the controller than in the view. This is a good case for using the form helper to create your dropdowns, it's cleaner.
stef
The form helper expects an associative array, an object will cause string conversion errors.
Yorick Peterse