我需要验证登录表单,但我在表单上收到错误:注意(8):未定义的变量:user [APP / Template \ Users \ login.ctp,第5行]
可能是什么?
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); ?>
<?= $this->Form->input('email' ,array('id' =>'email')); ?>
<?= $this->Form->input('password', array('type' => 'password'), array('id' => 'password')); ?>
<?= $this->Form->submit('Login', array('class' => 'button')); ?>
<?= $this->Form->end(); ?>
</div>
</div>
UsersController.php 上的登录功能:
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');
}
}
位于UsersController.php中的UPDATE登录功能
public function login()
{
$user = $this->Auth->identify();
if($this->request->is('post'))
{
if($user)
{
$this->Auth->setUser($user);
return $this->redirect(['controller' => 'comentario']);
}
// Erro no Login
$this->Flash->error('Erro de autenticação');
}
}
验证配置:
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'email',
'password' => 'password'
]
]
],
'loginAction' => [
'controller' => 'Users',
'action' => 'login'
]
]);
}
答案 0 :(得分:1)
$user
是对变量的引用,在您的视图中未定义。如果要为用户创建表单,则标准约定为:
<?= $this->Form->create('User'); ?>
将隐式发布到呈现视图的相同操作。
<强>更新强>
在检查表单是否已发布之前,您正在为$user
调用auth,因此在提交表单之前,当正常呈现视图时,它将抛出未定义的错误。我对3.x并不过分熟悉,因此您可能需要或可能不需要将$this->request->data
显式传递给auth函数。该方法应如下所示:
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');
}
else{
//do something else here
}
}
来自3.x documentation
识别用户并在AuthComponent中记录它们:identify()您 需要手动调用$ this-&gt; Auth-&gt; identify()来识别用户 使用请求中提供的凭据。然后使用$ this-&gt; Auth-&gt; setUser() 记录用户,即将用户信息保存到会话。
对用户进行身份验证时,会检查附加的身份验证对象 按他们所附的顺序。一旦其中一个对象可以识别 用户,没有检查其他对象。一个示例登录功能 使用登录表单可能看起来像:
public function login()
{
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
} else {
$this->Flash->error(__('Username or password is incorrect'), [
'key' => 'auth'
]);
}
}
}