Another use case for beforeSave()

Published on January 20, 2006 and tagged with cakephp  feature  problem  tip

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;
}

8 comments baked

  • mememe January 21, 2006 at 03:20

    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…

  • cakebaker January 21, 2006 at 13:45

    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.

  • Ricardo Stuven January 23, 2006 at 07:58

    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()
    {
      $this->setBoolean('public');
      return true;
    }

    :-)

  • cakebaker January 23, 2006 at 08:58

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

  • cake baker » Two useful functions for your AppModel January 23, 2006 at 11:20

    [...] 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. [...]

  • Ricardo Stuven January 25, 2006 at 01:56

    The FAQ is now updated.

  • andrew January 26, 2006 at 17:49

    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.

  • Ricardo Stuven January 28, 2006 at 22:37

    FYI, here is andrew’s ticket:
    https://trac.cakephp.org/ticket/329

Bake a comment




(for code please use <code>...</code> [no escaping necessary])

© daniel hofstetter. Licensed under a Creative Commons License