0

Morning,

I have a strange problem with the Zend Form Validator. When I want to output the error messages I see: ArrayArray.

My code:

<?php

// Load sms request form
$smsRequestForm = new Application_Form_Sms_Request();

// Form posted?
if ($this->getRequest()->getMethod() != 'POST') {
    // Show the form
    $this->view->showForm = true;            
    $this->view->smsRequestForm = $smsRequestForm;
} elseif (!$smsRequestForm->isValid($_POST)) {
    // Show the form and output the validation errors
    $this->view->showForm = true;            
    $this->view->smsRequestForm = $smsRequestForm;

    // Loop through the error messages
    foreach($smsRequestForm->getMessages() as $message)
    {
        echo $message;
    }
} else {

}

I've read the docs and learned that echo $message; should output the errormessage in plain text.

Doing foreach($smsRequestForm->getMessages() as $key => $message); does not solve my problem.

Does anyone know what I'm doing wrong?

Thanks in advance!

ivodvb
  • 1,164
  • 2
  • 12
  • 39

1 Answers1

2

You are mistaken here, getMessages() returns an array like this for example:

array(2) {
  ["username"] => array(2) {
    ["stringLengthTooShort"] => string(33) "'' is less than 3 characters long"
    ["alphaStringEmpty"] => string(21) "'' is an empty string"
  }
  ["password"] => array(1) {
    [0] => string(7) "Message"
  }
}

Therefore, you need to iterate over it to get each field errors as follows:

foreach($form->getMessages() as $fields)
{
    foreach ($fields as $error) {
        echo $error;
    }
}

More information here in the manual:

getMessages() returns an associative array of element names / messages (where messages is an associative array of error code / error message pairs).

I guess what you have read in the manual, is how to get an element messages using $messages = $element->getMessages();. Error messages returned for a single element are an associative array of error code / error message pairs.

Liyali
  • 5,643
  • 2
  • 26
  • 40