Home > Coding, PHP > CakePHP created and modified fields

CakePHP created and modified fields

February 8th, 2010

For a project of a client of ours, we had to create a custom web-application. After some online investigation Googling, CakePHP came out as the best-value-for-money PHP framework, and it comes with a super-duper handbook.

After implementing the outlines of the application, we had a first evaluation round which attended us at a small bug (?) in the system…

The “created” and “modified” (or “updated” as alternative) columns in the database scheme should, according to the CakePHP book, be updated automagically when using the built-in model->save() method.

After a few test-rounds we noticed that these values were initialised when first adding the data to the database, but were not updated afterwards when editing the model data.

The traceback lead me to the /cakeframework/cake/libs/model/model.php line 1204:

1204
if ($this->hasField($updateCol) && !in_array($updateCol, $fields)) {

This if checks if a model has access to a database column “created”, “modified” or “updated” with the hasField() model-method and also does a simple in_array() check and here’s the caveat: The second check requires the datetime-field NOT to be in a preset array with the following values “created”, “modified” or “updated”.

Rather tricky to result in both requirements returning “true” and update the datetimefields if available ^^.

So to fix it and have your modified / updated datetime-fields kept up-to-date change the line to the following:

1204
if ($this->hasField($updateCol) && in_array($updateCol, $fields)) {

Hoping to be of any assistance!

Author: Kim Categories: Coding, PHP Tags:
  1. Kim
    March 1st, 2010 at 12:43 | #1

    Update:

    It seems that I had broken the automatic adding of “created” and “modified” fields upon ADDING / CREATING new records…

    The correct practice to get this feature up and running when editing records, is thus checking your edited data-array for a “created” or “modified” field, and unsetting these fields if available. Then do a $this->ModelName->save() and all is well!

    This way CakePHP automagically adds these fields with the correct timestamps..

    Greets! and sorry for the false info ;-)

  1. No trackbacks yet.