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.

Creating New Fields<br />

Always use EntityFieldQuery when selectively searching for entities.<br />

Never try to query the database directly, as there is no guarantee that<br />

there is a relational database involved.<br />

Let's start with simply showing the five most recently created artworks:<br />

function artwork_page_list_recent() {<br />

$content = array();<br />

$query = new EntityFieldQuery();<br />

$query<br />

->entityCondition('entity_type', 'artwork')<br />

->propertyOrderBy('created', 'DESC')<br />

->range(0, 5);<br />

$result = $query->execute();<br />

$artworks = artwork_load_multiple(array_keys($result['artwork']));<br />

foreach ($artworks as $artwork) {<br />

$content[] = artwork_page_view($artwork, 'teaser');<br />

}<br />

}<br />

return $content;<br />

We start by creating a new query object. We then call methods on it, to filter by<br />

"entity type is 'artwork'", and then "order by the 'created' property, newest first"<br />

(that is, descending order). The range() method, just like DB queries, takes the<br />

start position as its first parameter and the count as its second.<br />

If we assume an SQL database, the resulting SQL will look something like<br />

the following:<br />

SELECT artwork.aid AS entity_id, artwork.vid AS revision_id, artwork.<br />

type AS bundle, 'artwork' AS entity_type<br />

FROM<br />

artwork artwork<br />

ORDER BY artwork.created DESC<br />

LIMIT 5 OFFSET 0<br />

The advantage here is that, should the author of the artwork module change the<br />

table structure on us, or if artworks were stored in a non-SQL data store, the SQL<br />

query above would break horribly but the EntityFieldQuery would continue to work<br />

because <strong>Drupal</strong> builds it dynamically based on what we're searching for.<br />

[ 208 ]

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

Saved successfully!

Ooh no, something went wrong!