General developer forum

Check active blocks on page

 
Picture of Rajendra Kumar
Check active blocks on page
 

Is there any way to list all available or assigned block on any page like landing page, course view page etc.



 
Average of ratings: -
Tim at Lone Pine Koala Sanctuary
Re: Check active blocks on page
Group Core developersGroup Documentation writersGroup Particularly helpful MoodlersGroup Plugin developers

For the current page, use $PAGE->blocks.

To see what is on other pages, you need code like this:

$page = new \moodle_page();
$page->set_url('/course/view.php', array('id' => $this->course->id));
$page->set_pagelayout('course');
$page->set_course($this->course);

$context = \context_course::instance($this->course->id);

$blockmanager = $page->blocks;

$blockmanager->load_blocks(true);

$missingblocks = self::$BLOCKS_TO_ENSURE_EXIST;
$desiredblockpositions = self::$BLOCK_ORDER;
$targetblockpositions = array();
foreach ($blockmanager->get_regions() as $region) {
foreach ($blockmanager->get_blocks_for_region($region) as $block) {
$instance = $block->instance;

if ($instance->parentcontextid == $context->id && in_array($instance->blockname, self::$BLOCKS_TO_REMOVE)) {
blocks_delete_instance($instance);
$this->log_action('blockremoved', $this->block_type_name($instance->blockname));
continue;
}

if (isset($missingblocks[$instance->blockname])) {
unset($missingblocks[$instance->blockname]);
} else {
if (isset($desiredblockpositions[$instance->blockname])) {
$tempname = $instance->blockname;
} else {
$tempname = 'OTHER';
}
$targetblockpositions[$instance->id] =
array($instance, $desiredblockpositions[$tempname]);
$desiredblockpositions[$tempname] += 1;
}
}
}

 
Average of ratings: -