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

Like most "info hooks", this function returns a large definition array, defining one or<br />

more fields. Also as we would expect, there is a corresponding hook_field_info_<br />

alter() hook. In our case, we just have the one called dimensions. Let's look at each<br />

property in turn:<br />

• label and description specify the human-readable name and explanation<br />

of this field.<br />

• settings defines an array of configuration options for the field and their<br />

default values. These settings are fixed and after we create an instance of a<br />

field cannot be changed, so use with caution. Generally you only want field<br />

settings if changing the setting would affect how data gets saved.<br />

• instance_settings is the same as the settings array, except that it can be<br />

changed after a field has been created. That makes it generally preferred over<br />

field-level settings.<br />

• default_widget and default_formatter specify what widget and<br />

formatter <strong>Drupal</strong> should use for a given field before the user specifies one.<br />

Like fields, widgets and formatters have unique string names. We'll talk<br />

about how to write those later in this chapter.<br />

The above code tells <strong>Drupal</strong> that there is a new field type called dimensions defined<br />

by our dimfield module, and gives a little metadata about it. However, <strong>Drupal</strong> still<br />

needs to know how that field is put together. For that, we implement a couple of<br />

other hooks.<br />

Defining the field structure<br />

Actually, no, we don't. Although called hooks in the <strong>Drupal</strong> documentation, these<br />

functions are pseudo-hooks: magically named module callbacks that are called<br />

individually by <strong>Drupal</strong> rather than together with that hook as used by all modules.<br />

Since our module is named dimfield, the supporting code for all of the field types<br />

we define in the dimfield module will live together in the same magic callback. For<br />

that reason, it's generally a good idea to not define too many field types in a single<br />

module as the code may get unwieldy. We also use a different name for the module<br />

and for the field type to help keep track of when we need to use which.<br />

A magic module callback, or pseudo-hook, looks like a hook, but<br />

is called individually rather than alongside implementations from<br />

all other active modules.<br />

[ 186 ]

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

Saved successfully!

Ooh no, something went wrong!