EntityFieldQuery: Let Drupal Do The Heavy Lifting (Pt 2)

In the first part of this introduction to EntityFieldQuery, we looked at how simple it was to quickly construct a query with only a few lines of code. In this second part of the series, we’ll take a look at some more practical ways to put EntityFieldQuery to use.

Our Example Module

For the purposes of this series, I’ve created a simple module, EntityFieldQuery Example, that demonstrates some uses of EntityFieldQuery. It’s hosted on Github; you can grab the source code if you’d like to see the code in more detail or if you’d like to install it yourself.

Some quick notes about what the module contains: in addition to the callbacks and block code described below, the module installs three node types, efq_article, efq_page, and efq_photo. These are very simple node types: efq_article and efq_page each contain a body field for text, while efq_photo contains a single image field. In addition, all three content types contain a US States field, which we’ll be using to construct our example queries.

I recommend using Devel content generate to quickly generate content for your examples, although you can of course create it manually if you like. For the purposes of my examples, I created 200 nodes using the following command:

When you uninstall this module, it will clean up after itself, removing all created content. I’m thinking of teaching this technique to my cats.

Extending EntityFieldQuery

One of the first things to to remember about EntityFieldQuery is that it is a proper PHP class. The means that you can extend its behavior to suit your needs. For example, when using EntityFieldQuery, you might find that you are often trying to find nodes. If you are trying to find content that you will be listing in public pages and blocks, you probably want it to all be published. Additionally, lists of content tend to be published with the most recent content first.

Let’s create our own version of EntityFieldQuery, NodeEntityFieldQuery, with these properties already set:

This is fairly straightforward. Each time we create a new NodeEntityFieldQuery, a number of things will be already pre-set for us, namely that we’re searching for published nodes and we want them returned in a reverse chronological order. Additionally, we instantiated a pager, since we’ll most likely want one. If we find ourselves using NodeEntityFieldQuery over and over again, we will save ourselves some time by having all these values pre-set.

Also note that we can extend the class with our own methods. We’ll come back to that method later.

A Simple Listing Page

Let’s start by creating a simple listing page. This is going to list all nodes of our three example content types in reverse chronological order, as well as providing a pager. First, we’ll need to define a menu item and callback for our page:

Now we can start our callback to provide the listing for us. We’re going to keep this very basic to start with: we’re just listing all the nodes of our three types, that are published, in reverse chronological order.

That’s all we need to do to provide us with a listing page with a pager. It’s not exactly Drupal For Dummies, but it really isn’t terribly difficult, and in particular it’s very few lines of code to get that result.

Adding Arguments

Of course, it would be more interesting if we could filter this list some. Let’s add some arguments to our callback. Our current URL is at efq. Let’s set it up so that we can use URLs in the form efq/%state/%node_type as well. We’ll have to set up our callback such that both state and node_type are optional, and to be aware of the arguments if they’re present.

Our new callback isn’t substantially different:


In our new callback, we look for a value for $state, and if it is present, we add a fieldCondition to our query. Additionally, we set up $node_types with a default value of an array of all of our content types, and look for a changed value. Note that the condition code is flexible:

$node_types can be an array, as is the default, or it can be a string, which is how it will come in from the URL. That’s fine; the condition will adjust to the type of argument you pass.

Building a Content-sensitive Block

So now we have a listing of our content, and it can accept arguments. It would be nice also if, on our individual nodes, we could find other content for our given state. Let’s construct a block that shows the five most recent items from that node’s state. Additionally, we should probably provide some links back to the listing pages, again based on state.

Constructing the framework for the block itself is basic Drupal:

Now of course we need to populate that block. Here’s the function that will do that for us (don’t worry, we’re going to break this down):

Let’s break this down a bit.

The beginning of this is quite straightforward. If we don’t have a node, there’s no point in continuing. Also, we need the node to have a state value, or else there isn’t any point in looking for state content for our block.

This looks very similar to our page listing query. We define a new query via NodeEntityFieldQuery, let the query know what kinds of nodes we’re looking for, and give it the value for the state field. Additionally, we’re limiting the number of results returned to the 5 most recent, since this is a block.

One thing you might want to consider is that you may not want the results listed in the block to include the node you’re currently on. This makes sense: if you see the same page you’re already reading listed in a sidebar, it can feel sloppy, or else like you’re having your time wasted.

Luckily, it is not hard to do this. Remember when we extended EntityFieldQuery to create NodeEntityFieldQuery? Remember this bit?

We can add our own methods to our new class. Let’s do that now.

This is a fairly simple method. If you pass in a node ID it will use it; otherwise it will attempt to use the node ID on the page you’re currently on. If you’re using EntityFieldQuery to search for nodes, and there is a node ID, this method will tell your query to exclude the current node. The key item is this line:

Note the “<>” operator. Normally if you’re looking to match a value or set of values, you can leave the operator out of your propertyConditions, fieldConditions, etc., because they’re set to “=” or “IN” by default, depending on whether you have a single value or multiple that you’re matching against. If you want to use a different operator for your condition, you have to enter it explicitly.

Now that we have our method, we just need to add a quick method call to our block callback function, and we’re set:

Most of the rest of the callback looks quite similar to our page listing callback:

We execute our query. We set the block title, since that is going to be the same whether we had content or not. If there are results from our query, we load them and then slot them into the block content.

We do generate a set of links to allow the user to get back to the page listings easily:

And finally, because we’re relatively thorough, we write a simple message to the block if not results are returned:

This Looks Kind Of Familiar…

If you’re an old Drupal hand, you might be wondering why I wouldn’t just build this in Views. Indeed, this might look a bit masochistic if you’re used to Views. However, there are a few things to consider:

  1. EntityFieldQuery is core. If you are interested in keeping your installation as lean as possible, this is something to consider. Views is a contributed module, and so it automatically adds size and overhead to your Drupal install.
  2. EntityFieldQuery is small. The amount of code required to generate an equivalent listing in Views, compared to what we built above, is much, much greater. To be fair, your Views code will almost certainly be exported and managed via Features, and so in effect you’re not writing the Views code anyway. But, that highlights a different point: writing code this way keeps you in code, rather than requiring you to work in a point-and-click interface. For the average developer, this is a very good thing.
  3. EntityFieldQuery is code. You might want to have certain things exposed to change and not others. For example, on a recent project, we were building a site for a client that had site builders on staff. These people were comfortable working with Views, and we wanted to make sure that they had the ability to create and modify views. However, we wanted to also make sure that there was some core functionality that was left untouched. If we had built that core functionality with Views, it would have been exposed to change. By building that core functionality with EntityFieldQuery, we kept it strictly in code, which protected it.

Summing Up and Coming Up

There is a lot of code in this post. If you are interested in understanding this better, I recommend installing the sample module, creating some test content, and playing with the code. I think much of the code is a lot easier to understand in context.

In our next post, we’ll look at some more advanced EntityFieldQuery techniques. We’ll also look at scenarios when EntityFieldQuery is a good candidate for the job, and some scenarios when EntityFieldQuery is not what you want to use.


Want more EntityFieldQuery? Check out ‘OR’ Queries with EntityFieldQuery from Fredric Mitchell.

  • Jerome Covington

    Thanks, this and the previous article in the series is helping me to see when using EFQs are more appropriate than using Views, as well as the power of this type of class based query building.

  • spoetnik

    Amazing. Looking thru the code, reading this post, and clicking my demo-site helps a lot to tackle this entityfieldquery thing.