0

This question is an exact duplicate of:

How do i get the block machine name $block_id programmatically in Drupal 8?

$block_id = 'machine_name_to_determine';

$block_config = \Drupal\block\Entity\Block::load($block_id);

marked as duplicate by Shawn Conn, mradcliffe, 4k4, kiamlaluno Mar 2 at 4:18

This question was marked as an exact duplicate of an existing question.

  • It really depends on where you're doing it and what information you have access to. Where are you putting this code? In a hook? If so what hook? – Matt Feb 28 at 18:52
  • You can query the block machine name with any information you have like plugin id, theme, region, ..., see drupal.stackexchange.com/questions/248324/… – 4k4 Feb 28 at 19:35
0

Here is a helper function to get the block content by machine name:

/**
 * @param $machine_name
 *
 * @return \Drupal\block_content\Entity\BlockContent|\Drupal\Core\Entity\EntityInterface|null
 * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
 * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
 */
function getBlockContentByMachineName($machine_name) {
  // Get the block id from machine name.
  $query_result = \Drupal::entityTypeManager()
    ->getStorage('block_content')
    ->getQuery()
    ->condition('machine_name', $machine_name)
    ->range(0, 1)
    ->execute();
  // Get the block id.
  $block_id = reset($query_result);
  if ($block_id) {
    $block = \Drupal\block_content\Entity\BlockContent::load($block_id);
    return $block;
  }
  else {
    return NULL;
  }
}

Use example:

$machine_name = 'machine_name_to_determine';

$block_content = getBlockContentByMachineName($machine_name);

$block_content is an instance of BlockContent you can do what you want with it for example get the build using:

 $build = \Drupal::entityTypeManager()
    ->getViewBuilder('block_content')
    ->view($block_content);
$block_render = render($build);
0

Why do you need the block's machine name? You can get the block ID from the admin interface. Then you can load the block using the ID.

Go to the block layout page https://example.com/admin/structure/block and from there, you can get the block ID. Simply click or hover on edit to get the ID from the edit URL of a block.

$block_details = \Drupal::entityTypeManager()->getStorage('block_content')->load($block_id);
$body_value = $block_details->body->view('full');

In this way, you get the various values attached to a block. I don't know what you want exactly, I hope this code may help you.

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