When I save data in one model, I'd like to create some data in another model and save that too. Because I can't do this using beforeSave(), I eventually decided to use afterSave() to create new data items in my second model. I'm not writing a blog application, but to use the blog analogy it's equivalent to automatically creating a series of comments for every blog post that is added and, when a post is edited, deleting all comments and re-adding new comments:
class Post extends AppModel {
function afterSave() {
ClassRegistry::init('Comments')->deleteAll(array('Post.id' => $this->id));
ClassRegistry::init('Comments')->saveAll($comments); // comments contains the comments to be added
}
}
This works fine, apart from the fact that the afterSave() function causes the redirection from my controller's add/edit actions (to /posts/index
) to be overruled, and I get redirected back to the add/edit form instead (if I comment out the entire afterSave() method, the redirection works as intended).
If you're wondering why I didn't put the logic in the controller, I did originally, but I want it to work for both add and edit actions, and also for a "batch" add action I use to add multiple "posts" at once.
I guess I have two questions:
Is there a better way to achieve this kind of result?
How can I make the redirection work?
Thanks for reading this far and if I haven't explained it clearly I hope you can use your imagination to see what I'm trying to do.