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.

4

2 に答える 2

4

1 つの方法は、使用するフィールドの配列を要素に渡し、それらをループして呼び出します。

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

配列を渡す

$this->element('validation_errors', array('fieldsToShowValidationFor' => array('id', 'etc'));
于 2012-06-08T05:53:09.970 に答える
4

配列をフラット化するのが最善の方法のようです。幸いなことに、CakePHP にはSet::flattenがあります。

これがerrorSummary.ctp私が思いついたものです:

<?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 }?>
于 2012-06-10T20:19:29.850 に答える