Changing Model Attribute Values In "create Controller"

Hi guys.

Just dived into yii2, decided to start there though it’s in beta and I’m loving it so far.

I have went through the crud generator and everything is working well, though I’m still getting used to the syntax.

But I was wondering if anyone can help me with changing model attribute values after the user hits the "Create" button after punching in data into the form.

The reason I’m trying to do this is because in the form data i have 3 fields regarding numbers.

kiloes_in // User inputs for example 700kg here

kiloes_out // User inputs for example 500kg here

kiloes_total // Then in the controller i would like to calculate 700-500.

I suspect you know what I’m trying to do

Something tells me I should be able to do this here




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

        {

            /* Some logic here perhaps ?*/


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

        } 



Can anyone give me a nudge in the right direction in my “public function actionCreate()” controller ? :)

you can do this after validation in the controller action like this




if($model->validate())

{

// do your calculations here and save your model like the below

   .....

   $model->save(false);

   .....

}



for example




if($model->validate())

{

   $model->c = $model->a - $model->b;

   $model->save(false);

}



don’t forget to send false to save() to prevent validation again.

If the calculation should apply in any case and not the current controller only you may want to put it into the beforeSave() event.