Add a block to each course - NOT via the front page

Re: Add a block to each course - NOT via the front page

by Rex Lorenzo -
Number of replies: 0

You can create an event observer for the \core\event\course_created event. Details on how to create an event observer: https://docs.moodle.org/dev/Event_2

In the event observer, here is a code snippet that we use to add "Recent activity" for certain courses:

        // Add the "Recent activity" and "Upcoming events" blocks upon build and
        // place them above the "Administration" block.
        $coursecontext = context_course::instance($courseid);
        $page->set_context($coursecontext);
        $page->blocks->add_regions(array(BLOCK_POS_RIGHT), false);
        $page->blocks->add_block('recent_activity', BLOCK_POS_RIGHT, -10, 0, 'course-view-*');
        $page->blocks->add_block('calendar_upcoming', BLOCK_POS_RIGHT, -9, 0, 'course-view-*');

You will need to get the courseid from the event object that is passed to the function.

Or if you want to add in default blocks for every course for a given format, check out the $CFG->defaultblocks_<format> config: