0

I tried to hook my Link type field with machine name "field_link". This field is rendered in template using delta index to extract some values, e.g.:

{{ content.field_link[0]['#title'] }}

I have noticed that when I use content.field_link[0] or content.field_link.0 my hook HOOK_preprocess_field__field_link(&$vars, $hook) is not triggered. But as soon as I use content.field_link the hooks works.

Is there some workaround or using deltas to extract some field's values is not the best practice?

Thanks

1
  • 1
    These are render arrays. The first example prints a value while the second triggers a rendering function to generate the output. That is why. If you need something other than the default, you should either go with a field formatter or preprocess new variables for the template.
    – Kevin
    Nov 2, 2021 at 20:07

1 Answer 1

1

The field preprocess hook only works when you render the field. Once you start extracting values off the field object (like individual properties or specific deltas), you're no longer rendering the field itself thus not triggering the hook.

I also do not recommend extracting and rendering data this way because you're losing some metadata that come with these objects (e.g. cacheability, theme info, formatter info, modifications from other modules, etc.). You could:

  • Create a Field Formatter for that field type and only render a specific delta (by overriding viewElements() and only adding specific deltas). You can make the delta configurable.
  • Or a combination of hook_field_formatter_third_party_settings_form and hook_preprocess_field. The former will let you save configuration into field display config, while the latter allows you to pick up that config and modify the field output.
    • A good example of this combination (albeit used for a different purpose) can be found in the Fences module.

In both cases, you can choose to make them configurable via admin and not hardcoding the delta selection into template. You can even make it so that you can ignore both entirely, leaving the field rendering the default output.

1
  • I use deltas to extract values and get rid of drupal's nested templates because most of the time I do my own. But as I see this is not a good idea. Currently my problem is that I've created custom Widget for Link field and I want to get some additional values from this widget to my template. Thanks for your response. Nov 2, 2021 at 20:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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