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?

Bởi isalpikachu k -
Số lượng các câu trả lời: 4

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

How can I do this?


this

Trung bình điểm đánh giá: -
Để phản hồi tới isalpikachu k

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

Bởi Michael Hughes -
Hình của Core developers Hình của Particularly helpful Moodlers Hình của Plugin developers
Write something that hooks into the the course_module_deleted event? See https://docs.moodle.org/dev/Events_API#Event_observers
Để phản hồi tới Michael Hughes

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

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


Để phản hồi tới isalpikachu k

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

Bởi Michael Hughes -
Hình của Core developers Hình của Particularly helpful Moodlers Hình của 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.
Trung bình điểm đánh giá:Useful (2)
Để phản hồi tới Michael Hughes

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

Bởi 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.