CCK-formatters make up the code and are thus capable of displaying the fields the way a coder wants it. Website developers often come short of formatters, when performing tasks. In this article I will offer a review of creating the formatter for node refence field, which will simply be adding anchor to the link.
First, we are to announce the formatter by causing the hook_field_formatter_info ():
/** * Implements 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 example_field_formatter_info() { $formatters = array( 'nodereference_anchor' => array( // The name that the user will choose in the display fields configuration page. 'label' => t('Link(with anchor)'), // An array with the types of cck fields that the formatter supports. 'field types' => array('nodereference'), 'description' => t('Displays a link to the referenced node with anchor.'), ), ); return $formatters; }
The hook returns an array to all arrays of all declared formatters in this module. Next, theming function in hook_theme() is to be announced and that will look after the field withdrawal:
/** * Implements hook_theme(). * * We declare our theme functions according to the array keys in hook_field_formatter_info. */ function example_theme() { return array( 'example_formatter_nodereference_anchor' => array( 'arguments' => array('element' => NULL), ), ); }
Well, here is the theming function itself:
/* * Theming functions for our formatter. * * And here we do our magic. You can use dsm($element) to see what you have to play with (requires devel module). */ function theme_example_formatter_nodereference_anchor($element) { $output = ''; if (!empty($element['#item']['nid']) && is_numeric($element['#item']['nid']) && ($title = _nodereference_titles($element['#item']['nid']))) { $output = l($title, 'node/'. $element['#item']['nid'], array('fragment' => 'example-anchor')); } return $output; }
As you see, all is simple and clear. This simplicity, however, will spare you the trouble of writing loads of code in tempate.php, and still more trouble of further supporting it.