views:

19

answers:

1

Hello,

I am creating a website with Zend_Form. In my controller, I assign a form object to the view. In the view, I use the following code to render the form:

<?php if ( isset( $this->success ) ): ?>
    <div class="message success"><p>Thanks!</p></div>
<?php elseif ( sizeof( $this->form->getMessages( ) ) > 0 ): ?>
    <div class="message success"><p>Something went wrong..</p></div>
<?php endif; ?>

<form>
    <label>Name:</label>
    <?php echo $this->form->name; ?>

    <label>E-mail:</label>
    <?php echo $this->form->name; ?>
</form>

Until now, this way of checking if there were form errors was good enough. But my client asked me if I could also specify the field that was not correct. So, for example: "Warning: you forgot to fill in your name". I've really got no idea on how to do this with Zend. Does anybody know where to start?

Thanks,

Martijn

A: 

You should be able to see it by requesting getErrors(); on the Zend_Form object.

It will return a array of errors where the key is the field name returns something like this.

array(
 'fieldname' => array('error1', 'error2'),
 'username' => array('errors')
);

You could also call $form->getElements() and iterate over each element to see which one is throwing errors

madsleejensen
That's true, but the problem is that my field names are English and my website is in Dutch. It would be really user unfriendly to show these English field names.
Martijn Dwars
Yes the field names are the name="" value's of the inputs / selects / textarea, you have to either add custom errors to the elements (which are in dutch) or create a conditional logic within the view saying something like "if ($fieldname == 'username') { echo "error on dutch" }" You can also add a Zend_Translate object to the form for handling error translations.
madsleejensen
I did try to use a Zend_Translate adapter to provide translated error messages. This worked, but this only provides a way to translate the messages itself (e.g. "This field is empty" => "Dit veld is leeg"), but it doesn't provide a way to also add a name for the field?
Martijn Dwars
You could iterate all the elements and call $element->isValid() to check them, and then use $element->getLabel() . ": " . implode("," $element->getErrorMessages()); . Or else you could use customize the standard decorators.
madsleejensen