首页 > 解决方案 > CakePHP 从不同视图登录

问题描述

我正在使用 CakePHP 3.6,我想允许用户从不同的视图登录。我有 2 个相同的表格,但每个页面上都有一个,而另一个只有 1 页。

让我告诉你:

你可以看到这个迷你表格在每一页上

你可以看到这个迷你表格在每一页上

可以看到这个页面有两个相同的表单。

这是我的 AppControler 的初始化功能

public function initialize()
{
    parent::initialize();

    $this->loadComponent('RequestHandler', [
        'enableBeforeRedirect' => false,
    ]);
    $this->loadComponent('Flash');
    $this->loadComponent('Auth', [
        'authorize'=> 'Controller',
        'authenticate' => [
            'Form' => [
                'fields' => [
                    'username' => 'email',
                    'password' => 'password'
                ]
            ]
        ],
        'loginAction' => [
            'controller' => 'Users',
            'action' => 'login'
        ],
         // If unauthorized, return them to page they were just on
        'unauthorizedRedirect' => $this->referer()
    ]);

}

这是我的UsersController登录功能:

public function login()
{

    if($this->request->is('post')) {
        $user = $this->Auth->identify();
        if($user) {
            $this->Auth->setUser($user);
            $this->Flash->success('You logged succesfully!');
            return $this->redirect($this->referer());
        }

        // Invalid login
        $this->Flash->error('Incorrect login');
    }
}

这是表格(记住它们是相同的):

<?php if(!$loggedIn): ?>
    <?= $this->Form->create(null, ['class' => 'form-signin']) ?>

        <h2 class="form-signin-heading">Login</h2>
        <?= $this->Form->input('email', ['required' => true, 'class' => 'form-control', 'placeholder' => 'Email', 'label' => false]) ?>
        <?= $this->Form->input('password', ['type' => 'password', 'required' => true, 'class' => 'form-control', 'placeholder' => 'Contraseña', 'label' => false]) ?>
        <?= $this->Form->input('remember', ['type' => 'checkbox', 'value' => 'remember-me']) ?>
        <?= $this->Form->submit('Entrar', ['class' => 'btn btn-lg btn-primary btn-block' ]); ?>

    <?= $this->Form->end() ?>
<?php endif; ?>

这个问题对我来说似乎很明显,但我不知道如何解决它。所有视图中的表单都不起作用,而仅在用户视图中。似乎只有当我在用户视图中时它才有效的登录操作......

谢谢!

标签: phpcakephploginviews

解决方案


只需将每个视图中的表单更改为 url,以便将 POST 数据发送到 users/login

echo $this->Form->create(null, [
    'class' => 'form-signin', 
    'url' => ['controller' => 'Users', 'action' => 'login']
]); 

推荐阅读