Drupal

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


Filed under:

This article is one of Metal Toad's Top 20 Drupal Tips. Enjoy!

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:


name = Facebook Link
description = "Add a formatter to textfields that allows Admins to determine how links will be displayed"
package = Fields
core = 7.x
files[] = facebooklink.module

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:


/**
* @file
* adds a formatter for text fields that creates a facebook button
*
*/

Then we start our first hook: facebooklink_field_formatter_info

/**
* Implements hook_field_formatter_info().
*/
function facebooklink_field_formatter_info() {
return array(
'facebooklink_formatter' => array( //Machine name of the formatter
'label' => t('Facebook Link'),
'field types' => array('text'), //This will only be available to text fields
'settings' => array( //Array of the settings we'll create
'pic_size' => 'small', //give a default value for when the form is first loaded
'tooltip' => 'Link to user Facebook page', //ditto
),
),
);
}

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:


/**
* Implements hook_field_formatter_settings_form().
*/
function facebooklink_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
//This gets the view_mode where our settings are stored
$display = $instance['display'][$view_mode];
//This gets the actual settings
$settings = $display['settings'];
//Initialize the element variable
$element = array();
//Add your select box
$element['pic_size'] = array(
'#type' => 'select', // Use a select box widget
'#title' => t('Button Size'), // Widget label
'#description' => t('Select what size of FB button'), // Helper text
'#default_value' => $settings['pic_size'], // Get the value if it's already been set
'#options' => array(
'small' => 'Small',
'medium' => 'Medium',
'large' => 'Large',
),
);
$element['tooltip'] = array(
'#type' => 'textfield', // Use a textbox
'#title' => t('Tool Tip'), // Widget label
'#description' => t('This text will appear when a user mouses over.'), // helper text
'#default_value' => $settings['tooltip'], // Get the value if it's already been set
);
return $element;
}

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:


/**
* Implements hook_field_formatter_settings_summary().
*/
function facebooklink_field_formatter_settings_summary($field, $instance, $view_mode) {
$display = $instance['display'][$view_mode];
$settings = $display['settings'];
$summary = t('Use a @size Facebook button with the tooltip of "@tooltip"', array(
'@size' => $settings['pic_size'],
'@tooltip' => $settings['tooltip'],
)); // we use t() for translation and placeholders to guard against attacks
return $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.


/**
* Implements hook_field_formatter_view().
*/
function facebooklink_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
$element = array(); // Initialize the var
$settings = $display['settings']; // get the settings
$size = $settings['pic_size']; // The Size setting selected in the settings form
$tooltip = $settings['tooltip']; // The tool tip assigned in settings
// Create the image - Note that I'm storing the images in our module but they could be anywhere
$image = ' ';
foreach ($items as $delta => $item) {
$fb = $item['safe_value']; // Getting the actual value
}
$options = array(
'html' => TRUE, // This tells Drupal that we're sending HTML, not plain text, otherwise it would encode it
'attributes' => array(
'title' => $tooltip, // This sets our tooltip
),
);
if(isset($fb)) {
$link = l($image, $fb, $options); // Create the Link
$element[0]['#markup'] = $link; // Assign it to the #markup of the element
}
return $element;
}

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.

Email Dan Linn

Similar posts

Get notified on new marketing insights

Be the first to know about new B2B SaaS Marketing insights to build or refine your marketing function with the tools and knowledge of today’s industry.