Search code examples
phpvalidationcakephpcakephp-3.0flash-message

Cakephp3 pass (custom) validation to flash message


It is simple to pass a message to flash via:

$this->Flash->error(__('The user could not be saved. Please, try again.'));

But when there are more errors from:

$package->errors();

I use just a simple foreach loop:

foreach ($package->errors() as $error=>$value)
{
    foreach ($value as $single_error)
    {
        $error_array[] = ($single_error);
    }
}

Then I pass it to a flash element:

$this->Flash->custom($error_array, [
                 'key' => 'custom']);

And in the flash message:

if ($message > 0) {
    foreach ($message as $m) {
        echo h($m).'<br />';
    }
} else {
    echo h($message);
}

I wonder it here is a better way of handling an array of validation errors.


Solution

  • I am using the following method if there are errors:

    Controller:

    $errors = $action->errors();
    $errorMessages = [];
    
    array_walk_recursive($errors, function($a) use (&$errorMessages) { $errorMessages[] = $a; });
    
    $this->Flash->error(__('Your action cannot be saved!'), ['params' => ['errors' => $errorMessages]]);
    

    Template/Element/Flash/error.tcp:

    <?php if (isset($params) AND isset($params['errors'])) : ?>
            <ul class="collection with-header">
                <li class="collection-header"><h5><?= __('The following errors occurred:') ?></h5></li>
        <?php foreach ($params['errors'] as $error) : ?>
                <li class="collection-item"><i class="material-icons">error</i><?= h($error) ?></li>
        <?php endforeach; ?>
            </ul>
    <?php endif; ?>
    

    Result:

    result

    Just for anyone interested, I am using MaterializeCSS.