Tuesday, October 23, 2012

$model->data state in ModelBehavior ::beforeSave() and ::afterSave()

I am writing a behavior which checks a field for duplicates in beforeSave() and updates the created row in afterSave().

I am wondering what happens to $model->data array if I modify it directly or I use $model->find() or $model->save() while in the callback.

Do other behaviors and callbacks also receive the same data array?
Am I responsible to leave it as-is after I finish modifying the data? 
Do I have to make another instance of the model and do finds and saves with that instance?

<?php 
function beforeSave(Model $model){
$value = $model->data[$model->alias]['unique_field'];
$duplicates = $model->find('all', array(
'conditions' => array('unique_field', $value)
));
if ($duplicates) { /* ... */ }
//what happens to $model->data here?
}

function afterSave(Model $model, $created){
$value = $model->data[$model->alias]['unique_field'];
$model->data[$model->alias]['unique_field'] = strrev($value); //for demonstration purposes
$model->save($model->data, array('callbacks'=>false));
//what happens to $model->data here?
}

Thanks for the input!

P.S. I have to update in afterSave because the unique field depends on the id, and has a temp value before the id is available.

--
Like Us on FaceBook https://www.facebook.com/CakePHP
Find us on Twitter http://twitter.com/CakePHP
 
---
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To post to this group, send email to cake-php@googlegroups.com.
To unsubscribe from this group, send email to cake-php+unsubscribe@googlegroups.com.
Visit this group at http://groups.google.com/group/cake-php?hl=en.
 
 

No comments: