Two useful functions for your AppModel

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()
{
  $this->setBoolean('active');
  $this->setDate('start');

  return true;
}

5 Comments

  1. Posted January 23, 2006 at 3:31 pm | Permalink

    Hmm this looks very cool (!). I’ve worked around this problem (date’s) by using a function out of the scaffold controller called _cleanUpFields() (see thinkingphp.org) but this is better! Nice job!

  2. Nate
    Posted January 23, 2006 at 5:00 pm | Permalink

    Daniel, this is a great solution to the problem of POST data not returning anything for unchecked checkboxes. Just be careful when using Model::saveField( ), because it will automatically write a 0 (false) value in any checkbox that is not set.

  3. Posted January 23, 2006 at 7:26 pm | Permalink

    gwoo also has a paste in Cakebin on a conversion of all the HTML helper date and time fields to SQL time.

  4. Posted January 24, 2006 at 9:10 am | Permalink

    @Troy: Thanks for the tip. Here is the link: http://cakephp.org/pastes/show/00e37cf0187d6b50ab921776f3ee7b8f

  5. Posted January 24, 2006 at 9:12 am | Permalink

    @Nate: Thanks for the warning. I was not aware of that.


One Trackback/Pingback

  1. […] Important: As it turns out this might not be the most “best practice” solution to working with date fields since this stuff should be better inside of the model. If you care to do things the right way definitly have a look at CakerBaker’s Blog post that deals with that topic and forget about the this step here ; ). […]

%d bloggers like this: