add to hatena hatena.comment (3) add to del.icio.us (0) add to livedoor.clip (0) add to Yahoo!Bookmark (0) Total: 3

CakePHP Formヘルパの拡張 その1
日本語日付選択プルダウン

$form->datetimeを拡張して日本語の日付選択プルダウンを生成

CakePHP1.2のFormHelperには日付をプルダウンメニューで選択する機能があります。
生年月日の入力などに重宝しますが、日付の書式が英語なので日本の日付形式に変更する必要があります。

そこで、Formヘルパを拡張してExformヘルパクラスを生成し、独自メソッド内で日本語化対応を実施します。
動作はこちらから確認できます。

準備

Exformヘルパ(exform.php)のソースは最後に記載してあります。
このファイルを
app/views/helpers
に配置。
コントローラーの先頭のヘルパ定義時に、標準のFormヘルパとセットで呼び出します。

PHP:
  1. var $helpers = array('Form','Exform');

実装方法

ビューの中で

PHP:
  1. <?php echo $exform->dateYMD('カラム名', null , array(
  2.     'minYear'=>1900,
  3.     'maxYear'=>date('Y'),
  4.     'separator'=>array(" 年度 "," 月 "," 日 "),
  5. ), true); ?>

といった感じで利用します。
通常のFormヘルパのdatetimeメソッドでは、

PHP:
  1. <?php echo $form->datetime('カラム名', 'YMD', 'NONE', null , array(
  2.     'minYear'=>1900,
  3.     'maxYear'=>date('Y'),
  4.     'separator'=>'-',
  5. ), true); ?>

のように、第2・第3引数に日付と時間のフォーマットが入りますが、
今回の$exform->dateYMDでは利用しない為削除しています。
オプション配列の'separator'に配列で年月日文字列を指定します。

ソースコード(exform.php)

PHP:
  1. class ExformHelper extends FormHelper {
  2.  
  3.     // 日本語YMD形式の日付選択
  4.     function dateYMD($fieldName, $selected = null, $attributes = array(), $showEmpty = true) {
  5.         if(!isset($this->options['month'])){
  6.             $this->options['month'] = array();
  7.             for ($i = 1 ; $i <= 12 ; $i++) {
  8.                 $this->options['month'][sprintf("%02d", $i)] = $i;
  9.             }
  10.         }
  11.         $sep = array("","","");
  12.         if(isset($attributes['separator'])){
  13.             if(is_array($attributes['separator'])){
  14.                 $sep = $attributes['separator'];
  15.                 $attributes['separator'] = "";
  16.             }
  17.         }else{
  18.             $attributes['separator'] = "";
  19.             $sep = array(" 年 "," 月 "," 日 ");
  20.         }
  21.         $ret = parent::dateTime($fieldName, 'YMD', 'NONE', $selected, $attributes, $showEmpty);
  22.        
  23.         $ret = preg_replace('|</select>|', '{/select}'.@$sep[0], $ret, 1);
  24.         $ret = preg_replace('|</select>|', '{/select}'.@$sep[1], $ret, 1);
  25.         $ret = preg_replace('|</select>|', '{/select}'.@$sep[2], $ret, 1);
  26.         $ret = str_replace('{/select}', '</select>', $ret);
  27.         return $ret;
  28.     }
  29. }

関連するその他の記事

Comments

Leave a Reply