user2387319
user2387319

Reputation: 123

Showing error messages in CakePHP

I think its a very easy thing. Suppose, I am in a view of a corresponding function of a controller. The function looks like :

class SomeController extends AppController{
public function action(){
.
.
.
if($this->request->is('post')){
   .
   .
   .
   if(some error appears)
      I want to get back to the "action" view with the data that was given to it before
   else
      continue processing
   .
   .
   .
}
populate $data and send it to the view "action";
}

I mean, I just want to get back to the specific view with the data whenever I want. I used redirect(array('controller'=>'some','action'=>'action')), but it didn't work. And using render() doesn't take the $data. Please help me.

Upvotes: 0

Views: 825

Answers (1)

Oldskool
Oldskool

Reputation: 34837

What you are describing are so called flash messages, they can be displayed in your view to tell the user something, for example that a save operation failed or succeeded. You will need to load the Session component and helper in your application to use them. So in your Controller (or AppController if you want to use it application wide), add:

public $components = array('Session');
public $helpers = array('Session');

Then in your controller set the flash message desired:

if (!$this->Model->save($this->request->data)) {
    // The save failed, inform the user, stay on this action (keeping the data)
    $this->Session->setFlash('The save operation failed!');
} else {
    // The save succeeded, redirect the user back to the index action
    $this->redirect(array('action' => 'index'));
}

Make sure to output the flash message in your view, by simply echo'ing:

echo $this->Session->flash();

That should do what you're looking for.

Upvotes: 2

Related Questions