Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 before save check if attributes are changed

Tags:

php

model

yii2

I want to check if some attributes in my model are changed in beforeSave() method according to data stored in database.

Is there some best practice to check if model has changed?

My goal si to make history. If some attribute changes, I save a copy into model_history table.

like image 692
Aleš Avatar asked Feb 27 '17 21:02

Aleš


2 Answers

You need to check for dirty attributes

You can call yii\db\ActiveRecord::getDirtyAttributes() to get the attributes that are currently dirty.

http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#dirty-attributes

like image 184
Ripper Avatar answered Sep 20 '22 15:09

Ripper


You must be careful,by use dirtyAttributes property because yii, consider the following: before myfield type int =4 after myfield type string = "4" if it happens myfield will be into dirtyAttributes automatically.

Other point: For your dirtyAttributes your fields should be "safeAttributes" in the scenario where you are going to work, in other way this changes will be ignored

regards

like image 45
Tomas Grecio Ramirez Avatar answered Sep 17 '22 15:09

Tomas Grecio Ramirez