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;
}
7 Comments
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…
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.
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;
}
:-)
@Ricardo: thank you for this nice and reusable solution :)
The FAQ is now updated.
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.
FYI, here is andrew’s ticket:
https://trac.cakephp.org/ticket/329
One Trackback/Pingback
[...] 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. [...]