开发者

Repopulating Select form fields in CodeIgniter

开发者 https://www.devze.com 2023-01-06 08:36 出处:网络
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 y

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:


$a开发者_运维百科llstates = 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消