Search code examples
cakephpcakephp-2.5

How to login with an element in CakePHP?


Currently I have a functional login procedure. My users go to a specific login view, type their username and password, access and are redirected to a specific dashboard.

In my users controller:

public function login() {

    if ($this->request->is('post')) {
        if ($this->Auth->login()) {
            return $this->redirect();
        }
        $this->Session->setFlash('Incorrect user or password.');
    }
}

The login view:

<h1>Access with your username:</h1>
<?php
    echo $this->Form->create('User', array('action' => 'login'));
        echo $this->Form->input('username', array('label' => 'User:'));
        echo $this->Form->input('password', array('label' => 'Password:'));
    echo $this->Form->end('Login');
?>

The issue came when I was asked to add some login fields directly in my main menu. So I tried adding them as an element in my header. It didn't work.

The element I'm adding in my header:

<div>
    <?php
        echo $this->Form->create('user', array('action' => 'login'));
        echo $this->Form->input('username', array('placeholder' => 'User', 'label' => false));
        echo $this->Form->input('password', array('placeholder' => 'Password', 'label' => false));
        echo $this->Form->submit('Ingresar', array('div' => true));
        echo $this->Form->end();
    ?>
</div>

I enter username and password and click the "login" button. It throws me the "Incorrect user or password." error message and redirects me to the view for the login action (without login in the user).

In there, one can successfully login without further issue, but the point was to reduce by 1 the needed clicks for the action.

What am I missing? What should I change/add/move?


Solution

  • In your second html form, the model User is not typed as it should be

    change

    echo $this->Form->create('user', array('action' => 'login'));
    

    To

    echo $this->Form->create('User', array('action' => 'login'));
    

    Note the u changed to U from the model name