1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CakePHP3で年月日選択のプルダウンのoptionをゼロ埋め表示させる

Posted at

はじめに

CakePHP3のFormHelper::date()で年月日を選択させるプルダウンを作ろうとして
月や日をゼロ埋めさせる方法でちょっとはまったのでメモ。

結論

date()に渡すoptionsでmonthやdayのところにleadingZeroValueをtrueで渡せばいけた。

sample.ctp
<?php echo $this->Form->date("dateSelection", [
        'monthNames' => false,
        'year'       => [
                            'start' => 1970,
                            'end'   => 2030,
                        ],
        'month'      => [
                            'leadingZeroValue' => true
                        ],
        'day'        => [
                            'leadingZeroValue' => true
                        ]
    ]); ?>

理由

DateTimeWidget::_generateNumbers()でこの値がtrueなら2桁ゼロ埋めするように書いてあった。

DateTimeWidget.php
    protected function _generateNumbers($start, $end, $options = [])
    {
        $options += [
            'leadingZeroKey' => true,
            'leadingZeroValue' => true,
            'interval' => 1
        ];

        $numbers = [];
        $i = $start;
        while ($i <= $end) {
            $key = (string)$i;
            $value = (string)$i;
            if ($options['leadingZeroKey'] === true) {
                $key = sprintf('%02d', $key);
            }
            if ($options['leadingZeroValue'] === true) {
                $value = sprintf('%02d', $value);
            }
            $numbers[$key] = $value;
            $i += $options['interval'];
        }

        return $numbers;
    }

インターバルとかもセットできるのね。

1
3
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
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?