views:

715

answers:

3

WHat's the best way/code in Login Form (Zend_Form) to display error message 'Login/password incorrect'?

I slowly begin to understand, that setting $this->setErrorMessage('Login/password incorrect') in form/init() is not enough and I somehow have to involve Validators to be able to see the message I set.

To which object should I bind this message and do I have to use validator or not? Thanks!

Update:

LoginAction() code:

$auth  = Zend_Auth::getInstance();
$authAdapter =
$this->_getAuthAdapter($formData['userName'],$formData['password']);
$result = $auth->authenticate($authAdapter);

if (!$result->isValid()) {
    //Problem: the line below doesn't display error message
    $form->addError('Username or password do not exist'); 
    $form->populate($formData);
    $this->view->form = $form;
A: 

I usually have just two checks to cover my authentication forms.

  1. Check username and password, and if either is not set, display a message like "Please enter both username and password"

  2. Validate credentials using Zend_Auth and display an error if they are invalid: "Invalid username or password".

I normally just pass the message to the view in a variable, but you might find a FlashMessenger useful.

David Caunt
A: 

I think you're looking for the Zend_Form_Decorator_FormErrors decorator. As this decorator is not registered by default on the Zend_Form you have to register the decorator manually.

You have to do something like this in your form's init() method:

$this->setDisableLoadDefaultDecorators(true);
$this->setDecorators(array(
    'FormElements',
    array('HtmlTag', array('tag' => 'dl', 'class' => 'zend_form')),
    'FormErrors',
    'Form'
));
Stefan Gehrig
A: 

I think the most flexible way is to use validators and their messages. Here two examples of how I normally do it:

//define the password field
$password = $this->addElement('password', 'password', 
    array ('label'=>'Password'));

//get the password element and add validators, filters, etc.
$password = $this->getElement('password')
    ->setRequired(true)
    ->addFilter('StringTrim')
    ->addValidator('NotEmpty', true, array('messages' => array(
        'isEmpty' => 'You did not enter your password!'))
     )
    ->addValidator('stringLength', true, array (6));

//this shows how you can always get a validator 
//and change the message for it
$password->getValidator('stringLength')
     ->setMessage('Your password is too short.');
tharkun
Why is $this->translate() required? Is that the best way to set custom error messages?
gaoshan88
$this->translate is not required. That's just for multi-language pages in case you have a translation adapter up and running.
tharkun