Showing custom bootstrap error message on Joomla 3.x administration

Today while developing my Joomla component I was told to show custom error message while doing javascript validation at admin side.

Based on the Joomla documentation you can set a field as required as below.

<field name="totalsms" 
 type="text" 
 label="Sample Admin Field"
 size="40" 
 default="" 
 required="true" />

The above field will be automatically validated at admin side if the form is submitted without giving a value in it.

However my requirement was to validate a field’s value based on another field’s value.  In my admin form I have 2 fields named as ‘Need Book’ and ‘Which Book’.  Need book is a list button where Yes or No will be displayed.  If the admin selected ‘Yes’ then the next field Which Book should be validated for mandatory.

Here is what I did today.  Definitely there would be better ways to do.

In Joomla admin, the error messages are displayed as below.

joomlaerr

These error messages are displayed under a div container ‘system-message-container’.  My idea is to hack this div container and show my custom error message.

Below are the javascript methods I introduced

This javascript method will create a new div container with the provided message and add them inside system-message-container.

function addCustomMessage(message, uniqid, css){
 css = typeof css !== 'undefined' ? css : '';
 
 var errcontainer = document.getElementById('system-message-container');
 var pnode = document.createElement("p");
 var textnode = document.createTextNode(message);
 pnode.appendChild(textnode);
 var divnode = document.createElement("div");
 divnode.setAttribute('id',uniqid);
 var already_available = document.getElementById(uniqid);
 if(already_available) return;
 
 divnode.className = "alert "+css;
 divnode.appendChild(pnode);
 errcontainer.appendChild(divnode);
}

This javascript method is to delete the newly created div container

function removeCustomMessage(uniqid){
 var parent = document.getElementById("system-message-container");
 var child = document.getElementById(uniqid);
 if(child){
  parent.removeChild(child);
 }
}

Below is the javascipt code which does the validation in my default.php

if(document.getElementById('jform_need_book').value == 'YES' && document.getElementById('jform_which_book').value == ''){
  addCustomMessage("Please select a book", 'val_select_book', 'alert-error');
  return;
 }else{
  removeCustomMessage('val_select_book');
 }

Thats all.

1 comment

Leave a Reply

Your email address will not be published. Required fields are marked *