views:

380

answers:

1

I'm doing this in app/views/mymodel/add.ctp:

<?php echo $form->input('Mymodel.mydatefield'); ?>

And then, in app/controllers/mymodel_controller.php:

function add() {
    # ... (if we have some submitted data)
    $datestring = $this->data['Mymodel']['mydatefield']['year'] . '-' .
                  $this->data['Mymodel']['mydatefield']['month'] . '-' .
                  $this->data['Mymodel']['mydatefield']['day'];
    $mydatefield = DateTime::createFromFormat('Y-m-d', $datestring);
}

There absolutly has to be a better way to do this - I just haven't found the CakePHP way yet...

What I would like to do is:

function add() {
    # ... (if we have some submitted data)       
    $mydatefield = $this->data['Mymodel']['mydatefiled']; # obviously doesn't work
}
+1  A: 

You could write a Helper that takes in $this->data['Mymodel']['mydatefiled'] as a parameter, assumes that year/month/day are in the array, and parse accordingly:

<?php
/* /app/views/helpers/date.php */
class DateHelper extends AppHelper {
    function ParseDateTime($dateField) {
         $datestring = $dateField['year'] . '-' .$dateField['month'] . '-' . $dateField['day'];
         return DateTime::createFromFormat('Y-m-d', $datestring);
    }
}
?>

Or something like that. I think the DateTime object was added in...PHP 5.2? CakePHP 1.x is targeted at PHP 4 compatibility, so I don't think there's any "CakePHP way" to do it, at least not for 1.x.

mgroves
Wow, thanks. I came to a similar solution myself, by adding it as a method to `AppController`, but the helper is definitely the way to go here.
Daren Thomas
heh, well I'm glad that worked, I didn't actually try the code before I posted :)
mgroves