11

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"

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

2 Answers 2

9

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.

5

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.