Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving model in afterSave() in cakePHP

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

like image 715
Jason Avatar asked Nov 30 '22 17:11

Jason


2 Answers

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' )
like image 74
Justin T. Avatar answered Dec 22 '22 15:12

Justin T.


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"');
like image 42
Ish Avatar answered Dec 22 '22 14:12

Ish