Fadly Dzil
Fadly Dzil

Reputation: 2206

beforeSave is same on update action in Yii2

Why yii2 identify actionUpdate is same actionCreate. Why I said like that : This is the case

I have a lot of field such as name, created_by with a special field in db that I want to auto_increment (but not primary key). the field is named nomor_surat (In english : letter_number)

So, if a new record that would be insert, no_surat will be 1,2,3,4, so on so on. Then I decide to create action beforeSave() like this :

public function beforeSave($insert) {
    parent::beforeSave($insert);

    $nomor = Request::find()->select('max(nomor_surat) as max')->scalar();
    $this->nomor_surat = $nomor + 1;

    return parent::beforeSave($insert);
}

In actionCreate, its success. Let say no_surat=1

But, f I update no_surat_1, let say I want to name in this record, the no_suart is change=2

Please Advise.

Upvotes: 4

Views: 3411

Answers (1)

Bizley
Bizley

Reputation: 18021

$insert variable is actually telling you if this is create or update action. This is boolean and it's true if model is being inserted and false if model is being updated.

And you use wrong logic in your example. It should be:

public function beforeSave($insert)
{
    if (parent::beforeSave($insert)) {
        if ($insert) { // only on insert
            $nomor = Request::find()->select('max(nomor_surat) as max')->scalar();
            $this->nomor_surat = $nomor + 1;
        }
        return true;
    }
    return false;
}

Upvotes: 6

Related Questions