You are here
Custom Display Fields (D6)
D7 - http://www.computerminds.co.uk/articles/creating-new-field-formatters-dr...
For the A.D.D.'ers: Example Module Files attached at the bottom.
Simple example of creating a custom Display Field. This is something that I keep using over and over again because with a small bit of code you can really flex what a field can do. Matt has made me blog on it to make a code example easy to get to.
For this example let's say that you wanted to add a field to track the history on which users are flagging and unflagging a node. The three items we are to track are User, Flagged Or UnFlagged, and date action took place. To do this we have added an unlimited text field that will be populated when the action took place and formatted as such: Uid | Boolean | Unix Time stamp. Now of course we cannot have the user view integers separated by pipes so we simply make a new Custom Display field that you could use in Node Display and Views. The code is pasted below and there is a zip file of the example this module attached to play with.

<?php
/**
* Implementation of hook_field_formatter_info().
*
* Here we define an array with the options we will provide in display fields page
* The array keys will be used later in hook_theme and theme_
*/
function custom_displays_field_formatter_info() {
$formatters = array(
'flaggedby' => array(
'label' => t('Flagged By'),
'field types' => array('text'),
'description' => t('Show flagged history'),
),
);
return $formatters;
}
/**
* Implementation of hook_theme().
*
* We declare our theme functions according to the array keys in hook_field_formatter_info
*/
function custom_displays_theme() {
$theme = array(
'custom_displays_formatter_flaggedby' => array(
'arguments' => array('element' => NULL),
),
);
return $theme;
}
/**
* Theming functions for our formatters
*
$element['#item']: the sanitized $delta value for the item,
* $element['#field_name']: the field name,
* $element['#type_name']: the $node->type,
* $element['#formatter']: the $formatter_name,
* $element'#node']: the $node,
* $element['#delta']: the delta of this item, like '0',
*/
function theme_custom_displays_formatter_flaggedby($element) {
if ($element['#item']['value']) {
$explode_string = explode('|', $element['#item']['value']);
$result = db_query_range("SELECT users.uid AS uid, users.name AS users_name FROM {users} {users} WHERE users.uid = %s", $explode_string[0], 0, 1);
$user = db_fetch_object($result);
$output = $user->users_name;
$flagged = $explode_string[1] ? 'Flagged' : 'Un-Flagged';
$output .= ' - '. $flagged;
$date = date('Y M D', $explode_string[2]);
$output .= ' - '. $date;
return $output;
}
}



Add new comment