set_select for select tag in codeigniter

How to set value for select tag ,as when i tried for text field

<input type="input" name="name" value="<?php echo set_value('name') ?>"/>

its working but when i tried for select tag

<SELECT class="form-control" name="user" style="width:200px;">
    <option value="">--Select--</option>
    <?php
        foreach ($result as $row):
        echo "<option value='" . $row['id'] . "' >" . $row['employee_name'];
    ?>
    <?php endforeach ?>
</SELECT>

its not working ,when validation run falls its again showing –Select– option

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

try this–> use set_select()

<select id="user" name="user" style="width: 230px; height: 40px;" >
<option value="" selected>--Select--</option>
<?php foreach ($result as $row) { ?>
<option value="<?php echo $row['id'] ; ?>" <?php echo set_select('user', $row['id'], False); ?> ><?php echo $row['employee_name'] ; ?> </option> 
<?php } ?>
</select>

Solution 2

For Codeigniter Dropdown list you should use set_select() instead of set_value() function. You can use like

<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> 

Solution 3

best way is to use form_dropdown method to use these as you are already looping and creating options create option array in controller and pass it to view like

$options = array('--Select--');

foreach ($result as $row){
     $options[$row['id']] = $row['employee_name'];
}

echo form_dropdown('user',$options,set_select('user','default_value'));

if not any select value from dropdown then default value will be used

Solution 4

this might help you.

<SELECT class="form-control" name="user" style="width:200px;">
    <option value="">--Select--</option>
    <?php
        foreach ($result as $row):
        echo "<option value='".$row['id']."' set_select('user', $row['id']);.">". $row['employee_name'];
    ?>
    <?php endforeach ?>
</SELECT>

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply