Drupal 7 Tutorial: Creating Custom Formatters with the Field API

Custom formatters are a great way to control the output of your fields. In this tutorial I’m going to use an example that takes a user’s Facebook URL as the input and outputs a button of the Admin’s choosing, along with an option to open the link in a new window. To get started, we’ll need to get a module skeleton sketched out. You’ll need to create these two files:

  • facebooklink.info
  • facebooklink.module

The first file, facebooklink.info, can be fairly simple:

We give it a name and a description and specify Drupal 7 core. We also add it to the fields group. This will group it with other field modules. The last line tells drupal where the guts are and that’s the module file.

The facebooklink.module file will be where we do the coding. There are four hooks we’ll need to get our custom formatter working.

  • hook_field_formatter_info() – This tells Drupal what fields it applies to and what settings are available.
  • hook_field_formatter_settings_form() – Here we’ll tell Drupal how to generate the form that collects the options.
  • hook_field_formatter_settings_summary() – This displays the chosen settings on the ‘Manage Display’ page
  • hook_field_formatter_view() – This is the hook where we actually do the formatting

When you start the file make sure you give it a standard module header and description:

Then we start our first hook: facebooklink_field_formatter_info

Here we’re making Drupal aware of the new formatter by giving it a machine name and setting the label, field types it will be available to, and what settings we plan to allow the admin to set. Your module could define any number of custom formatters with any number of settings.

Next up is the facebooklink_field_formatter_settings_form:

We’re now telling drupal what our form should look like when someone clicks the settings button. The form will contain a drop down labeled “Button Size” with three options (defaulted to small) and a text box labeled Tool Tip.

The next hook is facebooklink_field_formatter_settings_summary:

This hook is solely responsible for providing a summary of the formatting in the “Manage Display” page for the chosen content type. Our summary will now reflect the settings that we’ve chosen.

Now the real meat. This hook will do the actual formatting of the link.

This function collects all of our settings and does the actual formatting. We could even take this a step farther and create a theme function that could then be called from elsewhere, but these are the basics needed to create the formatter. You’ve now turned over the ability to format the end-user’s Facebook link to the client. They are pleased and give you money.

Resource: Metaltoad

Leave a Reply

Your email address will not be published. Required fields are marked *