populate dropdown in codeigniter form using set_value

Nishant Jani picture Nishant Jani · Aug 16, 2012 · Viewed 26.8k times · Source

i have a form that uses a drop down and im using codeigniter , form helper and form validation so when i get a validation error in my form , all the correctly entered fields are populated using set_value of codeigniter , however this doesnt work for dropdown

im doing :

<?php echo form_dropdown('mid', $id_map, set_value('mid'), 'id="mid"') ?>

when get error in form , always the first value of dropdown is selected and not previously set

Any ideas , what am i doing wrong?

Answer

TigerTiger picture TigerTiger · Aug 16, 2012

The correct method to use set_select() is

<select name="myselect">
<option value="one" <?php echo set_select('myselect', 'one', TRUE); ?> >One</option>
<option value="two" <?php echo set_select('myselect', 'two'); ?> >Two</option>
<option value="three" <?php echo set_select('myselect', 'three'); ?> >Three</option>
</select>

So Andras Ratz method/answer won't work.

Your method is correct.

<?php echo form_dropdown('mid', $id_map, set_value('mid'), 'id="mid"') ?>

However remember that set_value() is only going to return the value if you have setup a validation rule for it, in your case for mid. You could try as below -

<?php echo form_dropdown('mid', $id_map, (isset($_POST['mid']) ? $_POST['mid'] : ''), 'id="mid"') ?>

or just set a validation rule for mid too