2

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();

1 Answer 1

6

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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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