2

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;
        }
tereško
  • 58,060
  • 25
  • 98
  • 150
Constantin.FF
  • 687
  • 1
  • 10
  • 23
  • is validationErrors variable declare in model class? like public $validationErrors – naveen goyal Oct 17 '13 at 07:15
  • Yii validates all inputs with rules you shouldn't go to that beforesave action at all .. how ever there is isValid variable and if you set it to false you will prevent save.. – Svetoslav Oct 17 '13 at 07:17

1 Answers1

2

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.

Michael Härtl
  • 8,428
  • 5
  • 35
  • 62