Last active
August 29, 2015 14:09
-
-
Save newtonwagner/2e9dff0fc4fb574f09e6 to your computer and use it in GitHub Desktop.
Adapting Yii 1.x models to allow change validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class SomeModel extends GxActiveRecord | |
{ | |
/** | |
* @var $oldAttributes Holds the state of the object afterFind() until afterSave() | |
*/ | |
protected $oldAttributes; | |
/** | |
* Yii hook after filling the model | |
*/ | |
public function afterFind() | |
{ | |
$this->oldAttributes = $this->attributes; | |
return parent::afterFind(); | |
} | |
/** | |
* Yii hook after saving (create or update) the model | |
*/ | |
public function afterSave() | |
{ | |
$this->oldAttributes = $this->attributes; | |
return parent::afterSave(); | |
} | |
/** | |
* Example on how to use the $oldAttributes to check for | |
* changes in the model beforeSave(). | |
* You should do this on Yii using rules() and creating a validation | |
* method, but to keep things short and easily to understand... | |
* | |
* @return boolean | |
*/ | |
public function beforeSave() | |
{ | |
// first check if it is not a new record | |
if (!$this->isNewRecord) { | |
// check if 'created_date' attribute has changed | |
if ($this->oldAttributes['created_date'] != $this->created_date) { | |
$this->addError('created_date', "You can't change the created date!"); | |
} | |
} | |
return $this->hasErrors(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment