Two useful functions for your AppModel

Published on and tagged with cakephp  programming  tip

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.

First, Ricardo’s setBoolean function:

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

Second, my setDate function:

function setDate($field, $format = 'Y-m-d H:i')
  $model = $this->name;
  $fieldAddOns = array('min', 'hour', 'day', 'month', 'year');
  $dateInfo = array();
  foreach ($fieldAddOns as $fieldAddOn)
    $dateInfo[$fieldAddOn] = 
                isset($this->data[$model][$field . '_' . $fieldAddOn]) ? 
                intval($this->data[$model][$field . '_' . $fieldAddOn]) : null;
  $this->data[$model][$field] = 
                date($format, mktime($dateInfo['hour'], $dateInfo['min'], 
                null, $dateInfo['month'], 
                $dateInfo['day'], $dateInfo['year']));

If you want to use these functions, you have to copy them to your app/app_model.php. Copy cake/app_model.php, if app/app_model.php does not exist. After that you can use these functions in your models as shown in this example:

function beforeSave()

  return true;

8 comments baked

© daniel hofstetter. Licensed under a Creative Commons License