CakePHP: trouble updating record after overriding beforeSave

I’m using cakephp 1.2 and just spent a whole day figuring this out:

  • Apparently, when you override the beforeSave on one of your models, you can’t update records anymore! So, you define the primary key in the data array, or you do something like $this->id = xpto but neither one works. You either keep creating new records or you get a SQL Error: 1062: Duplicate entry error.

I’m not sure of the program flow after a call to the save function, but I solved this by taking a look at model.php in the lib directory of cake. Calling the model exists() function solves the problem:

...
$this->id = $someId;
$this->exists();
...

This course of action lets me keep my custom beforeSave and update records as normal.

Hope this helps someone :)

Spread the word...
  • Twitter
  • Facebook
  • del.icio.us
  • Google Bookmarks
  • StumbleUpon
  • Digg

Comments 1

  1. pjhile wrote:

    In 1.3 it’s easier to just set/unset the primary key in beforeValidate().

    Hope that saves somebody some time :]

    Posted 27 Jan 2011 at 1:44 AM

Post a Comment

Your email is never published nor shared. Required fields are marked *

-->

Page optimized by WP Minify WordPress Plugin

Miscellaneous is Digg proof thanks to caching by WP Super Cache