Display Zend_Form form errors in ViewScript

2019-04-09 00:46发布

I'm trying to display all form errors before the form using a ViewScript. Here is the code that I'm currently trying to use within my ViewScript:

<div class="errors">
<?php echo $this->formErrors($this->element->getMessages()); ?>
</div>

This call gives me an error message:

Warning: htmlspecialchars() expects parameter 1 to be string, array given

I've seen this same code suggested other places but its not working for me. If I print out $this->element->getMessages() I do see the error messages as the following:

Array ( [myField] => Array ( [isEmpty] => Value is required and can't be empty ) )

Any ideas?

2条回答
劳资没心,怎么记你
2楼-- · 2019-04-09 01:28

The getMessages() returns an array of form element names as keys which each contain an array of errors for that element. So basically instead of handing the formErrors view helper:

Array ( [isEmpty] => Value is required and can't be empty )

You are handing it:

Array ( [myField] => Array ( [isEmpty] => Value is required and can't be empty ) )

You would want to do something like this instead:

$arrMessages = $this->myForm->getMessages();
foreach($arrMessages as $field => $arrErrors) {
    echo sprintf(
        '<ul><li>%s</li>%s</ul>',
        $this->myForm->getElement($field)->getLabel(),
        $this->formErrors($arrErrors)

    );
}
查看更多
Rolldiameter
3楼-- · 2019-04-09 01:33

As Mark points out in his answer, the getMessages() returns an array of form element names as keys which each contain an array of errors for that element; and his solution is:

$arrMessages = $this->myForm->getMessages();
foreach($arrMessages as $field => $arrErrors) {
    echo sprintf(
        '<ul><li>%s</li>%s</ul>',
        $this->myForm->getElement($field)->getLabel(),
        $this->formErrors($arrErrors)

    );
}

This works, as long as getMessages() results in a two-dimensional array. However, if the form is based on relational data sets generated by Doctrine (or some other plugin), the error message associated with a field might also be an array and the above code will crash because it treats $arrErrors as a string when it turns out to be an array.

To capture the error messages if there's a second data set we could introduce a foreach statement nested inside the first foreach statement, but that won't work when getMessages() results in a two-dimensional array; nor does it work if the data sets are more than two-deep.

In a relational data scenario where we don't know how deep the error message comes from, a scalable solution is

$arrMessages = $this->myForm->getMessages();
print_r ($arrMessages);
查看更多
登录 后发表回答