My goal is to replace (by a custom markup) the render array of field_product when some conditions are met. (in a ecommerce site)

Ex: If this is the weekend or if it is after 12pm the field_product must not be rendered (but a markup like "the webshop is closed")

In mymodule_preprocess_node(&$vars) I have tried without success:



$vars['content']['field_product']['#cache']['contexts'][] = 'session';

Unfortunately, it is not working for anonymous users

The only solution I found is:


But as you can see, all the node is un-cached... not the field_product

What is wrong with my code?

Again: this should be uncached for anonymous users


You have to make sure you add #cache data inside of a render array only to render elements (containing #type, #theme or #markup). In other places of a render array it doesn't work.

Where you add cache max-age or contexts inside of an entity doesn't make a difference though, because there is no field level, only entity level caching.

Another problem is page caching for anonymous users. See How do I disable Twig and block cache for a specific module?

  • Thank you, I understand that it is not feasible... I have to invalidate all the node. Thank you!
    – Baud
    Jul 15 '19 at 22:09

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.