I am preprocessing a node with some data, i want to define a new cache context based on this data.

function hook_preprocess_node(&$variables) {
    $variables['change'] = rand(0,5);

Once i have defined the new context i think i shuold be able to use it as follows.

function  hook_entity_build_defaults_alter(array &$build, \Drupal\Core\Entity\EntityInterface $entity, $view_mode) {
  if($entity->getType() == 'page'){
    $build['#cache']['contexts'][] = 'change';

I can't seem to find out how to define a brand new cache context based on the data in my preprocess so that i can use it in hook_entity_build_defaults_alter();


You will need to define a cache context in yourmodule/src/Context. This will be a class implementing CacheContextInterface, as described in the docs here (see 'How to recognize, discover and create?).

If you search for implements CacheContextInterface in your code base you should be able to see some examples. The class will provide getContext() and getCacheableMetadata() methods.

  • note that you also need to define it as a service, not just the class. – Berdir Sep 8 '16 at 22:53

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.