LoginSignup
8
4

More than 5 years have passed since last update.

Cakephp3のFormHelperで年月日の入力フィールドを出力するときの便利なオプション

Last updated at Posted at 2016-08-03

例は誕生日

  • 年・月・日のselectタグにそれぞれにcssのclassをあて
  • 月をJanuaryとかじゃなくて数字で出し
  • 表示フォーマットをx年x月x日って後ろに漢字を混ぜ
  • 空っぽのところは「ー」って文字を出し、valueには空や数字ではなくで何かの文字を入れておく(空にしとくと0ってだされるので、年が00が選ばれて変になる)
  • 年の最初と最後の範囲を指定し
  • エラーがあった時は、cakeデフォルトのエラーcssを当てるために、form-errorっていうのが当たろうとするんだけど、年月日それぞれにclassをオプションで指定してしまっているので、form-errorが自動的に各フィールドに当てはまらない。だから、$append_classを書き足すようにしている。
src/Templates/Pages/date-form.ctp
<?php if ($this->Form->isFieldError('birthday')){
    $append_class = " form-error ";
}
?>
<?php
$this->Form->templates([
    'dateWidget' => '{{year}} 年 {{month}} 月 {{day}} 日 ',
]);
$attr = [
    "required"=>false,
    'monthNames'=>false,
    'empty' => ['-' => 'ー'],
    'year' => [
        'start' => 1960,
        'end' => 1998,
        'order' => 'desc',
        'class' => "select-year $append_class",
    ],
    'month' => ['class' => "select-month $append_class"],
    'day' => ['class' => "select-day $append_class"]
];
?>
<?= $this->Form->date('birthday',$attr);?>

ここに色々書いてあるけど、
http://book.cakephp.org/3.0/en/views/helpers/form.html#datetime-options

FormHelper.phpが表示されようとしている直前return $this->widget('datetime', $options);で、debug($options);って出力して出したのを頼りにやるほうが、ドキュメントを読むより楽かも。

vendor/cakephp/cakephp/src/View/Helper/FormHelper.php

public function date($fieldName, array $options = [])
{
    $options += [
        'empty' => true,
        'value' => null,
        'monthNames' => true,
        'minYear' => null,
        'maxYear' => null,
        'orderYear' => 'desc',
    ];
    $options['hour'] = $options['minute'] = false;
    $options['meridian'] = $options['second'] = false;

    $options = $this->_initInputField($fieldName, $options);
    $options = $this->_datetimeOptions($options);
        debug($options);
    return $this->widget('datetime', $options);
}


8
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
4