I've created a custom field formatter using hook_field_formatter_info() and implemented it using hook_field_formatter_view().

My formatter requires additional javascript though and at the moment I'm including it in hook_field_formatter_view() but I have a feeling there's gotta be a better place to do this.

However there is no hook_field_formatter_preprocess() (there is a formatter_prepare_view() though but it doesnt't seem right)

Any ideas?

1 Answer 1


Adding the JavaScript in hook_field_formatter_view() works just fine. Just also be sure to use #attached and not drupal_add_js() since that way your file is included in the render cache.

function mymodule_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();
  $settings = $display['settings'];

  foreach ($items as $delta => $item) {
    $element[$delta] = // Blah blah blah add output for each $items in $element as a render array.

  // Add the JavaScript file.
  $element['#attached']['js'][] = drupal_get_path('module', 'mymodule') . '/mymodule.field.js;

  return $element;
  • Since I was calling a theme function in the formatter_view() anyway I just moved the include js part to hook_preprocess_hook(), this is great know to know though!
    – Alex Weber
    Jan 10, 2012 at 19:16
  • can we add css also in the same way? $element['#attached']['css'][] = drupal_get_path('module', 'mymodule') . '/mymodule.field.css;
    – Cool
    Aug 29, 2016 at 12:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.