1
votes

What is wrong with my session? Why is it not an object? I am trying the cakePHP quick start blog example. I've copied all the code, but I can't keep this error from appearing when editing, deleting or adding a blog message:

Call to a member function setFlash() on a non-object

I've put in debug lines in views to see the session variables and the session data seems fine. I've also added the 'Session' helper to the controller to see if that would help.

Controller:

class PostsController extends AppController {

public $helpers = array('Html', 'Form','Session');

public function index() {
     $this->set('posts', $this->Post->find('all'));
}

public function view($id = null) {
    if (!$id) {
        throw new NotFoundException(__('Invalid post'));
    }
    $post = $this->Post->findById($id);
    if (!$post) {
        throw new NotFoundException(__('Invalid post'));
    }
    $this->set('post', $post);
}

public function add() {
    if ($this->request->is('post')) {
        $this->Post->create();
        if ($this->Post->save($this->request->data)) {
            $this->Session->setFlash('Your post has been saved.');
            $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash('Unable to add your post.');
        }
    }
}
public function edit($id = null) {
    if (!$id) {
    throw new NotFoundException(__('Invalid post'));
    }
    $post = $this->Post->findById($id);
    if (!$post) {
    throw new NotFoundException(__('Invalid post'));
    }
    if ($this->request->is('post') || $this->request->is('put')) {
    $this->Post->id = $id;
    if ($this->Post->save($this->request->data)) {
        $this->Session->setFlash('Your post has been updated.');
        $this->redirect(array('action' => 'index'));
    } else {
        $this->Session->setFlash('Unable to update your post.');
    }
    }
    if (!$this->request->data) {
    $this->request->data = $post;
    }
}

 public function delete($id) {
    if ($this->request->is('get')) {
    throw new MethodNotAllowedException();
    }
    if ($this->Post->delete($id)) {
    $this->Session->setFlash('The post with id: ' . $id . ' has been deleted.');
    $this->redirect(array('action' => 'index'));
    }
}
}
?>

I've added 'Session' to the helpers and I've tried just using $this->Session->flash() but there seems to never be a session object. Sessions are started correctly and the session data is present:

Array ( [Config] => Array ( [userAgent] => fd7f6d79160a3f20a706f3fed20eff02 [time] => 1369643237 [countdown] => 10 ) )

I don't know why there's no instance of session available.

1

1 Answers

3
votes

You are missing the session component.

You need to add it inside your PostsController:

class PostsController extends AppController {
    public $components = array('Session');
    //...
}