Sunday, November 13, 2011

CakePHP saveField() not working (solved)

Today I ran into a situation where CakePHP's method Model::saveField() didn't work.

My Picture model had a field named hidden and I tried to hide some entries using the following code:

$this->Picture->id = $id;
$this->Picture->saveField('hidden', 1);

But it didn't work! I spent almost an hour checking and rewriting my code, reading documentation, googling for similar problems, then checking my code again, etc. The issue occurred very simple and worth a facepalm.

The solution

The thing is that the Picture model had a beforeSave() method implemented. I created it for regular updates, such as when creating or editing the whole entry, and it contained some additional validation and processing (filename checks, thumbnail generation, etc.) I didn't realize it's also called before saveField().

So yeah, if saveField() doesn't do what it's supposed to, make sure that this issue is not caused by the side effects of beforeSave().

1 comment:

  1. Thanks for this post. I had the same the problem, which this resolved.