phpobjectyii2before-save

how to get data from before beforeSave()


In my system, I want a facility that it should always copy old record into another table before the actual table gets an update.

So that admin can see new data and old data as well ( to maintain a record of old and new values)

for that i use beforeSave() method

public function beforeSave($insert)
    {
        if (!parent::beforeSave($insert)) {
            return false;
        }

        echo "<pre>before save";print_R($this);die();
        return true;
    }

in update case, I noticed that $this returns both the old and new records

$this contains :

 app\models\Visitor Object (
     [_attributes:yii\db\BaseActiveRecord:private] => Array
         (
             [id] => 1
             [first_name] => new first name
             [last_name] => new last name
             [phone] => 987654321
             [created_at] => 0000-00-00 00:00:00
             [updated_at] => 0000-00-00 00:00:00
         )

     [_oldAttributes:yii\db\BaseActiveRecord:private] => Array
         (
             [id] => 1
             [first_name] => old first name
             [last_name] => old last name
             [phone] => 123456789
             [created_at] => 0000-00-00 00:00:00
             [updated_at] => 0000-00-00 00:00:00
         )

     [_related:yii\db\BaseActiveRecord:private] => Array
         (
         )

if i use $this->first_name it return me new value(new first name). but how dI i get access to the old data(old first name) so that i can save it to another table before the update.

Or any other suggestion achieving this is helpful.


Solution

  • You can use method $this->getOldAttribute($name), where name is the name of attribute you want to get value.

    There is also method $this->getOldAttributes(), which return array with the old attribute values (name-value pairs).