CakePhp | beforeSave and afterSave Callback Methods

Author - Kailash
8.02.2017
|
0 Comments
|

beforeSave(): This function is called automatically before every save or update operation. This function must return true if you want to continue save process. The data for save, if needed in this function, will be in $this->data.

Syntax:

class MyModel extends AppModel {
    public
    function beforeSave() {
        if (isset($this - > data[‘MyModel’]['fieldName'])) {
            //do your work
        }
        return true;
    }
}

b.Example: Trim name value before save.

class User extends AppModel {
    public
    function beforeSave() {
        if (isset($this - > data[‘User’]['name'])) {
            $this - > data[‘User’]['name'] = trim($this - > data[‘User’]['name']);
        }
        return true;
    }
}

afterSave($created): This function is similar to beforeSave() function but this function os called after every save and update model function call. $created argument contains boolean value true if data was successfully saved. The saved data can be accessed with $this->data.

Syntax:

class MyModel extends AppModel {
    public
    function afterSave($created) {
        if ($created) {
            //do your work
        }
    }
}

Example: Set error message variable in model on unsuccessful save.
class User extends AppModel {
    public
    function afterSave($created) {
        if (!$created) {
            $this - > error = 'My error message';
        }
    }
}

Enable or disable callback methods for particular save, update operation.

Syntax:
In controller:

$this - > ModelName - > save($dataArray, array('callbacks' => false));
In Model:
    $this - > save($dataArray, array('callbacks' => false));
Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

Your email address will not be published. Required fields are marked *

Send your message