Question

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;
        }
Était-ce utile?

La solution

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top