Skip to content

Instantly share code, notes, and snippets.

@FMCorz
Created November 27, 2020 00:22
Show Gist options
  • Save FMCorz/d63bc40184904841f89f5792b3e47c0b to your computer and use it in GitHub Desktop.
Save FMCorz/d63bc40184904841f89f5792b3e47c0b to your computer and use it in GitHub Desktop.
Create a Level up! entry for students added to a cohort
<?php
/**
* Snippet showing how to create a record for a student as they are added to
* a cohort. Students will earn 0 points so to only creates their record.
*
* These files below must be implemented as part of an existing plugin, or
* a new one. Only the two files relevant to Level up! are displayed below.
*/
// local/pluginname/db/events.php
$observers = [
[
'eventname' => '\\core\\event\\cohort_member_added',
'callback' => 'local_pluginname_observer::cohort_member_added',
],
];
// local/pluginname/classes/observer.php
class local_pluginname_observer {
/**
* Observes when a member is added to a cohort.
*
* @param \core\event\cohort_member_added $event The event.
* @return void
*/
public static function cohort_member_added(\core\event\cohort_member_added $event) {
if (!class_exists('block_xp\di')) {
return;
}
$userid = $event->relateduserid;
$courseid = 0; // The course ID does not matter when used site-wide.
// Do not add points to users who cannot earn points.
if (!has_capability('block/xp:earnxp', context_system::instance(), $userid)) {
return;
}
// Increase the number of points by 0 forces the record to be created.
$world = \block_xp\di::get('course_world_factory')->get_world($courseid);
$world->get_store()->increase($userid, $points);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment