beforeSave() example

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

2 Comments

  1. mememe
    Posted January 19, 2006 at 8:00 pm | Permalink

    what it means “resp. model_php4.php”?
    thanks!

  2. Posted January 20, 2006 at 10:02 am | Permalink

    It means “respectively model_php4.php”. It means you have to change model_php4.php or model_php5.php, depending on your PHP version. Btw: The bug is already fixed in trunk.


%d bloggers like this: