1

thanks for all stackoverflow members, I learned a lot from here.

I have a question about "beforeSave", I want save the old data to history-table in the database, for example if the user change anything I want save the old informations in the history-table.

Can anyone tell me what's the "best" scenario to achieve this ?

Thank you all and all suggestions are welcome.

Andy
  • 51
  • 9

2 Answers2

1

You must add the beforSave() function in your model.
Check if the param $insert is false theis mean you are updateing a record so in this case you can create a new HistoryModel, polutate and save

  public function beforeSave($insert)
  {
      if(parent::beforeSave($insert))
      {
          if(! $insert)
          {
              $historyModel = new History();
              $historyModel->att1 = $this->att1;
              $historyModel->att2 = $this->att2;
              ......
              $historyModel->attN = $this->attN;
              $historyModel->save();
              return true;
          }

      }

http://www.yiiframework.com/doc-2.0/yii-db-baseactiverecord.html#beforeSave%28%29-detail

ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
  • @scaiEdge, do I need also a Controller or only a Model? – Andy Sep 04 '17 at 12:57
  • the beforeAction must placed in model becase in defined in activeRecord Class .. The function as describetd in doc http://www.yiiframework.com/doc-2.0/yii-db-baseactiverecord.html#beforeSave()-detail in invoked by EVENT_BEFORE_UPDATE triggered by model->save() ...Normally the model->save() is used in action so using an actionUpdate the function is automaticallt called by the framework .. hope this is clear .. and if my answer is right please mark it as accepted ...see how here http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – ScaisEdge Sep 04 '17 at 16:36
  • don't save in DB the historyModel ? – ScaisEdge Sep 05 '17 at 06:20
  • 1
    you can try using $historyModel->save(false); for disabling validation is the values are save then check for validation rules – ScaisEdge Sep 05 '17 at 06:25
  • thank you so much again :-) it works like a charm :-) – Andy Sep 05 '17 at 06:38
0

For all others who want save only changes to Database here is the code:

  public function afterSave($insert, $changedAttributes) {
    parent::afterSave($insert, $changedAttributes);
    if(!$insert) {
        $historyModel = new History();
        if(isset($changedAttributes['attr1']  )){
            $historyModel->attr1 = $changedAttributes['attr1'];
        }
        ...
        $historyModel->save(false);
    }
}

Now you can save only the changes to database and not all records every time...

Andy
  • 51
  • 9