カレンダー4

カレンダー3で作成したプログラムを少し改造して、前の月、次の月を表示できるようにしよう
カレンダー3のソースの21行目から26行目を改造して、disp_dateという変数を受取り、disp_dateで指定された日付の月カレンダーを表示するようにする。
そして、disp_dateには必ずxxxx/xx/xxという形で年月日が入る事とする。
面倒なのでこの引数のフォーマットチェックを行わないw

//デフォルトは今日を表示
$year = date(‘Y’, $now);
$month= date(‘m’, $now);
$day= date(‘d’, $now);
$smarty->assign( ‘year’, $year );
$smarty->assign( ‘month’, $month );
$smarty->assign( ‘day’, $day );

//表示日付のセット
if( isset($_REQUEST[‘disp_date’]) && strlen($_REQUEST[‘disp_date’]) ){
$tmp = explode( ‘/’, $_REQUEST[‘disp_date’] );
$year = $tmp[0];
$month = $tmp[1];
$day = $tmp[2];
}

//前月リンク
$prev_year = $year;
$prev_month = $month – 1;
if( $prev_month <= 0 ) {
$prev_month = 12;
$prev_year –;
}
$smarty->assign( ‘prev_month’, “{$prev_year}/{$prev_month}/1” );

//翌月リンク
$next_year = $year;
$next_month = $month + 1;
if( $next_month > 12 ){
$next_month -= 12;
$next_year ++;
}
$smarty->assign( ‘next_month’, “{$next_year}/{$next_month}/1” );

$smarty->assign( ‘disp_year’, $year );
$smarty->assign( ‘disp_month’, $month );
$smarty->assign( ‘disp_day’, $day );

追加したソースの中に$_REQUESTという変数があるが、これはPHPの機能でWebサーバと連携して動いた時にPHPが生成する変数だ。
$_POST(POST変数が格納される),$_GET(URL変数が格納される)の内容を統合した変数が$_REQUESTだ。
とりあえず$_REQUESTを使用しておけば、GET,POSTに関わらず取得できる。

HTMLはbodyの中身を下記のように変更すればOKだ

<body>
<div style=”text-align:center;”>
<table border=”1″>
<tr>
<th style=”font-size:12px;” colspan=”2″><a href=”./lesson04.php?disp_date={$prev_month}”>前の月</a></th>
<th style=”font-size:12px;” colspan=”3″>{$disp_year}年{$disp_month}月<br/><a href=”./lesson04.php”>今日</a></th>
<th style=”font-size:12px;” colspan=”2″><a href=”./lesson04.php?disp_date={$next_month}”>次の月</a></th>
</tr>
<tr>
{foreach from=$week item=node}<th style=”background-color:#A0FFA0;padding:3px;”>{$node}</th>{/foreach}

</tr>
{foreach from=$month_date item=weeks}
<tr>
{foreach from=$weeks item=node}<td style=”text-align:center;padding:3px;{if $disp_year == $year && $disp_month == $month && $node==$day}color:white;background-color:blue;{/if}”>{$node}</td>{/foreach}
</tr>
{/foreach}
</table>
</div>
</body>

結果ページはこちら

月の表示を$year,$monthから$disp_year,$disp_monthに変更している。
また、$prev_month,$next_monthにPHPで計算したprev_monht,next_monthをアサインした日付を使用する。
当日判定は$dateのみではなく、年月日の判別に加えている

One comment

Comments are closed.