Hippyjim
Hippyjim

Reputation: 2522

How to prevent save from a behavior in Yii2

I want to add a check before save in several of my Yii2 models.

In Yii1 this was simply a case of adding a behavior that had a beforeSave method, that returned false.

This doesn't work in Yii2. I can register a behavior that is called before save, but returning false from it doesn't prevent that save.

Anyone know how to achieve this without having to duplicate a beforeSave method with identical code in all my models?

namespace app\components\behaviors;

use yii\base\Behavior;
use yii\db\ActiveRecord;

class PreventSaveBehavior extends Behavior
{

    public function events()
    {
        return [
            ActiveRecord::EVENT_BEFORE_INSERT => 'beforeSave',
            ActiveRecord::EVENT_BEFORE_UPDATE => 'beforeSave',
        ];
    }

    public function beforeSave($insert)
    {
        if (SomeClass::shouldWePreventSave()) {
            return false;
        }

        return parent::beforeSave($insert);
    }
}

Upvotes: 0

Views: 1510

Answers (1)

rob006
rob006

Reputation: 22174

In Yii2 in behaviors you need to use isValid property of ModelEvent.

public function beforeSave($event)
{
    if (SomeClass::shouldWePreventSave()) {
        $event->isValid = false;
    }
}

This is explained in event documentation.

Upvotes: 4

Related Questions