开发者

Make php date dropdown function 'sticky'

Out of coffee and brain's given up... ...can anyone 开发者_开发问答help to make this form date dropdown function retain selected month on $_POST ['submit'] or isset($missing) in the case of there being an error/missing field etc

 function createMonths($id='month_select', $selected=null)
{
    /*** array of months ***/
    $months = array(
            1=>'Jan',
            2=>'Feb',
            3=>'Mar',
            4=>'Apr',
            5=>'May',
            6=>'Jun',
            7=>'Jul',
            8=>'Aug',
            9=>'Sep',
            10=>'Oct',
            11=>'Nov',
            12=>'Dec');

    /*** current month ***/
    $selected = is_null($selected) ? date('m') : $selected;

    $select = '<select name="'.$id.'" id="'.$id.'">'."\n";
    foreach($months as $key=>$mon)
    {
        $select .= '<option value="'.str_pad($key, 2, "0", STR_PAD_LEFT).'"';
        $select .= ($key==$selected) ? ' selected="selected"' : '';
        $select .= ">$mon</option>\n";


    }
    $select .= '</select>';
    return $select;
}


In the event you have invalid form data, you should check if the $_POST['month_select'] variable is set and not empty and create your dropdown passing in it's value like so:

$selected = (!empty($_POST['month_select'])) ? $_POST['month_select'] : null;
createMonths('month_select', $selected);

function createMonths($id='month_select', $selected = null)
{
    /*** array of months ***/
    $months = array(
            '01'=>'Jan',
            '02'=>'Feb',
            '03'=>'Mar',
            '04'=>'Apr',
            '05'=>'May',
            '06'=>'Jun',
            '07'=>'Jul',
            '08'=>'Aug',
            '09'=>'Sep',
            '10'=>'Oct',
            '11'=>'Nov',
            '12'=>'Dec');

    /*** current month ***/
    $selected = is_null($selected) ? date('n') : $selected;

    $select = '<select name="'.$id.'" id="'.$id.'">'."\n";
    $select .= "<option value=""></option>\n";
    foreach($months as $key => $mon)
    {
        $select .= '<option value="'.$key.'"';
        $select .= ($key == $selected) ? ' selected="selected"' : '';
        $select .= ">$mon</option>\n";
    }
    $select .= '</select>';
    return $select;
}

I have also taken the liberty of fixing your createMonths() function by the recommendation regarding date('n') and changing your array keys to strings as this will avoid having to pad your months.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜