1

I need to programmatically update the paths for blocks that are displayed on a specific page, I can load all blocks using:

$nodeStorage = \Drupal::entityTypeManager()->getStorage('block');
$ids = $nodeStorage->getQuery()
                ->execute();
$items = $nodeStorage->loadMultiple($ids);

but I only want to load the blocks that are displayed on a certain page, but 'pages' doesn't work:

->condition('pages', '/mycat/pagename') 

what should I use?

1 Answer 1

1

Apparently this is not possible because the visibility of blocks is not part of their storage info, it's part of the config.

So the best you can do is filter by theme

$nodeStorage = \Drupal::entityTypeManager()->getStorage('block');
$blocks = $nodeStorage->loadByProperties(['theme' => 'theme_name']);

and loop through the returned data to check their path info:

foreach ($blocks as $block) {
  $visibility = $block->getVisibility();
  if (!isset($visibility['request_path']['pages'])) {
    continue;
  }
  
  $existing_pages_string = $visibility['request_path']['pages'];
  $existing_pages_array = array_map('trim', explode("\n", $existing_pages_string));

  if (in_array($old_path, $existing_pages_array)) {
    $new_pages = str_replace($old_path, $new_path, $existing_pages_string);
    $visibility['request_path']['pages'] = $new_pages;
    $block->setVisibilityConfig('request_path', $visibility['request_path']);
    $block->save();
  }
}

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.