Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How best to convert CakePHP date picker form data to a PHP DateTime object?

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
}
like image 1000
Daren Thomas Avatar asked Jan 18 '26 00:01

Daren Thomas


1 Answers

I know this is an old question, but in case anyone else comes looking for an answer: CakePHP's generic Model class has a method, ::deconstruct(), that is used to handle this necessary logic internally. You can use it like this:

$stringDate = $this->MyModel->deconstruct('fieldname', $arrayDate)
like image 87
mga226 Avatar answered Jan 20 '26 14:01

mga226