1

I'm trying to display a summary of validation errors at the top of the form instead of next to each input.

I didn't see any built-in form helper to do this, so I decided to create a view element to do it. However, $this->Form->validationErrors isn't a flat array of error messages, so I can't just loop through it and print out the validation errors. Here's a var_dump with just one validation error on one field:

array(1) { [0]=> &array(1) { ["terrcode"]=> array(1) { [0]=> string(30) "Please enter a territory code." } } }

So I can't loop through that without knowing the field names or flattening the array somehow. There's got to be an easier way to do this that I'm missing.

2 Answers 2

4

One way would be to pass an array of fields to use to the element and then loop over them and call:

foreach($fieldsToShowValidationFor as $field) {
    echo $this->Form->error($field);
}

Pass the array via

$this->element('validation_errors', array('fieldsToShowValidationFor' => array('id', 'etc'));
Sign up to request clarification or add additional context in comments.

Comments

4

Flattening the array seems to be the way to go, and fortunately CakePHP has a Set::flatten.

Here's the errorSummary.ctp I came up with:

<?php
$errors = $this->Form->validationErrors;
$flatErrors = Set::flatten($errors);
if(count($errors) > 0) { ?>
<div class="errorSummary">
<ul>
<?php foreach($flatErrors as $key => $value) { ?>
    <li><?php echo($value); ?></li>
<?php } ?>
</ul>
</div>
<?php }?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.