Skip to content

Instantly share code, notes, and snippets.

@fragoulis
Last active August 29, 2015 13:56
Show Gist options
  • Save fragoulis/9113335 to your computer and use it in GitHub Desktop.
Save fragoulis/9113335 to your computer and use it in GitHub Desktop.
Yii behavior that auto detects timestamps and applies custom conversion on their values.
<?php
class MyBehavior extends CActiveRecordBehavior
{
public to='yyyy-MM-dd';
public $from='Y-m-d';
public function beforeSave($event)
{
foreach ($this->owner->tableSchema->columns as $attribute => $column)
{
if (strpos($column->dbType, 'timestamp') === 0)
{
if ($this->owner->$attribute)
$this->owner->$attribute = date($this->from, CDateTimeParser::parse($this->owner->$attribute, $this->to));
}
}
}
public function beforeSave($event)
{
foreach ($this->owner->tableSchema->columns as $attribute => $column)
{
if (strpos($column->dbType, 'timestamp') === 0)
{
if ($this->owner->$attribute)
$this->owner->$attribute = Yii::app()->dateFormatter->format($this->to, $this->owner->$attribute);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment