diff --git a/calendar/tests/container_test.php b/calendar/tests/container_test.php index 23a41082eaf..3f08efbee43 100644 --- a/calendar/tests/container_test.php +++ b/calendar/tests/container_test.php @@ -285,6 +285,31 @@ class core_calendar_container_testcase extends advanced_testcase { $this->assertInstanceOf(event_interface::class, $factory->create_instance($event)); } + /** + * Test that when course module is deleted all events are also deleted. + */ + public function test_delete_module_delete_events() { + global $DB; + $user = $this->getDataGenerator()->create_user(); + // Create the course we will be using. + $course = $this->getDataGenerator()->create_course(); + $group = $this->getDataGenerator()->create_group(['courseid' => $course->id]); + + foreach (core_component::get_plugin_list('mod') as $modname => $unused) { + $module = $this->getDataGenerator()->create_module($modname, ['course' => $course->id]); + + // Create bunch of events of different type (user override, group override, module event). + $this->create_event(['userid' => $user->id, 'modulename' => $modname, 'instance' => $module->id]); + $this->create_event(['groupid' => $group->id, 'modulename' => $modname, 'instance' => $module->id]); + $this->create_event(['modulename' => $modname, 'instance' => $module->id]); + $this->create_event(['modulename' => $modname, 'instance' => $module->id, 'courseid' => $course->id]); + + // Delete module and make sure all events are deleted. + course_delete_module($module->cmid); + $this->assertEmpty($DB->get_record('event', ['modulename' => $modname, 'instance' => $module->id])); + } + } + /** * Test getting the event mapper. */ diff --git a/course/lib.php b/course/lib.php index 2f8cbdd7807..6877fac0d18 100644 --- a/course/lib.php +++ b/course/lib.php @@ -1204,8 +1204,10 @@ function course_delete_module($cmid, $async = false) { // Delete events from calendar. if ($events = $DB->get_records('event', array('instance' => $cm->instance, 'modulename' => $modulename))) { + $coursecontext = context_course::instance($cm->course); foreach($events as $event) { - $calendarevent = calendar_event::load($event->id); + $event->context = $coursecontext; + $calendarevent = calendar_event::load($event); $calendarevent->delete(); } } diff --git a/mod/lesson/locallib.php b/mod/lesson/locallib.php index 8c32a2d71cd..a963a7886c3 100644 --- a/mod/lesson/locallib.php +++ b/mod/lesson/locallib.php @@ -1574,7 +1574,9 @@ class lesson extends lesson_base { $DB->delete_records("lesson_timer", array("lessonid"=>$this->properties->id)); $DB->delete_records("lesson_branch", array("lessonid"=>$this->properties->id)); if ($events = $DB->get_records('event', array("modulename"=>'lesson', "instance"=>$this->properties->id))) { + $coursecontext = context_course::instance($cm->course); foreach($events as $event) { + $event->context = $coursecontext; $event = calendar_event::load($event); $event->delete(); }