Another use case for beforeSave()

Just another post about the new beforeSave() callback function ;-)

I am sure you have encountered the problem described in the FAQ entry “My Checkbox is not saving to the database record?” when you worked with checkboxes. A solution with beforeSave() allows you to move the corresponding code from the controller to the model because I think the model is the right place for doing such things. Here is the code:

function beforeSave()
  $this->data['Event']['public'] = 
                                isset($this->data['Event']['public']) ? 1 : 0;
  return true;


  1. mememe
    Posted January 21, 2006 at 3:20 am | Permalink

    the model could be a better place than controller, but i think the right place should be the *view* because it’s an issue with the checkbox, not with data type. excuse i don’t know how to solve it, but i think this should be the proper thing…

  2. Posted January 21, 2006 at 1:45 pm | Permalink

    Well, you can solve it with some Javascript and a hidden field. But that has the disadvantage that it does not work when Javascript is disabled.

  3. Ricardo Stuven
    Posted January 23, 2006 at 7:58 am | Permalink

    Add this to your AppModel:

    function setBoolean($field)
    $this->data[$this->name][$field] = isset($this->data[$this->name][$field])?1:0;

    Now your code looks like this:

    function beforeSave()
    return true;


  4. Posted January 23, 2006 at 8:58 am | Permalink

    @Ricardo: thank you for this nice and reusable solution :)

  5. Ricardo Stuven
    Posted January 25, 2006 at 1:56 am | Permalink

    The FAQ is now updated.

  6. andrew
    Posted January 26, 2006 at 5:49 pm | Permalink

    This is a problem with the HtmlHelper class. The checkbox should recieve on and off values (ex. array(‘on’=>1, ‘off’=>0) ). Then an input type=”hidden” with the same name as the checkbox and the default off value should be printed just before the checkbox input.

    If the checkbox is checked the ‘on’ value is returned, if it is not check the hidden value is returned.

  7. Ricardo Stuven
    Posted January 28, 2006 at 10:37 pm | Permalink

    FYI, here is andrew’s ticket:

One Trackback/Pingback

  1. […] Ricardo Stuven’s comment inspired me to completely refactor a function described in an earlier post. So from now on my app model contains two functions: setBoolean and setDate. […]

%d bloggers like this: