Set Zend\Form Error Messages from Controller
Asked Answered
G

3

6

this is probably a very simple task, but currently I'm failing horribly at it. I just want to add a custom error to my form when my authentication fails.

What i tried

$form->setMessages(array(
    array('password' => $this->failedLoginMessage)
));    

Unexpected Result

\Zend\Debug\Debug::dump($form->getMessages());
array(0) {}

If i understand the code correctly this should attach an error message to the password element. Actually looking at the setMessages i thought attaching a single-dimension array should have been enough, but it needs the 2nd dimension, too :S I'm just stuck on that simple task, sigh :)

Thanks in advance!

Guaranty answered 15/10, 2012 at 13:28 Comment(0)
M
14

My comment as answer, as you've requested:

You can also set error messages to an element directly, using:

$form->get('elemName')->setMessages(array('message1', 'message2', ...));
Mediocre answered 16/10, 2012 at 10:13 Comment(0)
G
1

Simple solution, read the code correctly... Correct usage as following:

$form->setMessages(array(
    'formElementName' => array(
         // multiple error messages possible...
    )
));
Guaranty answered 15/10, 2012 at 13:49 Comment(2)
You can also set error messages to an element directly, using $form->get('elemName')->setMessages(array('message1', 'message2', ...));Mediocre
@DanielM Provide this as an alternate answer and this will be the selected one. I was constantly looking for $form->getElement... good to know simple get() will do.. :)Guaranty
C
1

Use this lines of code.

$form->getElement('controlname')->setErrors(array('Your custom error'));

in case the message not showing in your page check removeDecorator method used in zend form. if there is use addDecorator method befor writing error message code line.

Coopt answered 25/3, 2015 at 7:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.