0

In CakePHP if you add created or modified fields to any DB table, then when data is saved or updated it inserts the DATETIME into the fields respectively.

I want to add to this.

I have a function in core.php (app/config/core.php) called isCheap() and can be called anywhere. This function returns either TRUE or FALSE.

I want to extend MODEL so that if any table has an is_cheap TINYINT(1) field it automatically get saved to the value of isCheap().

I looked at the file cake/libs/model/model.php and in the save() function there are many references to created, modified, updated. I am pretty sure this is where it does its magic but the function has a lot going on in it, and I am not sure how I could extend it to add my behavior?

2 Answers 2

3

You shouldn't modify the core. Instead, just add a beforeSave callback to app_model.php in the application. All models inherit from this class.

It would look something like this:

function beforeSave() {
    if(isset($this->_schema['is_cheap'])) {
        // your update here
    }
    return true;
}
Sign up to request clarification or add additional context in comments.

Comments

0

cdburgess's answer is what led me to my fix. For completness I want to add here exactly what I did.

I created the file /app/app_model.php with this as the contents:

class AppModel extends Model 
{
    function beforeSave()
    {
        if(isset($this->_schema['is_cheap'])) {
            $this->data[$this->alias]['is_cheap'] = isCheap() ? 1 : 0;
        }

        return true;
    }
}

I added the ? 1 : 0; becuase I am not sure if the TRUE/FALSE will automatically be converted to integers.

Works great, thanks cdburgess.

1 Comment

Glad to help. I am glad to see that it worked as you would expect too. ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.