Add block instance programmatically

Add block instance programmatically

by Joseph Malmsten -
Number of replies: 0

Hi,

Working for a company that manages a moodle block that allows users to upload and embed videos into moodle. One of our clients wants to be able to import a course with our block into a course that does not have our block and have that new course add the block when the import happens. 

I found the block manager inside the $PAGE global but it looks like by the time I'm accessing it the $PAGE is referencing the global settings page, not the course being imported. 

It also looks like the blocks API link I found somewhere on the moodle site points to an empty page https://docs.moodle.org/dev/Blocks_API

My current code looks like this:

$blockmanager = $PAGE->blocks;

$blockmanager->load_blocks(true);

// This is searching for if the page in it's current context contains the instance of the block. 

 if (!$blockmanager->is_block_present('panopto')) {

    // This would add a block, not an instance of the block, unless I am wrong. I need to be able to add an instance of a block to the course. 

    $blockmanager->add_block_at_end_of_default_region('panopto');

 }


I'm thinking I would need something more along the lines of adding a block instance to a course based on its moodle course id or course context. That would mean generating a moodle_page object that correctly points to the course page, or finding some other way of checking for existence and then adding a block instance to a course programmatically based on it's id if the course does not already contain the instance of the block. 


A finger in the right direction would be helpful, I don't see many examples of people trying something like this at the moment. 


Average of ratings: -