【问题标题】:Can't validate form CakePHP 3无法验证表单 CakePHP 3
【发布时间】:2016-07-20 22:48:28
【问题描述】:

我是 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');
        }


    }

【问题讨论】:

  • 首先你需要先阅读它。这将清楚你想要什么:book.cakephp.org/3.0/en/tutorials-and-examples.html
  • 我的 register.ctp 有工作验证。我只想知道为什么我无法验证 login.ctp。我已经阅读了这些教程,感谢您的回答。
  • 验证用户或验证表单域
  • 我需要验证表单,验证空字段等。我不能在 login.ctp 上执行此操作,但在 register.ctp 中我可以正常执行。我将 register.ctp 代码复制到 login.ctp 并没有。
  • 首先你必须为你的表创建模型和实体

标签: forms validation cakephp


【解决方案1】:

首先,改变这一行

<?= $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

【讨论】:

    猜你喜欢
    • 2016-01-01
    • 2017-01-24
    • 2011-03-21
    • 1970-01-01
    • 2018-04-12
    • 2012-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多