0

I have a form, where the error messages have to be displayed bundled at one place. The default messages are general, so the user sometimes doesn't know, which message is for which form field:

A record matching the input was found

Value is required and can't be empty

The input is not a valid email address...

I could write a custom message for every field, but is much effort and copy&paste.

So, I'd like to display the messages like this:

My element Foo label: A record matching the input was found

My element Bar label: Value is required and can't be empty

My element Buz label: The input is not a valid email address...

How to achieve this?

Community
  • 1
  • 1
automatix
  • 14,018
  • 26
  • 105
  • 230

1 Answers1

0

ZF2 seems not to provide a solution for this requirement. My solution/workaround is to override the Zend\Form\View\Helper\FormElementErrors replacing these lines of the FormElementErrors#render(...) by

$this->prepareMessagesToPrint($messages, $messagesToPrint, $element, $escapeHtml);

and add a method, that process the $messages as desired:

protected function prepareMessagesToPrint($messages, &$messagesToPrint, $element, $escapeHtml) {
    foreach ($messages as $nameOrType => $elementOrError) {
        if (is_string($elementOrError)) {
            $elementLabel = $element->getLabel()
                ? '<b>' . $this->view->translate($element->getLabel()) . '</b>' . ': '
                : null
            ;
            $message = $escapeHtml($elementOrError);
            $messagesToPrint[] = $elementLabel ? $elementLabel . $message : $message;

        } elseif (is_array($elementOrError)) {
            $newElement = $element->get($nameOrType);
            $this->prepareMessagesToPrint(
                $elementOrError, $messagesToPrint, $newElement, $escapeHtml
            );
        }
    }
}
automatix
  • 14,018
  • 26
  • 105
  • 230