0

我正在验证用户登录,如果用户提交的详细信息未通过身份验证,我想在表单中附加一条错误消息。

在 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;
}
4

2 回答 2

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,
        ));

我希望这是有用的。

于 2012-08-28T09:44:25.863 回答
-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

于 2012-08-28T14:01:59.767 回答