Programmatically enable an enrolment plugin

Programmatically enable an enrolment plugin

by David North -
Number of replies: 4

Is there a way to programmatically enable an enrolment plugin?


Or is it as simple as adding a record to mdl_enrol with the necessary data for the plugin? For some reason I don't trust this way of going about it.

Average of ratings: -
In reply to David North

Re: Programmatically enable an enrolment plugin

by Darko Miletić -

This is how it should be done:


function enable_enrol_plugin($plugin) {
    if (!enrol_is_enabled($plugin)) {
        set_config('enrol_plugins_enabled', get_config('core', 'enrol_plugins_enabled').','.$plugin);
        core_plugin_manager::reset_caches();
        context_system::instance()->mark_dirty();
    }
}



In reply to Darko Miletić

Re: Programmatically enable an enrolment plugin

by Darko Miletić -

Slightly improved


function enable_enrol_plugin($plugin) {
    if (!enrol_is_enabled($plugin)) {
        $updated = $plugin;
        $current = get_config('core', 'enrol_plugins_enabled');
        if (!empty($current)) {
            $updated = $current.','.$plugin;
        }
        set_config('enrol_plugins_enabled', $updated);
        core_plugin_manager::reset_caches();
        context_system::instance()->mark_dirty();
    }
}



Average of ratings: Useful (1)
In reply to Darko Miletić

Re: Programmatically enable an enrolment plugin

by David North -

Thanks for this.


Unfortunately my question wasn't clear enough though.


I'm actually looking to enable the plugin programmatically on the course level.

In reply to David North

Re: Programmatically enable an enrolment plugin

by Darko Miletić -

OK, here goes:


/**
 * @param string $plugin
 * @param object $course
 * @return mixed|null
 * @throws coding_exception
 */
function add_enrol_instance($plugin, $course) {
    global $DB;
    $inst = null;
    $enrol = enrol_get_plugin($plugin);
    if (!empty($enrol)) {
        $inst = null;
        $instances = enrol_get_instances($course->id, false);
        foreach ($instances as $instance) {
            if ($instance->enrol == $plugin) {
                $inst = $instance;
                break;
            }
        }
        if ($inst === null) {
            $instid = $enrol->add_default_instance($course);
            if ($instid === null) {
                $instid = $enrol->add_instance($course);
            }
            $inst = $DB->get_record('enrol', array('id' => $instid));
        }
    }
    return $inst;
}




Average of ratings: Useful (1)