Saving model in afterSave() in cakePHP

17,303

Solution 1

It can be done this way

// Its your model Image.php
function afterSave($created) {
    if($created) {
         // its new record
         // do your work here
    }
}

Little Tweak (not recommended)

If you want to bypass beforeSave on db operations in afterSave() use $this->Model->query() , instead of $this->Model->save();

// little hack to bypass beforeSave
$this->Model->query('UPDATE listings SET name="xx" WHERE id="1"');

Solution 2

If you want to bypass all callbacks (afterSave/beforeSave) in the afterSave() itself, I found this syntax working for me :

$this->save($data, array('callbacks'=>false));

To disable the triggers, the manual states indeed that :

The save method also has an alternate syntax:

save(array $data = null, array $params = array()) $params array can have any of the following available options as keys:

array(
     'validate' => true,
     'fieldList' => array(),
     'callbacks' => true //other possible values are false, 'before', 'after' )
Share:
17,303
Jason
Author by

Jason

Updated on June 04, 2022

Comments

  • Jason
    Jason almost 2 years

    I have a form with a file upload field in it and I have created a model behaviour file to handle file processing.

    I have two functions, beforeSave and afterSave:

    In beforeSave I do some stuff and then set the file value in data to null so it can be saved. Else it will try to save an array, and the database expects just a string (the file name)

    In afterSave I generate a new file name based on some text fields on the form, and add the lastInsertId infront of it. I also move the file from temp to desired location. This all works fine, but when I try to save the new filename to the Model it just doesnt work.

    I have done a lot of test and debugging, and also spent hours searching online. The conclusion is that you can not save in afterSave, it triggers itself and will run beforeSave again.

    So my question is, how can I update the newly inserted model? The filename inserted need to have the primary key in its name, and its unknown at time of beforeSave.

    grateful for any help! jason