Creating Custom Formatters with Display Suite
Here at EchoDitto, we've been making heavy use of the Display Suite module. It obliterates a lot of the more tedious theming issues we typically run into when building out a Drupal site, and for the most part, we love it. But as with any solution that takes logic out of code and puts it into the UI, if you want to do anything that isn't already provided by DS, you're going to have a write a bunch of code.
So far, the biggest drawback to using DS that we've experienced so far is the lack of formatters. For example, suppose you have something like an Action content type with the following fields:
… and the Link field contains a link to an action or petition on Salsa, Convio, or whatever.
If you set this up using Views, linking the Title field to the Link field would be a snap. Not so with Display Suite. There are a number of options here, but for something small like this, the Custom Formatters module is a great choice. For the example given above, you could create a custom PHP formatter that did the following:
// the $variables object holds all available variables $text = $variables['#object']->title; $link = $variables['#object']->field_link['und']['value']; print l($text, $link);
Then, in the DS UI, just set the field to use your custom formatter:
We can also handle another, slightly more complicated situation involving the Media module. Suppose you've got a content type that includes a Video field handled by Media, and you want to rewrite the title of that link. So instead of:
You can have the human-readable:
The problem here is that the Media module doesn't give you a URL to link to: it gives you a URI:
The trick to dillying yourself out of this pickle is a wacky, hard-drinking little function called file_create_url(). It takes a stream wrapper (such as our URI) and turns it into a URL. Big ups to Ethan for finding this function.
We can now create a custom formatter that does the following:
// we can also use the terser #items field $items = $variables['#items']; $text = t('Boom goes the whale'); $link = file_create_url($items['uri']); print l($text, $link);
Although it's a bit of a pain to create a custom formatter for something so simple, doing so allows you to make full use of Display Suite and all its awesome powers, and is my current preferred solution for dealing with small things like this.
About Drupal Sun
Drupal Sun is an Evolving Web project. It allows you to:
- Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
- Facet based on tags, author, or feed
- Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
- View the entire article text inline, or in the context of the site where it was created
See the blog post at Evolving Web