Score:1

Get the node that a block is placed on without a route parameter?

in flag

Is there a way to devise from a block instance that was placed in Layout Builder how to load up and extract what node (or entity) it was placed into?

We are indexing pages into Solr and some inline components that load the node from the current route for data are failing because Search API is loading the entities to index and not crawling paths.

Score:4
cn flag

A block placed in Layout Builder can load the entity context:

$entity = $this->getContextValue('entity');

This works in the block build method. If you are altering an existing block you can use a LayoutBuilderEvents::SECTION_COMPONENT_BUILD_RENDER_ARRAY event:

public function onBuildRender(SectionComponentBuildRenderArrayEvent $event) {
  $build = $event->getBuild();
  $contexts = $event->getContexts();
  if (isset($contexts['entity'])) {
    if ($entity = $contexts['entity']->getContextValue()) {
      $build['content'][] = ['#markup' => $entity->label()];
    }
  }
  $event->setBuild($build);
}
Kevin avatar
in flag
I'll check - I think someone is trying to load this from hook_preprocess_block. If this does not work from there, is it possible to add a property via BlockComponentRenderArray event and then see it?
4uk4 avatar
cn flag
Yes, this looks good. This event has even a contexts property.
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.