I would like to display a "Please log in" link to anonymous users instead of the normal output of file_default. (I have hook_file_access op download implemented to return AccessResult::allowedIf($account->isAuthenticated()); so security wise this is OK.)

I couldn't find a hook_field_formatter_alter, or similar; which hook can I use to make this change? Or if not a hook, how?


There a serveral ways to do this:

  1. Extending the field formatter
  2. Using a hook, for example hook_ENTITY_TYPE_view()
  3. Changing the render array in the preprocess

You can put the logic as code in all of this places. But the main problem here is caching. You can not simply change the content of the field. You also have to change the cache tags/context, otherwise this code will not work. The field content will only be built once after cache rebuild and then remain unchanged.

If performance is important, this is better solved in javascript.

Your Answer

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