Updates both model


(Pleasecall911kenneth) #1

When I create something in forms it automatically gets the default date and time from the system and put it on the time_start, I’m trying to do when I update the details it gets the current date and time and save it on time_end but it updates both time_start and time_end


public function actionCreate()

    {

        $model = new Ticket();


        if ($model->load(Yii::$app->request->post()) && $model->save()) {

            return $this->redirect(['view', 'id' => $model->id]);

        } else {

            $model->time_start = date('d-m-y h:i:s');

            return $this->render('create', [

                'model' => $model,

            ]);

        }

    }

The update code gets the time_end


 public function actionUpdate($id)

    {

        $model = $this->findModel($id);


        if ($model->load(Yii::$app->request->post()) && $model->save()) {

            return $this->redirect(['view', 'id' => $model->id]);

        } else {

                $model->time_end = date('y-m-d h:i:s');            

                return $this->render('update', [

                'model' => $model,

            ]); 


        }

    }


(Zabachok) #2

Use Timestamp behavior in your model: http://www.yiiframework.com/doc-2.0/yii-behaviors-timestampbehavior.html


(Shivcharan Panjeta) #3

I think you should use beforeSave function in model.

You can check $insert to find if new record or old

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

// ...custom code here...    return true;}