Reputation: 4813
I have the following code in my controller:
class ContactsController extends AppController {
public $helpers = array('Html', 'Form', 'Session');
public $components = array('Session');
public function index() {
$this->set('contacts', $this->Contact->find('all'));
}
public function view($id) {
if (!$id) {
throw new NotFoundException(__('Invalid contact'));
}
$contact = $this->Contact->findById($id);
if (!$contact) {
throw new NotFoundException(__('Invalid contact'));
}
$this->set('contact', $contact);
}
public function add() {
if ($this->request->is('post')) {
$this->Contact->create();
if ($this->Contact->save($this->request->data)) {
$this->Session->setFlash('Your contact has been saved.');
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash('Unable to add your contact.');
}
}
}
}
In the add() method I have the line $this->redirect(array('action' => 'index'));
I'm expecting this line to redirect back to my index page within my view. But all I get is a blank white page.
Any help appreciated.
Regards, Stephen
Upvotes: 2
Views: 9094
Reputation: 3414
After lots of research finally I got a solution for that.
Please use
ob_start();
in AppController.php
ob_start();
class AppController extends Controller {
function beforeFilter() {
parent::beforeFilter();
}
}
Upvotes: 7
Reputation: 29137
Your code looks valid; I don't see an error in the code you provided.
There are a few possible causes;
app/Config/core.php
- Configure::write('debug', 2);
<?php
or ?>
. This will cause a 'headers already sent' warning, and the browser will not redirect. There are many questions regarding this situation here on StackOverflow, for example: How to fix "Headers already sent" error in PHPNote;
in CakePHP its good practice to put a return
before any redirect statement; this will allow better Unit-testing of your application, i.e.:
return $this->redirect(array('action' => 'index'));
Tracking these kind of problems may be troublesome, I'll add some pointers
Auth
or Security
component, it's possible that one of these cause the 'problem' (e.g. authorization failed or the posted data is marked 'invalid', which will be handled by a 'blackHole()' callback. Disable both in your AppController to check if the problem is still presentDebugging code:
if (headers_sent($file, $line)) {
exit("headers were already sent in file: {$file}, line number: {$line}");
}
Upvotes: 18