Search code examples
phpvalidationzend-framework2zend-formvalidationerror

How to add an error message to the form in Zend Framework 2?


I have a complex Zend\Form with multiple nested Fieldsets. Now I need to implement a cross-Fieldset-validation. That means, the validation rule refers to multiple Elements from different Fieldsets. The only way I found to do that, is to implement this validation in MyForm#isValid(), since it's the single place, where I can access every Fieldset from.

MyForm extends Form
{
    public function isValid()
    {
        $isFormValid = parent::isValid();
        $isCrossFieldsetVaidationOk = // my additional validation logic
        return $isFormValid && $isCrossFieldsetVaidationOk;
    }
}

Not tested yet, but it will work. The problem is in adding of error messages.

I've tried

$this->setMessages(array_merge(
    $this->getMessages(), ['my new message'])
);

But it doesn't work.

How can I add Form error messages?


Solution

  • Errors messages are link to the form's elements, not directly to the form. So as newage said, you have to set the message for a specific element (so his answer is valid and I upvoted it :-) ).

    But as you extends Form, you can set you own error messages method directly in the form :

    MyForm extends Form
    {
    
        protected $errorMessages = [];
    
        public function isValid()
        {
            $isFormValid = parent::isValid();
            $isCrossFieldsetValidationOk = // your additional validation logic
    
            if (!$isCrossFieldsetValidationOk) {
                $this->addErrorMessage('Oh oh... Cross-fieldset validation error...');
            }
            return $isFormValid && $isCrossFieldsetValidationOk;
        }
    
        public function addErrorMessage($text)
        {
            $this->errorMessages[] = $text ;
            return $this; // For a fluent setter
        }
    
        public function getErrorMessages()
        {
            return $this->errorMessages ;
        }
    
        public function getMessages($elementName = null)
        {
            if ($elementName) {
                $messages = parent::getMessages($elementName);
            } else {
                $messages = array_merge($this->getErrorMessages(), parent::getMessages($elementName));
            }
            return $messages;
        }
    
    }