PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, March 19, 2022

[FIXED] yii2 calculated 2 value in action create

 March 19, 2022     model-view-controller, php, yii, yii2     No comments   

Issue

This my action create in controller

public function actionCreate()
{
    $model = new User();

    if ($model->load(Yii::$app->request->post()) && $model->save()) {
        return $this->redirect(['view', 'id' => $model->id]);
    } else {
        return $this->render('create', [
            'model' => $model,
        ]);
    }
}

Database:

tb_leave

id
id_employee <fk>
startdate
enddate
duration
leave_type //enum 'annual leave','medical check'

tb_employee
id
name
address
total_leave

The logic is // if "total_leave" >= "duration" && leave_type = "Annual Leave" then total_leave - duration. And the result insert to total_leave in tb_employee.

Can someone help me for this problem?


Solution

Add beforeSave function to tb_leave model class like below and update total_leave value.

/**
 * @inheritdoc
 */
public function beforeSave($insert)
{
    if (parent::beforeSave($insert)) {

        $user = User::find()->where(['id' => this->id_employee])->one();

        if($user->total_leave >= this->duration && this->leave_type = "annual Leave"){
            $user->total_leave = $user->total_leave - this->duration;
            $user->save();
        }

        return true;
    } else {
        return false;
    }
}

this function will trigger every time before saving tb_leave.



Answered By - Irfan Ali
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing