Technical notes about OctoberCMS a Laravel CMS. Notes are written by inetis team, a Swiss webagency

<- Back

Backend - Display error messages before model fields

Posted on by

By default in the backend, when a model is saved and trigg errors you get the first error message displayed on the flash message. This work very nice for small forms. For big forms with many validations rules it's not the best behavior.

In these cases we most want to have the validations messages displayed just before the related field.

Demo

Setup

To implement that you can add the following file to plugins/AUTHOR_CODE/PLUGIN_NAME/assets/js/display-fields-errors.js.


/**
 * Listen error field message and display error message
 */
$(window).on('ajaxInvalidField', function (event, field, fieldName, fieldMessages, isFirst) {

    if (isFirst) {
        $('.field-has-error').remove();
    }

    $('<div class="field-has-error text-danger">' + fieldMessages[0] + '</div>').insertBefore($(field))
});

/**
 * Remove error messages on Success
 */
$(window).on('ajaxBeforeUpdate', function (event, context, data, textStatus, jqXHR) {

    // Check handler to avoid to clear message when other Ajax request occur (e.g.: recordFinder)
    if (typeof context.handler !== 'undefined'
        && context.handler === 'onSave') {
        $('.field-has-error').remove();
    }
});

and add the $this->addJs(url('plugins/AUTHOR_CODE/PLUGIN_NAME/assets/js/display-fields-errors.js')); line in the __construct method of your controller (no forget to replace AUTHOR_CODE and PLUGIN_NAME by your dev name and the name of your plugin).

<?php namespace Author\Plugin\Controllers;

class Items extends Controller
{
    ...

    public function __construct()
    {
        ...

        $this->addJs(url('plugins/AUTHOR_CODE/PLUGIN_NAME/assets/js/display-fields-errors.js'));
    }

}