Category Archives: Module Development

Adding a JavaScript/CSS Library to Drupal with the Libraries API

Let’s say we found a useful bit of JS or CSS that we’d like to use within our Drupal site.  For example, this jQuery ListNav Plugin.  An ideal way to accomplish this is by adding it to Drupal’s Library API.  Here’s how to do it.

First, make sure you have the Libraries API module installed and enabled.

Next, we’re going to write a custom module that implements hook_libraries_info() to add our custom library to Drupal’s set.

The jquery_listnav.info file:

and the hook_libraries_info() implementation within jquery_listnav.module:

First, we create a new $libraries array and then define a key => value pair within $libraries for our new library.  The key is the name of our new library within Drupal’s eyes — in our case it’s “jquery-listnav”.  The value is another array of information about our new library.

We’ve defined the following bits of info about our library:

  • name
  • vendor_url
  • download_url
  • version_arguments (which is itself yet another array)
  • files (which is itself yet another set of multi-dimensional arrays)

The former three (name, vendor_url, and download_url) are pretty self-explanatory but let’s dig into the latter two.

The ‘version arguments’ key tells Drupal where it can find information about the library’s version.

The ‘file’ key points Drupal to where the file is located.  In this case, since our library is only one file, the version is contained therein.  If your library consists of many different JS and/or CSS files, you may have an .info file which contains the version data or it may be in only one of the files.

The ‘pattern’ key is a regex expression that tells Drupal how to find the version of the library (if any exists).

The ‘lines’ (optional) key tells Drupal the maximum number of lines to search for the aforementioned regex.  It defaults to 20 so if you know your version is always on line 1 (say, in a minified version of the code in question), you can save some cycles by specifying such here.

Next, the ‘files’ key is the crucial data point as it tells Drupal where to find the files that should be included in this library.

The ‘js’ key is yet another array that contains the file names of JS files to include in this library.  We’ve packaged the JS file in the same directory as our module but it could easily be in the theme itself.

The ‘css’ key is the same as the ‘js’ key but for CSS files.

There are quite a few more available keys in the $libraries array definition including declaring dependencies and utilizing external libraries.  You can read more about them on the Drupal 7 API Reference page for hook_libraries_info().

Finally, one last thing I’d like to cover is how to load a library and add it to a specific page.

I’d like this library to load on all displays of a specific view named ‘directory’.  So in my template.php file in my theme, I implement theme_views_pre_render() and create an if-block for that case.

Then I call:

to load the library we created earlier.  Now that that JS is available, I call drupal_add_js() to run the pertinent JS function.

Sometimes we’ll want a library loaded and available on all views, or all pages.  In that case, you could employ the same tactic but remove the if-block from the theme_views_pre_render() call.  You could even do it in something like hook_init().

How to Add a Custom Shortcode to Drupal 7

We recently received a request to embed some JavaScript for a live chat client into multiple pages within our site.  The live chat service provided the JS code snippet to our team along with the ID key we would need to use within the snippet to link the client on our pages with the live-chatters on the other side.  There were also a few settings that could be changed within the snippet — things like background color, offset width, and location on the page.

Since we do not allow JavaScript tags within our WYSIWYG editor, we couldn’t just ask our Content Managers (CMs) to copy/paste the snippet right into the Body (or other) field.  We also didn’t want to be called upon everytime the script needed to be embedded on a different page or when the ID key changed due to a new marketing campaign (or any other reason).  We decided to use Shortcodes.

Shortcodes are little bits of code that, when parsed in a field that allows them, expand to a pre-defined output, replacing any pre-defined variables in the expansion.

For a quick example, a shortcode for embedding a link to Google may be:

When that string is parsed in a shortcode-enabled field, it might render as:

This is useful because, if the link to Google were to ever change, any number of instances of the shortcode can be updated all at once by one modification to the Shortcode code.

As I mentioned, Shortcodes can also take variables.  For example:

might expand to

This tutorial requires the contrib module Shortcode.  We’ll write a custom module to extend its functionality and add a new shortcode. Here’s how to do it.

First, let’s create a module.  I’ll call mine “tmbridge_custom_shortcodes” and, thus, create a directory, tmbridge_custom_shortcodes, in my custom modules directory and two files, tmbridge_custom_shortcodes.module and tmbridge_custom_shortcodes.info, in that directory.

I won’t speak to writing the info file in this post, but you can refer to this page on d.o for more information.

The first thing we need to do in this new module is name and describe our new shortcode and indicate the callback functions it will use:

We need to define the variables (or attributes) for our new shortcode.  We do this by implementing hook_theme():

Next, let’s define our callback function for the new shortcode.  This callback function takes the variables as defined by the user in the shortcode’s use in the WYSIWYG editor and applies any business logic, formatting, or modification (like setting a default, if empty):

Now, we need to define the theme function that our process callback function calls.  In this case, it’s simply ‘shortcode_friendly_alert’.  This theme function returns the output of the shortcode with the variables replaced.  Here’s where the magic of this module happens.  You can put literally any markup you wish into this function’s output and populate as many variables within it with user-defined data (this means you could get data from any Drupal object that’s in scope, as well).  It could be JavaScript (including AJAX functionality), CSS, output from other theme functions (blocks, views, etc.), Or… just run of the mill HTML markup.

In this tutorial, we’re just using some (really) basic JS and HTML to make the point, but I really want to drive home the wide breadth of functionality one could implement herein.

Finally, let’s define our tip callback.  This function outputs text below the WYSIWYG editor that tells the user what the shortcode is used for and shows the user what parameters are available.

And that’s it for the code!  Simply enable the module and be sure to remember to enable the new shortcode in all the Text Formats you’d like it available within (/admin/config/content/formats).  The available shortcodes are listed in the vertical tab “Shortcodes” under “Filter Settings:

Enabling Shortcode in Text Format Settings
Be sure to enable your new Shortcode in the Text Format settings

You will then see your new shortcode available in all fields that use those Text Formats.

Your new shortcode is now available in all WYSIWYG fields that use those Text Formats.
Your new shortcode is now available in all WYSIWYG fields that use those Text Formats.

 

Integrating Webforms with Open Atrium’s Panes by Creating a Custom CTools Plugin

Open Atrium (OA) core utilizes PanelizerFieldable Panels Panes, and CTools to give content managers (CM) a convenient UI for adding new and existing content to a node.  Open Atrium core also includes the Webform contrib module but, unfortunately, neither is it panelized nor is it ready as a CTools content type out-of the box.

This means that (a) core OA does not allow a CM a way to add other panes to a webform node and, thus, no way to add panes native display.  In this post, we will outline how to add a new content type to CTools and how to define that new content type.

First, we need to create a module.  I’m calling mine:

So in my modules/custom directory, I’ve created a directory:

and files:

Of course, you’ll need to write your info file but I’m sure you know that already!  Now we need to tell CTools where to find our plugin files so my module file looks like:

This is boilerplate code that implements hook_ctools_plugin().  It tells CTools to look in directory “plugins” for plugin files when looking for content types.

Within the tmbridge_webform_panes directory, next to the tmbridge_webform_panes.module, let’s create a “plugins” directory and inside that, let’s create a “content_types” directory.  My directory structure now looks like:

CTools knows to look for include files within the directory that is returned from the call to hook_ctools_plugin_directory() so let’s create an include file within the content_types directory.  We’ll call it tmbridge_webform_panes.inc.  Our directory structure now looks like:

The first thing we need in this file is a $plugin array definition that outlines what this plugin does:

Many of these elements are self-explanatory.  The first element, single, tells CTools that this plugin has 0 subtypes.  The next three elements are string definitions that will appear in the UI for CMs.  The latter four elements define the callback functions that will be called when this plugin’s code is run.  Next in this post, we’ll get to the meat-and-potatoes of writing a CTools plugin: callback functions.

We need to determine which types this plugin should be able to render.  Since we are concerned with webforms, we’ll query the database for all subtypes that have webform components and build an array containing that set:

Next, we’ll build the edit form that presents available options to the user by writing the callback function that we defined earlier in the plugin array.

We are only concerned with the webform to embed in this plugin, but this function can be extended to include any kind of user-defined settings you may need.

You may notice that in this callback function, we make a call to a helper function called _webform_panes_get_all_forms($subtype).  This is a custom auxiliary function defined as follows:

Something to note in this function is the line:

This is how we limit the select options on the edit form to include only nodes to which the user has access.  If our use case called for it, we could instead look here for the node_edit permission and only allow a user to include a webform to which they have edit access.  We’d like users to embed any forms to which they have access so all we are looking for is node_access.

Next, we define the form submit callback which saves the form state information:

Finally, we can talk about rendering.  The render function below creates a block from the selected webform and defines the view mode that will be used to render said node.

We check here if the pane has an override title defined and, if not, we use the webform node’s title as default.  A check for permission is made here as well.  We also take this opportunity to populate the $settings variable with a flag that will be used in the corresponding template to easily check if this block is a webform block.

We also define here the theme hook to use to build the block content.  This is completely dependent on the theme you are using, I’ve opted for a custom hook defined in my theme but use whatever suits your needs (we’ll talk more about creating a custom theme hook to use here in another post.).  You can find more information on the theme() function in drupal.org’s API documentation.

And, with one last function, we define the administrative title that will be used for a webform in a pane:

And voilà! We now have a new content type available to CTools to embed a webform within a pane on any Panelized node’s display.  The plugin pulls all accessible webforms into a select box and allows the user to select from that list:

Webform content type selection process -- step 1 and 2
We now have a Webform content type defined for use within Open Atrium.
Webform selection process -- step 3
And we can select from a list of all the webforms to which we have access

Of course, Open Atrium has native functionality to embed blocks and, at least with Webforms 3 and up, we can configure all webform nodes to automatically create an associated block — however, a custom CTools plugin yields a more comfortable user experience for CMs as Webforms are considered a distinct content type.  It also allows more customization of and during the rendering a webform.

Another alternative to a custom CTools plugin would be to “Panelize” the entire Webform content type.  This would allow CMs to add other panes to a webform node itself.  This comes with its own set of pros and cons.  I will cover this process along with its pros and cons in another post.

A corollary to creating a plugin for a new CTools content type is to create a new pane style plugin for CTools.  Combined together, a content type plugin and a style plugin can yield some great functionality.  I plan to write another post on that subject soon.

CTools plugins are incredibly powerful.  The above tutorial is merely one use case but the methodology and structure is consistent across the board.  Be sure to keep them in your toolchest for when a need may arise.