문제

I would like in some cases the beforeSave in an Yii Behavior to breaks the save and return an error. What I have tried, and not worked is:

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

    $tested_value = null;

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

And in the Controller:

        $model=new Post;
        if($model->save()){
            // no matter what this is always executed
        } else {
            print_r($model->validationErrors);die;
        }
도움이 되었습니까?

해결책

As documented here: If you override the beforeSave($event) method in a CActiveRecordBehavior, you have to set the isValid property of the $event to false, if you want to prevent saving of the owner model.

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

Also note, that it's $model->errors, not $model->validationErrors.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top