Blog Archive

Thursday 24 January 2013

Adding autocomplete to a simple module field in FUEL CMS

This quick tip follows on from Add a JQuery plugin to FUEL CMS module admin page.

FUEL CMS v1.0 uses JQuery's UI library  in the admin by default. This means features like auto-complete, or auto-suggest if you prefer, are very easy to add to simple modules.

In your model, add the form_fields() function if it is not already present, and choose the field in the model you wish to add autocomplete to - in this example, I'm going to suggest emails in an email field called "contact_email":

$fields['contact_email'] = array(
    'class' => 'email_suggest', 
    'comment' => 'Known emails will be suggested as you type'
); 
 
The array configuration here is minimal, we are just attaching a CSS class to the field, and adding a comment so that hovering over the label in the form will show the comment as a tooltip. More field options are shown on this page.

Since suggesting emails to the user when filling in an email field is so useful, I want to do it for any module that has an appropriate field, so instead of adding the JQuery function to the model's Controller.js, I'm going to add it to the parent class, BaseFuelController.js, then it will be available to call from any extended class.

Find a suitable location in BaseFuelController.js to put the following (I put it at the very end, don't forget to extend the array by putting a comma before it)

email_suggest : function() { 
    $('.email_suggest').autocomplete({ 
         source: '/suggest_emails' 
    });
}
 
As per the Autocomplete documentation, this function (email_suggest) will apply the autocomplete to an element with a class of "email_suggest", and will look for data remotely in the url '/suggest_emails'.

I made a controller to return emails in a JSON array from that url, but you could use the opt-in view functionality of FUEL CMS and create a view file of the same name, thus saving a bit of typing! If the emails are private, you might want to protect them from being viewed by just anybody (ie outside of the admin). You could opt to put the url inside of the Fuel module, but that's another project.

In the Controller.js of your module (mine was an "events" module, so it was named EventsController.js), you then just need to add something like this:

add_edit: function(){
    this._super(); 
    this.email_suggest(); 

 
Since the module's Controller.js is an extension of the BaseFuelController.js, the function is called from the parent class. So for other modules that need the same feature, just add this.email_suggest(); to the add_edit() function in their Controller.js, not forgetting to define the js_controller key in MY_fuel_modules for each module you need to.

And that's pretty much it!

No comments:

Post a Comment

My top artists