如何让 Yii 之前保存破坏保存


How to make Yii beforeSave breaks the save

我希望在某些情况下,之前在 Yii 行为中保存会破坏保存并返回错误。我尝试过但没有奏效的是:

public function beforeSave($event) {
    parent::beforeSave($event);
    $tested_value = null;
    if(is_null($tested_value)){
        $this->validationErrors = Yii::t('app', 'Ops!  Error');
        return false;
    }
}

在控制器中:

        $model=new Post;
        if($model->save()){
            // no matter what this is always executed
        } else {
            print_r($model->validationErrors);die;
        }

如下所述: 如果在 CActiveRecordBehavior 中重写 beforeSave($event) 方法,如果要阻止保存所有者模型,则必须将$eventisValid 属性设置为 false。

if($preventSave) {
    $event->isValid = false;
}

另请注意,它是$model->errors,而不是$model->validationErrors