Maureen Moore
Maureen Moore

Reputation: 1127

Persistent Flash Message in cakephp version 2.2.2

In my view I have:

<?php echo $this->Session->flash();  ?>

In my UsersController I have:

public function login() {

        $this->Session->delete('Flash.auth');
        $this->Session->delete('Message.flash');
        $this->Session->delete('auth');
        $this->Session->delete('Message.auth');

        if ($this->Auth->login()) {
        $this->redirect($this->Auth->redirect(array('controller' => 'users', 'action' => 'index')));
        } else {
        $this->Session->setFlash('Invalid username or password, please try again', null, null);
            }
        }
public function logout() {

    $this->defaultTextView();

    return $this->redirect($this->Auth->redirect(array('controller' => 'users', 'action' => 'login')));
    }

function index($id = null) {    
        $this->Session->delete('Message.flash');
        $this->Session->destroy('Message.flash');
        $user_id_sess = $this->Session->read('Auth.User.id');
        $this->defaultAdminViewHere();
        $this->set('user_id_sess', $this->Session->read('Auth.User.id'));
        $this->User->id = $id;
        $this->set('user', $this->User->read());    
    }

The problem is that my flash message persists even after a successful login.

pr($this->Session->read()); yielded:

Array
(
    [Config] => Array
        (
            [userAgent] => adcb84540c454620867cea3249a69ca1
            [time] => 1544388026
            [countdown] => 10
        )

    [Message] => Array
        (
            [flash] => Array
                (
                    [message] => Invalid username or password, please try again
                    [element] => default
                    [params] => Array
                        (
                        )
                )
        )
)

Forced to add more details as my post is mostly code. It doesn't display the error message when I use the wrong password. It displays the error message after I log out.

Upvotes: 0

Views: 308

Answers (1)

Rohit Rasela
Rohit Rasela

Reputation: 445

The flash message works after minimum one redirect that's why you are getting this message. When you access this login action to display login form flash message sets but not getting print. After successful login this old flash message gets print because of one redirection. You need to write your login method something like this:

public function login() {

    if ($this->request->is('post')) {

        if ($this->Auth->login()) {

            $this->redirect($this->Auth->redirect(array('controller' => 'users', 'action' => 'index')));

        } else {

            $this->Session->setFlash('Invalid username or password, please try again', null, null);

            $this->redirect(array('controller' => 'users', 'action' => 'login'));
        }
    }

}

Upvotes: 1

Related Questions