How do you give a custom block (in a custom module) access to field values produced by the context of page?

eg: If the page has a field, say 'field_my_custom_id' and I want to use it for some purpose in the Build function of a custom block, how to access it from within my module?

1 Answer 1


At the point when you build your block you don't know what other code will put in the page.

As alternative you can use the routing system, because the route is resolved in the bootstrap process (in D8 the symfony framework) before any custom code is run:

if ($node = \Drupal::routeMatch()->getParameter('node')) {
  $field_my_custom_id = $node->field_my_custom_id->value;

Of course you don't know if other code will put this field on the page, but you know that the url of the page will produce the specific node as main content.

  • Excuse my ignorance, but if I call that in say hook_preprocess_block() I can get the variable but then how to I pass it to my build() function?
    – tanbog
    Commented Jun 22, 2016 at 6:37
  • NVM I didn't realise you can make that call inside the build function itself thank you so much!
    – tanbog
    Commented Jun 22, 2016 at 6:42
  • 2
    Yes, you also have to set the cache context '#cache' => ['contexts' => ['route']]
    – 4uk4
    Commented Jun 22, 2016 at 7:18
  • ah excellent, I got round the problem by setting cache to zero: '#cache' => array('max-age' => 0) but that looks like a better solution
    – tanbog
    Commented Jun 22, 2016 at 7:47

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.