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.

<head>
  <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" />
</head>
<body>
  <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>
</body>

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">
  <cfscript>
    var qGet = "";
    var clientsList = [];
    var stClients = "";
  </cfscript>
  <cfquery name="qGet" datasource="clients">
    SELECT
      clientid, title, firstname, lastname
    FROM clients
  </cfquery>
  <cfscript>
    //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;
  </cfscript>
</cffunction>

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="">

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

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

         //on auto suggest
         $(this).autocomplete({
            source: sourceValues,
            select: function(event, ui) {
               selectedObj = ui.item; 
               $(this).val(selectedObj.label);
               $('#'+ 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
            }//change
         }); //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')
      suggestInput(clientsList,'client-suggest');
}); //document.ready
</script>

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;
   top:6px;
   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:


$('#<your-form-id>').formValidation({
   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'
            }
         }
      },//firstname
      lastname: {
         validators: {
            notEmpty: {
               message: 'Last Name is required and cannot be empty'
            }
         }
      }//lastname
   }//fields
});

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>
   </div>
   <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">
      </div>
   </div>
</form>

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):


<html>
<head>
<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" />
</head>
<body>
   <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>
</body>
</html>

 

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 */

email.setBodyTokens({
  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(
   from=configBean.getKey('emails').senderEmail,
   to=configBean.getKey('emails').recipientEmail,
   subject= "User Details"
 );

 var stInfo = {};
 stInfo.title = "Cool Programmer";
 stInfo.firstname = "John";
 stInfo.lastname = "Doe";
 stInfo.email = "John.Doe@supercool.com";

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

 // 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:


<p>
#args.firstname# #args.lastname#<br>
#args.title#<br>
#args.email#
</p>

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();
cr.add(
   cr.createSubcriteria('report','subrpt')
   .withProjections(property="report_id")
   .createAlias('subrpt.confirmations','subconf')
   .createAlias('subconf.staffs','substaffs')
   .createAlias('substaffs.teams','subteams')
   .isEq('subteams.teamName','Developers')
   .propertyNotIn("report_id")
);

Notes

  • 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

Notes:

  • 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
  local.email = MailService.newMail().config(
    from=configBean.getKey('sysEmail'),
    to=arguments.user.getEmail(),
    subject= emailTitle
  );

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

  // Add HTML email
  local.email.addMailPart(charset='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

Notes:

  • 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:


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

Notes:

  • 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++){
        notifyUser(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();

      cr.createAlias('confirmations','c').createAlias('c.users','u').createAlias('u.teams','t');
      rc.reports = cr.list(asQuery=false);

   } //list

}//component 

Note:

  • 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

<cfoutput>
  <table>
    <thead>
      <tr align="left">
        <th>ID</th>
        <th>Start Date</th>
        <th>Staff Name</th>
        <th>Team</th>
        <th>Comments</th>
      </tr>
    </thead>
    <tbody>
      <cfloop array="#rc.reports#" index="report">
        <tr>
          <td>#report.getReport_id()#</td>
          <td>#DateFormat(report.getStartDate(),"dd/mm/yyyy")#</td>
          <td>#report.getStaffs().getFirstname()# #report.getStaffs().getLastname()#</td>
          <td>#report.getTeams().getTeamName()#</td>
          <td>#report.getConfirmations().getComments()#</td>
        </tr>
      </cfloop>
    </tbody>
  </table>
</cfoutput>

Notes

  • 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:


<head>
   <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css">
   <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.2.2/css/buttons.dataTables.min.css">
</head>

And in the body, link to the libraries:


<body>
   <script src="https://code.jquery.com/jquery-1.12.3.js"></script>
   <script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
   <script src="https://cdn.datatables.net/buttons/1.2.2/js/dataTables.buttons.min.js"></script>
   <script src="https://cdn.datatables.net/buttons/1.2.2/js/buttons.flash.min.js"></script>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/2.5.0/jszip.min.js"></script>
   <script src="https://cdn.rawgit.com/bpampuch/pdfmake/0.1.18/build/pdfmake.min.js"></script>
   <script src="https://cdn.rawgit.com/bpampuch/pdfmake/0.1.18/build/vfs_fonts.js"></script>
   <script src="https://cdn.datatables.net/buttons/1.2.2/js/buttons.html5.min.js"></script>
   <script src="https://cdn.datatables.net/buttons/1.2.2/js/buttons.print.min.js"></script>
</body>

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:


<script>
$(document).ready(function() {
   $('#summary').dataTable({
      dom: 'Bfrtip',
         lengthMenu: [
            [ 10, 25, 50, 100, -1 ],
            [ '10 rows', '25 rows', '50 rows', '100 rows', 'Show all' ]
         ],
         buttons: [
            'pageLength',
            'copy',
            {
               extend: 'csv',
               title: 'Summary'
            },
            {
               extend: 'excel',
               title: 'Summary'
            },
            {
               extend: 'pdf',
               title: 'Summary'
            },
            'print'
         ]
   });
});
</script>

Notes

  • 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:

csv-pdf-datatables-2a