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?

isalpikachu k-mit -
Antal besvarelser: 4

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

How can I do this?


this

Gennemsnitsbedømmelse: -
I svar til isalpikachu k

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

Michael Hughes-mit -
Core developers-ip assinga Particularly helpful Moodlers-ip assinga Plugin developers-ip assinga
Write something that hooks into the the course_module_deleted event? See https://docs.moodle.org/dev/Events_API#Event_observers
I svar til Michael Hughes

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

isalpikachu k-mit -

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']);
    } 
}


I svar til isalpikachu k

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

Michael Hughes-mit -
Core developers-ip assinga Particularly helpful Moodlers-ip assinga Plugin developers-ip assinga
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.
I svar til Michael Hughes

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

isalpikachu k-mit -
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.