beforeSave() example

Published on and tagged with cakephp  feature  programming  tip

I wrote already about the new model callback functions like beforeSave() and afterSave(). At that time I wondered what the use cases of these callbacks would be. Now I saw an opportunity for using the beforeSave() callback for storing datetime information.

Ok, let’s start with the view. Here is the code that is relevant for the example:

$html->dayOptionTag('Event/start');
$html->monthOptionTag('Event/start');
$html->yearOptionTag('Event/start');
$html->hourOptionTag('Event/start');
$html->minuteOptionTag('Event/start');

In the controller we do:

$this->Event->save($this->params['data']);

In the model we write our beforeSave() callback function. The code is simple. You can move the _getDate() function to AppModel if you want to reuse its functionality.

class Event extends AppModel
{
  function beforeSave()
  {
    $this->data['Event']['start'] = $this->_getDate('Event', 'start');

    return true;
  }
		
  function _getDate($model, $field)
  {
    return date('Y-m-d H:i:s', mktime(
                    intval($this->data[$model][$field . '_hour']), 
                    intval($this->data[$model][$field . '_min']), 
                    null,
                    intval($this->data[$model][$field . '_month']), 
                    intval($this->data[$model][$field . '_day']),
                    intval($this->data[$model][$field . '_year'])));
  }
}

So, everything is done? Yes, but wait. Our example will not work due to a bug in CakePHP. Well, you can fix it (or wait until the bug get officially fixed). You have to add one line (and a closing bracket, don’t forget!) to the save() function of /cake/libs/model/model_php5.php (resp. model_php4.php). Disclaimer: use this fix on your own risk ;-)

if ($data)
{
  $this->set($data);
}

if($this->beforeSave()){  <- add this line

4 comments baked

Bake a comment




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

© daniel hofstetter. Licensed under a Creative Commons License