How can I run a function when a course module is deleted in moodle?

How can I run a function when a course module is deleted in moodle?

by isalpikachu k -
Number of replies: 4

I want to run a function when this button is clicked and the course module is deleted.

How can I do this?


this

Average of ratings: -
In reply to isalpikachu k

Re: How can I run a function when a course module is deleted in moodle?

by Michael Hughes -
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Plugin developers
Write something that hooks into the the course_module_deleted event? See https://docs.moodle.org/dev/Events_API#Event_observers
In reply to Michael Hughes

Re: How can I run a function when a course module is deleted in moodle?

by isalpikachu k -

I've added these and nothing happens. It works when I add \core\event\course_module_updated though I have no idea why. I need the \core\event\course_module_deleted event.


In db/events.php:

$observers = array(

    array(
        'eventname'   => '\core\event\course_module_deleted',
        'callback'    => 'mod_game_observer::course_module_deleted',
    ),
);

In classes/observer.php:

defined('MOODLE_INTERNAL') || die();


class mod_game_observer {

    /**
     * Observer for the even course_module_deleted.
     *
     * @param \core\event\course_module_deleted $event
     */
    public static function course_module_deleted(\core\event\course_module_deleted $event) {
        global $DB;
        //die(var_dump($event));
        $DB->delete_records_select("game_results", "cmid = ".$event->objectid);
        $DB->delete_records_select("game", "id = ".$event->other['instanceid']);
    } 
}


In reply to isalpikachu k

Re: How can I run a function when a course module is deleted in moodle?

by Michael Hughes -
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Plugin developers
Course module deletion can happen I think "out of band" in that the user can "delete" the module, but Moodle actually "flags" the activity for deletion (and hides it from users) and stacks an adhoc task that then performs the actual deletion, so you may want to dig into that whole process to see exactly how it works and what events get raised at what point in the process.

You also need to do a version bump to get your event observers to be updated, which is common step to forget.
Average of ratings:Useful (2)
In reply to Michael Hughes

Re: How can I run a function when a course module is deleted in moodle?

by isalpikachu k -
I didn't know there was a recycle bin in moodle so they weren't exactly deleted that's why it didn't run, also cron script doesn't run automatically on local so the recycle bin wouldn't even show up so I just disabled it.