Friday, June 17, 2011

Adding a new display option in the view


To create a formatter option like the ones provided by CCK editor you need to follow the following steps. For those of you who don't know what a formatter is take a look at the following images. If you go to display option in any content type "admin/content/node-type/test-content-type/display" you can find these options. These are the same options that appear when selecting a formatter in the views when you are displaying field from content(CCK) group.

For this example I have taken link module. Link module has the following seven options by default. I will be adding a new option "File with Icon", which will make the file appear link a download link along with the icon. To begin with we will have these.










The first thing that we have got to do is implement hook_field_formatter_info. The values passed are what should the label for this formatter be, this format will apply to which field types and how do we handle the multiple values. The key in the array that we are passing is "file". This is important as the other functions we will write are dependent on this.

function mymodule_field_formatter_info() {
  return array(
    'file' => array(
      'label' => t('File with icon'),
      'field types' => array('link'),
      'multiple values' => CONTENT_HANDLE_CORE,
      ),
  );
}

Now since the key is "link", CCK will look out for a function that begins with theme_[modulename] and ends with formatter_file. So first let us write an entry for that in our implementation of hook_theme.

function mymodule_theme() {
  return array(
    'mymodule_formatter_file' => array(
      'arguments' => array('element' => NULL),
     ),
  );
}

The theme function that returns the formatted field.

function theme_mymodule_formatter_file($element = NULL) {
  global $base_path,$base_url;
  $icon_path =  drupal_get_path('module', 'filefield') . '/icons/' . get_file_type($element['#item']['url']);
  $output = theme_image($icon_path);
  $output .= l($element['#item']['title'],$element['#item']['url'],array('attributes' => array('target' => '_blank')));
  return $output;
}

Now that we have done all the necessary changes, the much awaited output will look like this


No comments:

Post a Comment