Backend - Display error messages before model fields
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'));
}
}
Posted in OctoberCMS on Oct 13, 2017