Search code examples
codeigniter-3

For drop down. I want to apply validation for update drop down. Everything works fine. Updated value inserted in data base


But when i select drop down value and any error related firstname etc. and on update button it remove selected value and show old value.

<td  align=left>Select Month:<select name=month id="month">
<?php 
$date = $row->birth;    
$stamp = strtotime($date); 
?>
<?php
echo '<option .date("m", $stamp). '.$selected.'>'.date("m", $stamp).'</option>';
?>
<option name=""></option>
<option value='01'>January</option>
<option value='02'>February</option>
<option value='03'>March</option>
<option value='12'>December</option>
</select>
<?php echo form_error('month','<div style="color:red">', '</div>'); ?>
<span class="error"></span>
</td>

Solution

  • You can use codeigniter's set_select function to keep the selection if form validation fails:

    Select Month:<select name=month id="month">
    <option name=""></option>
    <option value='01' <?php echo  set_select('month', '01'); ?>>January</option>
    <option value='02' <?php echo  set_select('month', '02'); ?>>February</option>
    <option value='03' <?php echo  set_select('month', '03'); ?>>March</option>
    <option value='12' <?php echo  set_select('month', '12'); ?>>December</option>
    </select>
    

    See also: https://www.codeigniter.com/userguide3/helpers/form_helper.html#set_select


    If you have a value you'd like to set in the dropdown when the page first loads, you can use the third argument:

    Select Month:<select name=month id="month">
    <?php 
    $date = $row->birth;    
    $stamp = strtotime($date); 
    $month = date("m", $stamp);
    ?>
    <option name=""></option>
    <option value='01' <?php echo  set_select('month', '01', $month == '01'); ?>>January</option>
    <option value='02' <?php echo  set_select('month', '02', $month == '02'); ?>>February</option>
    <option value='03' <?php echo  set_select('month', '03', $month == '03'); ?>>March</option>
    <option value='12' <?php echo  set_select('month', '12', $month == '12'); ?>>December</option>
    </select>