Latha
(Lparameshwarappa)
July 10, 2013, 7:36am
1
Hi., i have 40 fields in my db., and i need to check which fields is been updated with new values?
so i have my code in update like
if($model->save())
if ( $model->isChanged(‘id’) )
{
echo $model->id; exit;
}
but getting error:
One and its behaviors do not have a method or closure named "isChanged".
So., before to use isChanged(), i need to add this into behaviour(), what i need to add to use this?? help me…
You have 40 fields in table,which model you are saving,you want to know,which fields are updated of 40,Am I right?
ezekiel
(Ezekiel P Fernandez)
August 24, 2013, 10:10pm
4
there’s no such method as isChanged()right now ActiveRecord just updates it all (unchanged or not)also to determine the changed value you must do it before saving (or if you would copy the older model in some kind of variable)
public $changedAttributes = array();
public $oldModel;
public function beforeSave(){
$this->oldModel= self::model()->findByPk($this->id);
foreach($this->attributes as $attribute){
if($attribute != $olderModel->$attribute)
$this->changedAttributes[] = $attribute
}
return parent::beforeSave();
}
yugenekr
(Yugenekr)
August 25, 2013, 6:03am
5
You may use this behavior (it was initially suggested long ago by somebody else, but I don’t remember who’s the author ):
class TrackChangesBehavior extends CActiveRecordBehavior
{
private $oldAttributes = array();
function afterFind($event)
{
parent::afterFind($event);
$this->oldAttributes = $this->owner->attributes;
}
/**
* Checks if specified attribute has changed
*/
public function getIsAttributeChanged($name)
{
if ($this->owner->getIsNewRecord()) {
return false;
}
return $this->oldAttributes[$name] !== $this->getOwner()->$name;
}
}
[size=2]
[/size]
$old_values = $model->attributes; //store values of model in a variable
$model->attributes = $_POST['model_name']; //new values assign to model
if($model->save()) {
$diff = array_diff_assoc($old_values, $model->attributes);
if(!empty($diff)) {
//model values updated
} else {
//model values not updated
}
}
You can use $model->update() to update values. $model->save() method validates data before saving, but $model->update() method does not validate data.