Great Drupal Functions

Oliver Walker
Added by: Olly
Posted on: Friday, 23rd April '10
Filed under: Drupal

You often see lists of great Drupal modules, Lullabot frequently do podcasts about popular modules, and recently at Drupalcon San Francisco, there was a session on the Top 100 useful contributed modules. Continuing in the same theme, I thought I'd write about some Drupal functions that are super useful and find myself using frequently. Hope this is helpful and I'm sure this will spawn further blog posts in the same vein. If you have any favourites, be sure to add them (and a description if you like) in the comments below.

I'm a themer and site builder. What does this mean? I take functional and architecture documents, take photoshop design files and with them I build websites. Thus I spend a lot of my time in the theme layer, a lot of my time at the Drupal interface coalface, and also time creating custom modules to deliver specific functionality and utility. The functions listed below might be boring, but they're the functions I find myself using over and over again. I've tried to detail how I use them too. If I've made any mistakes, please do correct me in the comments section below.

Note: I've purposefully left out preprocess and hook functions as I feel these are worthy of their own seperate blog posts, which I'll be writing in due course.

Path

Drupal paths can be fiddly. Especially if you're moving your site from development to production to live servers and paths and directories are changing. Using Drupals internal path and linking functions will keep you from running into trouble.

drupal_get_path()

Need to link to a file in a theme or a module? This is the function for you. This function will provide you a link to a drupal location, such as a directory of a module or theme. For example, including a javascript file in a module.

$path = drupal_get_path('module', 'MY_MODULE_NAME') . '/js/my_javascript.js');
drupal_add_js($path, 'module');

Find out more: http://api.drupal.org/api/function/drupal_get_path/

l()

I've listed the drupal linking function 'l()' under Path because I find the real value in using this function is that it ensures the path is correct, and also will create a path alias (if pathauto is installed and enabled). That's how I stumbled into this function, way back in the day. I was creating links using code like:

print '<a href="/path/to/my/page">Title Text</a>';

With code like this, things can go bad quickly. The following would break this link:

  • You move your site into a sub directory such as example.com/_newsite/path/to/my/page
  • You edit the page and change the title, changing the path

Let's say path/to/my/page is an alias for node/55. The best way to write this link would be:

print l(t('Title Text'), 'node/55');

Of course, the l() function is sexy for so many other reasons too, for example it will automatically add an 'active' class to the link if the link is, well, active. Find out more: http://api.drupal.org/api/function/l

Other honourable mentions:

file_directory_path() - get the path to your files directory, module_load_include() - load an included file for your module.

Database

If you're writing queries to the database in Drupal you have to, HAVE TO, use the database abstraction layer. Find out more here: http://api.drupal.org/api/group/database. Also, if you're writing database queries, you should be putting your code into a custom module, or at the very least a theme preprocess function. Never put database queries direct into template files or functions.

db_affected_rows()

Want to find out how many rows were returned from your last database query? This simple function tells you how many results. Not exactly the rockstar of Drupal functions, but I do use it quite a bit. Read more: http://api.drupal.org/api/function/db_affected_rows.

db_query()

Use this function to query the database. There are other, similar functions out there (e.g. db_query_range, which retrieves a limited set of results), that you will use for more specific functionality, but more often than not, if you're querying the database, you will find yourself using this function.

$sql = "SELECT * FROM {files} f WHERE f.nid = %s";
$result = db_query($sql, arg(1));

Find out more: http://api.drupal.org/api/function/db_query

Themeing

drupal_flush_cache()

For me, I find the process of clicking the clear cache button on admin > settings > performance frustrating and time consuming when themeing out a website. Even using the devel module, you have to click something on the website to clear the cache. It's always clicking: click, click, click. And flushing the cache is something that you do very, very frequently during the development of a site. You know the drill, you create a new template file and the theme doesn't register the template file without the cache being flushed; so you have to flush the cache.

I add this function to the top of my template.php file. When it's uncommented, every time the page reloads, the cache will be flushed. Comment the function call out to stop this from happening. I just find this way easier than having to click buttons to clear the cache.

//commented out the function won't run, e.g.
#drupal_flush_cache()

//uncommented, the function will flush the cache every time the page is reloaded
drupal_flush_cache()

NOTE! Do not leave this in a production website - especially uncommented and activated! Read more: http://api.drupal.org/api/function/drupal_flush_cache

theme_item_list()

You've got a bunch of items or links, and you want to output them nicely as an html list. Save yourself the trouble of writing for loops and mixing markup and php code, and pass this delicious function a php array of your links, and let it do the heavy listing.

//define list title (optional)
$list_title = "MY LIST";

//define list type (defaults to ul)
$list_type = 'ol';

//define list attributes - pass an array of html attributes
$list_attr = array('class' => 'mylist', 'id' => 'mylistid');

//define array of list items
$items = array();
//list items can be straight text or a link, for example:
$items[] = t('Hello World');
$items[] = l('Hello World', 'node/123');
//list items can also be passed classes and other attributes, for example:
$items[] = array('data' => t('Hello World'), 'class' => 'mylistitemclass');
//list items can be nested using a sub array of children items
$children = array('child 1', 'child 2', 'child 3');
$items[] = array('data' => 'Parent', 'children' => $children');

//output your list items
print theme('item_list', $items, $list_title, $list_type, $list_attr);

Read more: http://api.drupal.org/api/function/theme_item_list/

theme_table()

I will spare you the gritty details, but if you want to render a nicely formatted table (complete with all the bells and whistles a drupalized table provides), use this function rather than taking the time to loop through your data and render your own. Much like the theme_item_list() function above, this function takes a bunch of arrays as parameters, and does the heavy lifting. Useful for tabular data. http://api.drupal.org/api/function/theme_table/

dpr() *requires devel module

If there were a Drupal Module Olympics, and perhaps there should be such a thing, then for my money the Devel module would be right up there with Views and CCK. It would mostly be up there for the dpr() function, which I use relentlessly throughout the development of a Drupal website. If you ever find yourself trying to physically shake your computer to loosen the $node variable to see what's inside it... "it's INSIDE the computer"... then this is the module for you. In a template or module file, or even in a block you can use this function to find out what's inside those mystical drupal objects and arrays:

//show contents of a node
dpr($node)

//show contents of the variables inside a preprocess function
function yourtheme_preprocess_page(&$vars) {
  dpr($vars);
}

Of course, the devel module gives you bags more than just 1 function. Install it to find out more!

Node

It's always handy to know some basic node handling functions. You might not use them a lot, but it helps to have an awareness of them. If you've ever tried loading a node yourself with custom SQL queries, it's probably something you'll never want to do again. These simple functions will help:

node_load()

You've got a node id, or some parameters that you want to load a node from (title for example). This function will load up the node for you:

if(arg(0) == 'node' && is_numeric(arg(1)) && !arg(2)) {
  $mynode = node_load(arg(1));
}

Handier than a bag of spanners: http://api.drupal.org/api/function/node_load

node_view()

You've loaded your node, and now you want to generate a display of a node, either a teaser or a full page: This function does just that. http://api.drupal.org/api/function/node_view

node_teaser()

Here's a really useful function. You have some content, that may or may not contain markup and you want to truncate that content to create a shortened version or 'teaser'.

//input format - filter your content as per your input format settings
$input = 1;

//size - the characted lenght you want the content truncated to
$size = '400';

node_teaser($my_content, $input_format, $size);

More! http://api.drupal.org/api/function/node_teaser

 

And so that pretty much wraps up this list. I hope it's useful to someone. As I've wrote this I thought of a good number of other functions that should have made the cut. Add your favourite functions, comments and feedback using the comment form below.