Nice trick to toggle your Model field in CakePHP

This little trick will allow you toggle any field, for example ‘status’ which can be either 0 or 1…

Add this little function to your model or better yet, app model:

Update 1: Thanks to Kalt for the sound improvement to the original method
Update 2: And thanks to rafaelbandeira3 for improving it even further

function toggleField($field, $id=null) {
   if(empty($id)) {
      $id = $this->id;
   }

   $field = $this->escapeField($field);
   return $this->updateAll(array($field => '1 -' . $field),
                             array($this->escapeField()  => $id)
                           );
}

(Daniel Hofstetter pointed out that instead of ‘1-‘ you could use the ‘NOT’ operator)

Now in your controller you could do:

$this->User->toggleField('status', $id);

Of course, we assume that we are dealing with only 0 or 1 as status types.

%d bloggers like this: