I want the list of the names of all regions available in the current theme in drupal 8. How to do this ?
And is it possible to get the list of the blocks placed on that region ?
3 Answers
Active ADMIN theme & active SYSTEM theme might be different.(By default active admin theme is seven & active system theme is bartik)
Get the current theme used by the below code(if you are in admin section it will return seven, else bartik)
$theme = \Drupal::theme()->getActiveTheme()->getName();
As we need the system theme, below code will do the job
$theme = \Drupal::config('system.theme')->get('default');
And pass the theme name to get all the regions
$system_region = system_region_list($theme, $show = REGIONS_ALL);
This will give you all the regions in array format
$region_list = json_decode(json_encode(system_region_list(\Drupal::config('system.theme')->get('default'),$show = REGIONS_ALL)),true);
Second part of the question
Get the blocks in particular region . Below is the code snippet which can get the blocks placed in pre-content region:
$blocks = \Drupal::entityManager()
->getStorage('block')
->loadByProperties(array('theme' => \Drupal::config('system.theme')->get('default'),'region'=>'pre_content'));
-
thank you for your attention..but this system_region_list() returning a stdClass Object, which doesn't conatin the region array/list Sep 27, 2016 at 7:19
-
-
My current default theme is Bartik, it has 15 regions but $region_list is listing up only 9. Even region names are also different in some cases. Sep 27, 2016 at 7:31
-
I don't know is it possible to get the blocks list in one line, but you can do it like that:
$blocks = \Drupal\block\Entity\Block::loadMultiple();
$region_name = 'content';
$block_ids = [];
foreach($blocks as $block){
if($block->getRegion() === $region_name){
$block_ids[] = $block->id();
}
}
This worked for me a couple of times already, looking how the core does it:
In case of "/admin/structure/block" contains all the regions, you only have to look up how it's implemented in the core.
- Get the link where you saw the functionality (/admin/structure/block in our case)
- If you use IDE "find in path" on the core directory and paste it.
- You are looking for a "*.routing.yml", which will tell you which controller handles the request
- Now you are on your own to find it, but it's really not that hard.
As mentioned above you will need this:
system_region_list($theme, $show)
But also I suggest you to take a look at BlockListBuilder.php
, in core/modules/block!