read populates $model->data

2 November, 2007

Show comments

For the past couple of days, I've had this niggling doubt that I've been missing something. Some code that I had in a behavior, which was supposed to be triggering a save for two field values, further down the line kept turning into a save which included every field in the table with the old field values. Why was this happening? I asked Elvis, he didn't know so I had to suck it up and find out.

At first I thought it would be a simple coding error, so I looked around and found a Nice article on the Set class by Mariano which looked like it could have been related - only the code I had wasn't using the Set class anywhere. I did a bit of debugging but couldn't see what was happening in the debug stack to cause the magical appearance of the stale data. Skip on a couple of days and a dirty workaround later, and I came across the answer. In a bit of code posted in a comment for a previous post was the following little pearl:

read populates $model->data which then screws up the save, so just don't use it!


How very interesting, didn't know that. So after a quick confirmatory check on the read method in the api later (read has acted in this way since revision 4476 , 9 months ago - I didn't get the memo!), the hunt for read began.

So it transpires that in the beforeSave method was a call to read to get the current model data to do a comparison, which was also overwriting the model data with the model's previous data, which was then bypassing the (if-field-x-isn't-present) check, triggering a save with stale data and causing all sorts of problems. However: Hurrah - source of problem identified.

Wrapping Up

The model method read populates the model variable data - Lesson learned and I'll now make use of this piece on knowledge to further my abilities to write less and do more. So what's the moral of the story? Don't take anything for granted, nothing happens without a reason, and if what's happening isn't what you want, it could well turn out it is exactly what you asked for. In which case, ensure you ask the right questions (in this case use find), and you'll get the answer you expect ;)

Bake on!