Php 如何向表单中添加错误消息?
我正在验证用户登录,如果用户提交了未经身份验证的详细信息,我希望在表单上附加一条错误消息 在FieldSet中,我可以看到函数Php 如何向表单中添加错误消息?,php,zend-framework2,Php,Zend Framework2,我正在验证用户登录,如果用户提交了未经身份验证的详细信息,我希望在表单上附加一条错误消息 在FieldSet中,我可以看到函数setMessages(),但这似乎只与元素键匹配和设置 如何将错误消息附加到表单而不是表单元素 以下代码位于LoginForm类中 public function isValid() { $isValid = parent::isValid(); if ($isValid) { if ($this->getMapper())
setMessages()
,但这似乎只与元素键匹配和设置
如何将错误消息附加到表单而不是表单元素
以下代码位于LoginForm类中
public function isValid()
{
$isValid = parent::isValid();
if ($isValid)
{
if ($this->getMapper())
{
$formData = $this->getData();
$isValid = $this->getMapper()->ValidateUandP($formData['userName'], $formData['password']);
}
else
{
// The following is invalid code but demonstrates my intentions
$this->addErrorMessage("Incorrect username and password combination");
}
}
return $isValid;
}
第一个示例是从数据库进行验证,并将错误消息发送回表单:
//Add this on the action where the form is processed
if (!$result->isValid()) {
$this->renderLoginForm($form, 'Invalid Credentials');
return;
}
下一步是向表单本身添加简单验证:
//If no password is entered then the form will display a warning (there is probably a way of changing what the warning says too, should be easy to find on google :)
$this->addElement('password', 'password', array(
'label' => 'Password: ',
'required' => true,
));
我希望这是有用的。在ZF1中:为了将错误消息附加到表单,您可以为此创建一个decorator元素: 摘自: 然后作为控制器中的一个示例:
// Get our authentication adapter and check credentials
$adapter = $this->getAuthAdapter($form->getValues());
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($adapter);
if (!$result->isValid()) {
// Invalid credentials
$form->setDescription('Invalid credentials provided');
$this->view->form = $form;
return $this->render('index'); // re-render the login form
}
不确定这在ZF2中是否仍然有效谢谢David,解决方案已经可以正常工作了,唯一缺少的是验证服务API返回无效登录时的错误消息。抱歉,我不明白。。。顶部的不是正确的解决方案吗?发布一些代码,希望能给你一些启示。
// Get our authentication adapter and check credentials
$adapter = $this->getAuthAdapter($form->getValues());
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($adapter);
if (!$result->isValid()) {
// Invalid credentials
$form->setDescription('Invalid credentials provided');
$this->view->form = $form;
return $this->render('index'); // re-render the login form
}