CakePHP: Date field with default values

Monday, July 23, 2012

print this page
send email


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.

Cakephp code:

echo $form->input('date', array(
'type'  => 'date',
'label' => 'Date',
'empty' => TRUE,
'minYear' => 2000,
'dateFormat' => 'DMY',
'maxYear' => date('Y'),
'minYear' => date('Y') - 10
# default order m/d/y
));

PHP Way out:
$placeholder = '[RandomStringWhichDoesNotAppearInTheMarkup]';
$out = $this->Form->input('date', 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;
Jquery way:
        // var valid=true;

        jQuery(document).ready( function() {

            $("#dateDay option:first").text('DAY');
            $("#dateMonth option:first").text('MONTH');
            $("#dateYear option:first").text('YEAR');


        });






0 comments:

Post a Comment