user1458942
user1458942

Reputation: 11

cakephp beforeSave flash message

Is there a way to set flash message or error message from the Model, in the beforeSave function and read the error/message in the view. And I'm not talking about validation errors.

Upvotes: 1

Views: 1301

Answers (1)

tigrang
tigrang

Reputation: 6767

Something along these lines should work with the information available on hand:

<?php
class AppModel extends Model {

    public $lastErrorMessage;

    public function beforeSave(...) {
        $this->lastErrorMessage = null;
        return true;
    }

}

<?php
class MyModel Extends AppModel {

    public function beforeSave(...) {
        parent::beforeSave(..);
        if (error) {
            $this->lastErrorMessage = 'Some error message';
            return false;
        }
        return true;
    }
}

<?php
class MyController extends AppController {

    public function action() {
        if ($this->MyModel->save($this->request->data)) {
        } else {
            $message = "Some default message";
            if ($this->MyModel->lastErrorMessage) {
                $message = $this->MyModel->lastErrorMessage;
            }
            $this->Session->setFlash($message);
        }
    }
}

Upvotes: 7

Related Questions