Feb10th

CakePHP - saving dates in your model

Learning continues! Today I learned about Controller::cleanUpFields().

If you’ve used CakePHP’s scaffolding and are ready to create your own views you might run into a problem saving dates into your database.

Here’s the scenario:
You have a table with a datetime field in it. In your view you have a form that saves a date and the date field is create with the HTMLHelper:
$html->dateTimeOptionTag();

In your controller you have a simple Model::save() call to save your new record but low and behold your date is set to NULL.

Apparently CakePHP does not do a great job of automatically taking the selections that are created by dateTimeOptionTag() and converting them into a datetime string for the database.

Instead, before you call Model::save() you need to call Controller::cleanUpFields(); it will do some magic and give you a date string that the database likes.