CakePhp | beforeSave and afterSave Callback Methods

|
| By Webner

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));

Leave a Reply

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