无法验证CakePHP 3的形式

时间:2016-07-20 22:48:28

标签: forms validation cakephp

我是CakePHP的新手,我无法验证登录表单。我收到以下错误:注意(8):未定义的变量:用户[APP / Template \ Users \ login.ctp,第5行]

我已尝试使用此代码:<?= $this->Form->create('User'); ?>错误已删除,但验证无效。

有人能帮助我吗?

login.ctp

<br>
<div class="index large-4 medium-5  large-offset-4 medium-offset-4 columns">
    <div class="panel">
        <h2 class="text-center">Login</h2>
        <?= $this->Form->create($user); ?>

             <?php

            echo $this->Form->input('email');
            echo $this->Form->input('password');
                ?>

            <?= $this->Form->submit('Login', array('class' => 'button')); ?>

        <?= $this->Form->end(); ?>
    </div>
</div>

登录功能 - UsersController.php

 // Login

    public function login()
    {      

        if($this->request->is('post'))
        {
            $user = $this->Auth->identify();

            if($user)
            {
                $this->Auth->setUser($user);
                return $this->redirect(['controller' => 'comentario']);
            }

            // Erro no Login

            $this->Flash->error('Erro de autenticação');
        }


    }

1 个答案:

答案 0 :(得分:0)

首先,改变这一行

<?= $this->Form->create($user); ?>

到这个

<?= $this->Flash->render('auth') ?>
<?= $this->Form->create() ?>

然后,您可以像这样简化提交

<?= $this->Form->button(__('Login')); ?>

确保在src / Model / Table中创建UsersTable.php并输入此代码

// src/Model/Table/UsersTable.php
namespace App\Model\Table;

use Cake\ORM\Table;
use Cake\Validation\Validator;

class UsersTable extends Table
{

    public function validationDefault(Validator $validator)
    {
        return $validator
            ->notEmpty('username', 'A username is required')
            ->notEmpty('password', 'A password is required')
    }

}

使用重定向登录方法中的特定控制器并不好。改变它:

return $this->redirect($this->Auth->redirectUrl());

然后告诉您的Auth组件登录后用户应该重定向

$this->loadComponent('Auth', [
        'loginRedirect' => [
            'controller' => 'Articles',
            'action' => 'index'
        ],
        'logoutRedirect' => [
            'controller' => 'Pages',
            'action' => 'display',
            'home'
        ]
    ]);

最重要的。阅读Authentication and Authorization Tutorial