Using jQuery UI Autocomplete with hidden ID in ColdBox

Previously in How to use jQuery UI Autocomplete with ColdBox and Bootstrap the value used was singular and also the record identifier. However what if we want to submit the identifier but show another text value for the auto-suggest to the user, for example, if we want to show the client’s full name for auto suggest, but submit the client’s ID.

The environment used for this example is:

  • ColdBox 3.8
  • BootStrap 3.1.1
  • ColdFusion 10

The steps are essentially the same  (the differences are in the helper function and front end UI), i.e.

  • Reference jQuery UI in the main layout
  • Create a helper function to retrieve the required data
  • Use autocomplete on the view page

1 Reference the jQuery UI in the main layout

Open layouts\Main.cfm and add the following reference to the style sheet and JavaScript for jQuery UI (if not already present), i.e.

  <link href="/path/to/bootstrap/bootstrap.min.css" rel="stylesheet" type="text/css"/ >
  <link href="/path/to/jquery-ui/themes/smoothness/jquery-ui.min.css" rel="stylesheet" type="text/css" />
  <script src="/path/to/jquery/jquery.11.1.js"></script>
  <script src="/path/to/jquery/ui/jquery-ui.min.js"></script>
  <script src="/path/to/bootstrap/bootstrap.min.js"></script>

2 Create a helper function to retrieve the required data

Load includes\helpers\ApplicationHelper.cfm and add the following function:

<cffunction name="getClients" access="remote" output="no">
    var qGet = "";
    var clientsList = [];
    var stClients = "";
  <cfquery name="qGet" datasource="clients">
      clientid, title, firstname, lastname
    FROM clients
    //convert query to array
    for (var row in qGet) {
      stClients.label = row.title & ' ' & row.firstname & ' ' & row.lastname;
      stClients.value = row.clientid;
    ArrayAppend(clientsList, stClients);
    return clientsList;

3 Use jQuery UI Autocomplete on the view page

In the view page, for example, the edit.cfm where autocomplete is needed, add the following code:

//somewhere in the form section, add this:
<input type="text" name="clientname" id="clientname" class="form-control client-suggest" value="">
<input type="hidden" name="clientid" id="clientid" class="form-control" value="">

  //retrieve list of clients from db, getClients is a function in the application helper
  var #toScript(getClients(), "clientsList")#;

$(document).ready(function() {
   var suggestInput = function (sourceValues, elemClassName){
      $('input.' + elemClassName).each(function(){
         var formElemName = $(this).attr('name');
         var hiddenElemID = formElemName + 'id';

         //on auto suggest
            source: sourceValues,
            select: function(event, ui) {
               selectedObj = ui.item; 
               $('#'+ hiddenElemID).val(selectedObj.value); 
               return false; 
            change: function(event,ui) {
               var formElemVal = $(this).val();
               if (formElemVal === ''){
                  //clear id from hidden field if input is blank
                  $('#'+ hiddenElemID).val('');
               } //if
         }); //autocomplete

         //clear id from hidden field if input is blank
         $('#' + formElemName).blur(function(){
            if ( $('#' + formElemName).val() == ''){
               $('#' + hiddenElemID).val(''); 
      } //each
   } //suggestInput

   if ($('.client-suggest').length){
      //activate auto suggest for client input box 
      //(i.e. the input with class of 'client-suggest')
}); //document.ready

Here we use the ColdFusion toScript function to convert ColdFusion value to JavaScript saving it as clientsList. getClients is the ColdBox helper function which we added to ApplicationHelper.cfm.

The client name input box will sugget the client’s full name (including title), but upon form submission, the client’s ID will be submitted.


How to Show Required Icon for Mandatory Fields

Here’s a quick tip on how to show the required icon for mandatory fields when using FormValidationJS for Bootstrap forms.

In your application’s style sheet ensure you add the following:

/* Adjust feedback icon position */
#<your-form-id> .has-feedback .form-control-feedback {
   top: 0;
   right: -15px;
/* for required select element, a padding-right of 42.5px is added; we want to over-ride this value */
   .has-feedback .form-control {
   padding-right: 12px;
.required .control-label:after {
   color: #d00;
   content: "*";
   position: absolute;
   margin-left: 1px;
   font-family: 'Glyphicons Halflings';
   font-weight: normal;
   font-size: 10px;

Then in the page where you have a form that needs client side validation using FormValidation, ensure you have the following:

   framework: 'bootstrap',
   icon: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-refresh'
   fields: {
      firstname: {
         validators: {
            notEmpty: {
               message: 'First Name is required and cannot be empty'
      lastname: {
         validators: {
            notEmpty: {
               message: 'Last Name is required and cannot be empty'

In the actual form, ensure you have something similar to this, in particular the class=”form-group required” part:

<form id="<your-form-id>" class="form-horizontal" role="form" method="post" action="">
   <div class="form-group required">
      <label for="firstname" class="col-md-3 control-label">First Name:</label>
      <div class="col-md-3">
         <input type="text" name="firstname" class="form-control" placeholder="First Name">
   <div class="form-group required">
      <label for="lastname" class="col-md-3 control-label">Last Name:</label>
      <div class="col-md-3">
         <input type="text" name="lastname" class="form-control" placeholder="LastName">

Lastly, don’t forget to link to the style sheet (including the application’s styles) and scripts for FormValidation JS and jQuery in the appropriate places (in the head section for styles, and body for scripts):

<title>Page title</title>
<link href="<path-to-formvalidation>/formValidation.min.css" rel="stylesheet" />
<link href="<path-to-application-stylesheet>/your-app-name.css" rel="stylesheet" />
   <script src="<path-to-jquery>/jquery.min.js"></script>
   <script src="<path-to-formvalidation>/formValidation.min.js"></script>
   <script src="<path-to-formvalidation>/framework/bootstrap.min.js"></script>


ColdBox MailService – Passing Complex Values to the Body

In a previous blog post on using the ColdBox MailService we made use of the service’s SetBodyTokens method to pass through simple values, that is something like this:

/* define the token for use in the email view.
this is the dynamic content for the html email body */

  title = emailTitle,
  firstName = arguments.user.getFirstName(),
  url = baseURL & "/reports/list"

Then in the view used to display the email body content, any placeholder variables will be replaced with the passed in value. That is @title@ will be replace with the value passed in. So if a value of Cool Programmer was passed in, then @title@ will now show Cool Programmer.

Using the SetBodyTokens method means that we can not passed in complex values like an array or a struct. To overcome this issue we will instead use the MailService’s SetBody method to pass in the value via the args parameter to the email body’s view template.

Firstly, in the handler where the MailService is invoke and where the sendUserDetails function is defined, add the following dependency injections at the top of the file:

property name="mailService" inject="coldbox:plugin:MailService";
property name="renderer" inject="coldbox:plugin:Renderer";
property name="configBean" inject="coldbox:configBean";

Then add the following function to gather the information and send the email in this same file, as follows:

public void function sendUserDetails(event){ 
 var email = MailService.newMail().config(
   subject= "User Details"

 var stInfo = {};
 stInfo.title = "Cool Programmer";
 stInfo.firstname = "John";
 stInfo.lastname = "Doe"; = "";

 // generate html content for email from template
 email.setBody( renderer.renderView( view='userDetails', args=stInfo ));

 // Send the email. MailResult is a boolean.
 mailResult = mailService.send(email);

} //sendUserDetails

In the view for the email body (i.e.  view=”userDetails”), the passed in values are in the args scope, so to access them we refer to each variables as args.variable-name (i.e. replace stInfo with argsargs.firstname). Here’s a partial code snippet to illustrate:

#args.firstname# #args.lastname#<br>

A Subquery Using ColdBox’s Detached Criteria Builder

Let’s say we want to create the following SQL query with a subquery using ColdBox’s Detached Criteria Builder:

select *
from reports r
where r.report_id not in (
   select report_id
   from confirmations c
   inner join staffs s on s.staff_id = c.staff_id
   inner join teams t on t.team_id = s.team_id
   where t.teamName = 'Developers'

In our objects world we have the following corresponding entities:

  • report
  • confirmation
  • staff
  • team

And the following relationships between them:

  • A report can have one to many confirmations submitted by staff
  • A confirmation belongs to a staff
  • A staff belongs to a team

Then our ORM query for the above SQL query using ColdBox’s Detached Criteria Builder would be as follows:

cr = reportService.newCriteria();


  • confirmations is the relationship between the report and confirmation entities
  • staffs is the relationship between the confirmation and staff entities
  • teams is the relationship between the staff and team entities

Further Learning

For more information on ColdBox Criteria Builder and Detached Criteria Builder, please visit these links:

Using the ColdBox MailService Plugin

Need to send out emails in your ColdBox application? Then the ColdBox MailService plugin is your friend. Here are the steps:

  1. Inject the mail service
  2. Create the email method
  3. Create the html email view
  4. Using the email method

Inject the Mail Service

Before you can use the mail service, we need to inject it into the handler component where we will define the mail method like so:

component accessors="true" {
  property name="mailService" inject="coldbox:plugin:MailService";
  property name="renderer" inject="coldbox:plugin:Renderer";
  property name="configBean" inject="coldbox:configBean";
  property name="userService"  inject="model:userService@solitary";
} //component


  • We first inject the MailService plugin
  • Then the Renderer plugin so we can render the email message
  • Finally we inject the configBean to bring in any configurations from the ConfigurationCFC (coldbox.cfc)

Create the email method

In the same handler component, create an email method, e.g. notifyUser. Here’s an example to illustrate:

private void function notifyUser(required user) {
  var baseURL = len(configBean.getKey('sesBaseURL')) ? configBean.getKey('sesBaseURL') : configBean.getKey('htmlBaseURL');
  var emailTitle = "New Records Available";
  rc.emailView = 'notifications/newEntry';

  // Create a new mail object = MailService.newMail().config(
    subject= emailTitle

  /* define the token for use in the email view. 
     this is the dynamic content for the html email body */{
    title = emailTitle,
    firstName = arguments.user.getFirstName(),
    url = baseURL & "/reports/list"

  // Add HTML email'utf-8',type='text/html',body=renderer.renderView(view=rc.emailView));

  // Send the email. MailResult is a boolean.
  local.mailResult = mailService.send(local.Email);
} //notifyUser


  • We use the injected configBean to retrieve settings from the ConfigurationCFC (coldbox.cfc) and set the base URL
  • Then we create a new mail message using MailService’s newMail method
  • Then we define the token for the body and add the html email. The content of the html email is defined in the views folder. In the above example, a view template called newEntry.cfm should be created and saved under the views/notifications sub-folder
  • Finally we send it using the MailService plugin’s send method.

Create the email view

Under the views folder, create a subfolder called notifications. Then in this new subfolder create a new file called newEntry.cfm and add the following code snippet:

  <p>Dear @FIRSTNAME@,</p>
  <p>New records are now available. Please <a href="@URL@">logon</a> to action them.</p>
  <p>System Admin</p>


  • Any @key@ will be replace by the values defined in the MailService’s new email setBodyTokens method in the notifyUser method.
  • So in this instance @TITLE@ will be replaced with the value: New Records Available

Using the email method

Here’s the scenario. In your application you have a method which uploads a file and emailing all application users to notify them of new records. Here the notifyUser method is called and used.

And an example code snippet to illustrate.

public void function upload(event){
  uploadResult = getPlugin("FileUtils").uploadFile(fileField="csvFile",destination=expandPath('files'),nameConflict="Overwrite");
  if (!StructIsEmpty(uploadResult) ){
    users = userService.findAllWhere(criteria={isActive=true});
    if (!ArrayIsEmpty(users)){
      for (var i=1; i<=ArrayLen(users); i++){
    } //if !ArrayIsEmpty()
} //upload

Traversing Multiple ORM Associations with ColdBox CriteriaBuilder

Let’s say you have the following entities:

  • Report
  • Confirmation
  • Staff
  • Team

And the following associations between the entities:

  • A report can have one to many confirmations submitted by staff
  • A confirmation belongs to a staff
  • A staff belongs to a team

And let’s say you are querying the Report entity but also want to show Confirmation, Staff and Team entity details in a ColdBox view. How would you do use ORM associations and ColdBox’s CriteriaBuilder to navigate multiple associations and bring back the required information?

Here’s how we can achieve that goal by using the ColdBox CriteriaBuilder’s CreateAlias method:

  • Create a link from Report to Confirmation with CreateAlias
  • Create a second link from Confirmation to Staff with CreateAlias
  • Lastly, create a third link from Staff to Team with CreateAlias
  • Link all of the above together by chaining the CreateAlias, i.e. CreateAlias().CreateAlias().CreateAlias()

Here are some example code snippets to illustrate:

1. Entities and their Associations

Report Entity

component persistent="true" extends="<path-to-base-entity>" table="reports" { 
 property name="report_id" fieldtype="id" generator="identity" setter="false";
 property name="startDate" ormtype="date";
 property name="endDate" ormtype="date";

 property name="confirmations" fieldtype="one-to-many" inverse="true" cfc="<path-to-confirmation-model>" singularname="confirmation" fkcolumn=report_id" cascade="delete"; 
 public Report function init(){      
        return this;
} //component

Confirmation Entity

component persistent="true" extends="<path-to-base-entity>" table="confirmations" { 
 property name="confirmation_id" fieldtype="id" generator="identity" setter="false";
 property name="comments" sqltype="nvarchar" length="800";

 property name="staffs" singularname="staff" fieldtype="many-to-one" cfc="<path-to-user-model>" fkcolumn="staff_id";
 public Confirmation function init(){
    staffs = [];    
    return this;
} //component

Staff Entity

component persistent="true" extends="<path-to-base-entity-model> " table="staffs" {
  property name="staff_id"  fieldtype="id" generator="identity" setter="false";
  property name="firstname" sqltype="nvarchar" length="100";
  property name="lastname" sqltype="nvarchar" length="100";

  property name="teams" singularname="team" fieldtype="many-to-one" cfc="<path-to-team-model>" fkcolumn="team_id" foreignkeyname="FK_staff_team_id_teams";

  public User function init(){
    teams = [];
    return this;
} //component

Team Entity

component persistent="true" extends="<path-to-base-entity-model>" table="teams" {
  property name="team_id" fieldtype="id" generator="identity" setter="false";
  property name="teamName" sqltype="nvarchar" length="50";

  public Team function init(){
    return this;
} //component

2. Querying with CriteriaBuilder and CreateAlias

In your Report entity handler Report.cfc, maybe you have an action that retrieve the information for the Report entity listing view. Let’s say this action is called list. Here’s the code to retrieve the information from the Report, Confirmation, User and Team entities:

/* Report.cfc */
component accessors="true" {
   property name="reportService"    inject="model:ReportService";
   property name="sessionStorage"   inject="coldbox:plugin:SessionStorage";

   function preHandler(event,action){
   public void function list(event){
      var rc = event.getCollection();
      var cr = reportService.newCriteria();

      rc.reports = cr.list(asQuery=false);

   } //list



  • We are chaining the CreateAlias method to link the entities via their associations, so we can traverse the entities and display the required information.

3. Displaying the Information

Ok, we should now be able to retrieve all the information we needed using ColdBox CriteriaBuilder. Let’s see how we can access and display them. And let’s say we want to display the following information:

  • Report ID
  • Report Start Date
  • Staff First and Last name
  • Team Name
  • Confirmation comments

      <tr align="left">
        <th>Start Date</th>
        <th>Staff Name</th>
      <cfloop array="#rc.reports#" index="report">
          <td>#report.getStaffs().getFirstname()# #report.getStaffs().getLastname()#</td>


  • Please note the getters and setters are automatically created.
  • Staffs, Teams and Confirmations are ORM associations, and hence their respective getters are:
    • getStaffs()
    • getTeams()
    • getConfirmations()

How to export to csv, pdf and more using DataTables

Ever wanted to easily export tabular data as csv, pdf, Excel in addition to copying and printing them with just a click in a ColdBox or any web applications and sites? Well, you can by using jQuery and DataTables, and it is as easy as 1-2-3:

  1. Link to the libraries
  2. Initialise the table and buttons
  3. Test the buttons

Link to the Libraries

In the html page head add the following styles for the DataTables table and buttons:

   <link rel="stylesheet" type="text/css" href="">
   <link rel="stylesheet" type="text/css" href="">

And in the body, link to the libraries:

   <script src=""></script>
   <script src=""></script>
   <script src=""></script>
   <script src=""></script>
   <script src=""></script>
   <script src=""></script>
   <script src=""></script>
   <script src=""></script>
   <script src=""></script>

Initialise the table and buttons

To initialise the table with an id of summary, and add the buttons (copy,csv,excel,pdf,print), add this JavaScript snippet towards the button of the page:

$(document).ready(function() {
      dom: 'Bfrtip',
         lengthMenu: [
            [ 10, 25, 50, 100, -1 ],
            [ '10 rows', '25 rows', '50 rows', '100 rows', 'Show all' ]
         buttons: [
               extend: 'csv',
               title: 'Summary'
               extend: 'excel',
               title: 'Summary'
               extend: 'pdf',
               title: 'Summary'


  • lengthMenu in combination with pageLength – rows per page to display options – i.e. 10,20,50,100 per page etc
  • extend and title allow us to specify the title to use for display and file name for the csv, Excel and pdf buttons
  • dom parameters (turn on/off – present means it’s on):
    • B – buttons
    • f – filtering input
    • r – processing display element
    • t – The table!
    • i – Table information summary
    • p – pagination control

Test the buttons

Test each of the following buttons:

  • Copy
  • CSV
  • Excel
  • PDF
  • Print

Here’s what you should see if you click the Copy button: