Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP: Date field with default values

Tags:

php

cakephp

I'm using CakePHP 2.1 and have a date field to get a users date of birth:

e.g.

echo $this->Form->input('Profile.dob', array('label' => 'Date of Birth'
                                        , 'dateFormat' => 'DMY'
                                        , 'empty' => array('DATE','MONTH','YEAR')
                                        , 'minYear' => date('Y') - 110
                                        , 'maxYear' => date('Y') - 0));

As you can see I have tried to set the default values using an array, however it just makes them all have a default value of DATE. How do I get it so that each of the dropdowns has the correct value?

like image 491
Cameron Avatar asked Nov 16 '25 20:11

Cameron


1 Answers

It's a bit of a hack and quite ugly, but since the empty option doesn't appear to support multiple values it's probably the easiest solution - unless you want to rewrite the whole dateTime() function. str_replace unfortunately doesn't allow limiting the number of replacements, which is why we have to resort to preg_replace.

$placeholder = '[RandomStringWhichDoesNotAppearInTheMarkup]';

$out = $this->Form->input('Profile.dob', array('label' => 'Date of Birth'
                                            , 'dateFormat' => 'DMY'
                                            , 'empty' => $placeholder
                                            , 'minYear' => date('Y') - 110
                                            , 'maxYear' => date('Y') - 0));

$escapedPlaceholder = preg_quote($placeholder, '/');
$out = preg_replace("/$escapedPlaceholder/", 'DATE', $out, 1);
$out = preg_replace("/$escapedPlaceholder/", 'MONTH', $out, 1);
$out = preg_replace("/$escapedPlaceholder/", 'YEAR', $out, 1);

echo $out;
like image 193
mogelbrod Avatar answered Nov 19 '25 09:11

mogelbrod