18.10.2016 Views

Drupal 7 Module Development

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Creating New Fields<br />

Again, there's no guarantee that we're even dealing with an SQL database. Aren't<br />

you glad we're letting <strong>Drupal</strong> figure all of that out for us?<br />

It is also possible to do more complex queries on fields, for instance, the<br />

following one:<br />

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

$query<br />

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

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

->fieldCondition('field_artist', 'value', 'Da Vinci', 'CONTAINS',<br />

0)<br />

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

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

In this case, instead of using a simple "is exactly equal to" comparison, we are<br />

asking for any entity whose field_artist field has the string "Da Vinci" in it<br />

anywhere. That allows us to match both "Da Vinci" and "Leonardo Da Vinci". The<br />

fifth parameter lets us restrict results to just those fields that have "Da Vinci" as<br />

their first instance (remember, 0-based) if they are multi-value.<br />

There are of course corresponding entityOrderBy(), propertyCondition(), and<br />

fieldOrderBy() methods for building up more interesting field queries. See the<br />

inline documentation in includes/entity.inc for the full range of options.<br />

Summary<br />

We have now completed a module that touches on the three most important parts of<br />

the Field API. We've created a new field type to store data, corresponding widgets<br />

to allow users to edit it, and formatters to control how that data is displayed when<br />

the entity the field is attached to is viewed.<br />

Although our use cases were reasonably simple, <strong>Drupal</strong> allows arbitrarily complex<br />

Widgets and Formatters. Some Widgets can interact with the URL or third party<br />

data sources to handle default values, or perhaps show a completely different set of<br />

form fields under certain conditions. Formatters can use the theme system to display<br />

data themselves or leverage JavaScript libraries to create interactive visualizations of<br />

the data stored in a field. With swappable storage engines, advanced use cases can<br />

even load data from another database or server entirely, including one that does not<br />

involve SQL.<br />

[ 210 ]

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

Saved successfully!

Ooh no, something went wrong!