What is the best way to alter field output? I found "hook_field_formatter_view" but seems nothing like "hook_field_formatter_view_alter" exists. In my case I have address fields (Addressfield module) which used in "Shipping" and "Billing" panes on DrupalCommerce's checkout page. I want to add some js to these fields, preferable using Drupal's Form API "#attached"

  • What is the JS that you would want to add to these fields?
    – saadlulu
    Commented Sep 16, 2012 at 7:54
  • jquery autocomplete plugin
    – volocuga
    Commented Sep 17, 2012 at 10:14

2 Answers 2


You may want to try to alter it with a preprocess function:

function example_preprocess_field(&$variables) {  
  $field_name = $variables['element']['#field_name'];  
  if ($field_name == 'field_example_field') {
    // Your code here.

I ran a test to modify $variables['element']['#attached']['js'] but Drupal didn't recognize the changes to the element. Not sure why. So, you may have to use drupal_add_js.


The hook_field_formatter_view() specified by the display configuration is called in field_default_view(), which is itself called (a layer or two below it) by field_attach_view().

You can see from the second link that this calls hook_field_attach_view_alter() after it's finished with the field formatters:

drupal_alter('field_attach_view', $output, $context);

so you should be able to define that hook.

Note, though, that you'll have to re-find the field on the entity, as it runs the hook for the entire render array, not simply the render array for one field. But the example hook linked to above gives an example of how to do that.

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.