What is the best way to convert CakePHP date picker form data into a PHP DateTime object?

I do 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('Ym-d', $datestring); } 

Absolutely should be the best way to do this - I haven't found a CakePHP way yet ...

What I would like to do:

 function add() { # ... (if we have some submitted data) $mydatefield = $this->data['Mymodel']['mydatefiled']; # obviously doesn't work } 
+3
source share
2 answers

I know this is an old question, but in case someone else is looking for an answer: CakePHP generic Model class has a ::deconstruct() method that is used to internally process this necessary logic. You can use it as follows:

 $stringDate = $this->MyModel->deconstruct('fieldname', $arrayDate) 
+6
source

You can write a helper that takes $this->data['Mymodel']['mydatefiled'] as a parameter, assumes that year / month / day is 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('Ym-d', $datestring); } } ?> 

Or something like that. I think a DateTime object was added in ... PHP 5.2? CakePHP 1.x aims to be compatible with PHP 4, so I don’t think there is a “CakePHP way” for this, at least not for 1.x.

+4
source

All Articles