18.10.2016 Views

Drupal 7 Module Development

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 7<br />

To demonstrate how entity and field queries work, let's start by creating a new menu<br />

item to list recently created artworks. We'll put it in the artwork module for now.<br />

function artwork_menu() {<br />

// ...<br />

$items['artwork/recent'] = array(<br />

'title' => 'Recently added artworks',<br />

'page callback' => 'artwork_page_list_recent',<br />

'access arguments' => array('view artworks'),<br />

'file' => 'artwork.pages.inc',<br />

);<br />

}<br />

return $items;<br />

Just as <strong>Drupal</strong> provides a query builder for SQL databases that abstracts<br />

database-specific logic, it also provides a query builder for Entities and Fields.<br />

The API for it is a single class named, boringly enough, EntityFieldQuery.<br />

Before we have a look at EntityFieldQuery directly, let's take a step back and<br />

consider what sorts of things we can search on. At the conceptual level, there<br />

are three "levels" of data by which we can filter:<br />

• Entity level data: It is data that is common to all entities of all types. This<br />

includes the entity type itself, the bundle name, the entity ID, and the<br />

revision ID (if applicable). All entities of any type will have these items.<br />

• Properties: They are those data elements that are common to all objects of<br />

a given entity type, but not to all entities. That is, they are pieces of data<br />

common to all nodes, or to all users, or to all artworks. Examples include the<br />

'node title' and 'creator uid' for nodes, user 'login name' for user entities, and<br />

the 'artwork title' and 'creation date' for artworks.<br />

• Fields: They are, of course, specific to a given bundle definition (painting or<br />

sculpture). However, they may also be shared by entities of different types.<br />

When searching for entities, we can filter by or order by data at each of those levels.<br />

Not all combinations make sense, however, and the query will reject nonsensical<br />

combinations by throwing an exception.<br />

Since we cannot know what the storage engine or engines are that an entity uses, that<br />

too limits the complexity of the searches we can do. For instance, we are only able to<br />

do "AND" searches, not complex conditions with OR. We also cannot search across<br />

different data stores. Nonetheless, that still leaves a huge range of use cases that can<br />

be solved very easily.<br />

[ 207 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!