Cyclone
Cyclone

Reputation: 15269

CakePHP validation messages position

Normally, the CakePHP's validation messages from models like:

class User extends AppModel {
    public $name = 'User';
    public $validate = array(
        'username' => array(
            'required' => array(
                'rule' => array('notEmpty'),
                'message' => 'A username is required'
            ),
            'regexp' => array(
                'rule' => '/^[a-z0-9]{3,10}$/i',
                'message' => 'Only letters and integers, min 3, max. 10 characters'
            )
        )
    )
}

Are printed below the inputs, I mean that messages: 'message' => 'A username is required'

So it looks like:

|INPUT|
[Message]

How do I can change that so the messages gonna be added to the array:

$errors[] = 'Message';

And then, I would like to use foreach to print them in one place.

Is that possible?

Upvotes: 0

Views: 1244

Answers (1)

bujanga
bujanga

Reputation: 26

CakePHP has all of the validation errors available to the view in $this->validationErrors. So I loop through them thusly:

<?php if ( !empty($this->validationErrors['Model']) ) { ?>
<div id="errorlist">
    <h3><a href="#">You have errors in your submission. <?php echo $warnimage; ?></a></h3>
    <div>
    <ul>
    <?php foreach( $this->validationErrors['Model'] as $val ){ ?>
        <li><?php echo $val; ?></li>
    <?php } ?>
    </ul>
    </div>
</div>
<?php } ?>

EDIT

Where to place this code? Place the code in the view where you would like it displayed.

How to disable displaying those errors below inputs? I don't disable that display but suppose if you wished you could just unset $this->validationErrors['Model']. (untested)

Another solution is to use elements as shown in this article by Miles Johnson.

Upvotes: 1

Related Questions