我正在验证用户登录,并且如果用户提交了不进行身份验证的详细信息,则希望在表单中附加错误消息。
在FieldSet中,我可以看到函数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;
}
答案 0 :(得分:1)
第一个示例是从数据库进行验证,只是将错误消息发送回表单:
//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,
));
我希望这是有用的。
答案 1 :(得分:-1)
在ZF1中:为了将错误消息附加到表单 - 您可以为此创建一个装饰元素:
取自:
http://mwop.net/blog/165-Login-and-Authentication-with-Zend-Framework.html
class LoginForm extends Zend_Form
{
public function init()
{
// Other Elements ...
// We want to display a 'failed authentication' message if necessary;
// we'll do that with the form 'description', so we need to add that
// decorator.
$this->setDecorators(array(
'FormElements',
array('HtmlTag', array('tag' => 'dl', 'class' => 'zend_form')),
array('Description', array('placement' => 'prepend')),
'Form'
));
}
}
然后作为控制器中的一个例子:
// 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