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 />

3. We want to present a unified custom interface to users while editing that<br />

data, especially if it is multi-value.<br />

4. We want to display the data to the user in a custom format.<br />

All of these are reasons why we may want to write our own field code.<br />

In our case, we are dealing with artworks. Artworks have dimensions, either height<br />

and width, or height, width, and depth. Although we certainly could just add three<br />

numeric fields to our artwork bundles and call it a day, that is not very attractive<br />

either for the content editor or for site viewers. It gets even uglier if we want to allow<br />

multi-value fields; say if a given artwork is a collection of small statues or a series of<br />

similar paintings.<br />

We will therefore define a new type of field to store dimensions, either height and<br />

width, or height, width, and depth. Although in our case we are talking about works<br />

of art, the field itself would apply just as well to cars, buildings, animals, or any other<br />

content that represents an object that takes up space. A good field type is generic<br />

enough to fit many different situations.<br />

How Field API works<br />

As hinted above, there are several different complementary parts to defining a field:<br />

• Field type: this is strictly speaking, just the content definition. It defines the<br />

name of the field and what its inner data structure is, but not how to save it<br />

or how to display it.<br />

• Field: this is a particular configuration of a field type.<br />

• Field instance: this is the combination of a particular field with a bundle or<br />

subclass of an entity type<br />

• Widget: this is a form element that exposes the field to a content editor. It<br />

could use simple text fields or be something as complex as an interactive<br />

Flash-based tool.<br />

• Formatter: this is a piece of code that formats a field for display on screen.<br />

Typically it just wraps <strong>Drupal</strong>'s theme system to do so.<br />

Note that nowhere in any of the parts mentioned do we define how or where the<br />

data gets stored. That is handled by a field storage engine, which can be configured<br />

separately per field. By default all fields use a common storage engine that saves<br />

fields to <strong>Drupal</strong>'s database. That's good enough for our needs, so we won't go into<br />

field storage engines in depth.<br />

[ 184 ]

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

Saved successfully!

Ooh no, something went wrong!