Posts Tagged with beforeSave

Displaying 1-3 of 3 results.
Wiki: Yii2 behavior and beforeSave usage example without conflicts and errorswiki
posted by admin on February 22, 2017
Behaviors:

public function behaviors()
{
return [
[
'class' => TimestampBehavior::className(),
'createdAtAttribute' => 'created_dt',
'updatedAtAttribute' => 'updated_dt',
'value' => your datetime format value,//or remove row to default with UNIX TIMESTAMP
],
];
}

BeforeSave:

public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {

if ($this->isNewRecord){
//to do
}else{
//to do
}

return true;
}
return false;
}
Read more
Wiki: Yii2 beforeSave() and afterSave()wiki
posted by admin on February 22, 2017
Wonderful methods beforeSave () and afterSave () in Yii2 help us to solve various problems, for example, you want before saving the database to change the date format, or save the log action. But not everyone knows how to inherit them.

Let's start with a simple afterSave():

public function afterSave($insert, $changedAttributes){
parent::afterSave($insert, $changedAttributes);
//... to do
}

There is nothing complicated, we simply pass to the parent method all the same settings and run it, and then do everything we needed.

Now beforeSave():

public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
//... to do
return true;
}
return false;
}

All the practical as well as with afterSave() method, except that we need to return the result of the parent method, otherwise we when calling $model->save() will get false, and our model will not be saved, nor do we we will receive no errors. Remember this moment.

Yii1 The principle is the same, only the parameters are not transferred there.Read more
Resolved: Yii isNewRecord is false in beforeSave?
posted by admin on April 23, 2016
I made a beforeSave method in my model (extends GXActiveRecord), the if isNewRecord never gets triggered. My beforeSave() gets called, though.

When I print the $this->isNewRecord variable, it's false. When is this variable set to false anyway? I'm very sure it's new

public function beforeSave(){


if(parent::beforeSave())
{
if($this->isNewRecord){
$this->setAttribute('doc_status','new');
print "something";
}else{
$this->setAttribute('doc_status','updated');
}
return true;
} else { return false;

}
Read more