I'm trying to manually enroll students in a course Moodle
using a Script
but I can't. I am using the function but it doesn't work role_assign
for me.Moodle
The code I am using is the following:
//obtiene el id del rol "member" que ha sido creado anteriormente
$rolMember = obtenerIdRol ("member");
$rolManager = obtenerIdRol ("manager" );
$contexto = context_course::instance($comunidad_moodle);
foreach ($usuariosUVDotlrn as $usu) {
$userid = null;
$usernameDotln = $usu["username"];
$rolDotln = $usu["rol"];
if($rolDotln == "dotlrn_admin_rel"){
$rolid = $rolManager;
}else if($rolDotln == "dotlrn_member_rel"){
$rolid = $rolMember;
}else{
$rolid = -1;
}
//obtenemos el id del usuario en Moodle
$sql = "SELECT id FROM mdl_user WHERE username = ?";
$resUsu = $DB->get_records_sql($sql, array($usernameDotln));
foreach ( $resUsu as $n ) {
$userid = $n->id;
}
//Comprobamos que el usuario existe en moodle.
if( is_null($userid)){
m("- El usuario: $usernameDotln no existe en la Base de Datos de Moodle");
}else{
//Comprobamos si el usuario pertenece al curso
$enrolled = is_enrolled($contexto, $userid, '', true);
if( !$enrolled){
if($rolid != -1){
$idroleassign = role_assign($rolid , $userid, $contexto);
m("- El usuario: $usernameDotln con id: $userid y rol: $rolid insertado en el curso: $comunidad_moodle");
}else{
m("- El usuario: $usernameDotln con id: $userid y rol: $rolid no esta en el curso: $comunidad_moodle. No se ha encontrado el rol.");
}
}else{
m("- El usuario: $usernameDotln con id: $userid ya pertenece al curso: $comunidad_moodle");
}
}
}
Note: the function m("") is responsible for displaying the text in the console
Note2: the function obtenerIdRol
is as follows:
/**
* Devuelve el id del rol pasado.
*
* @param $rol nombre del rol.
*
* @return id del rol
*/
function obtenerIdRol ($rol ){
global $DB;
$id = null;
//obtenemos el id del rol en Moodle
$sqlrol = "SELECT id FROM mdl_role WHERE shortname = ?";
$roles = $DB->get_records_sql($sqlrol, array($rol));
foreach ( $roles as $r ) {
$id = $r->id;
}
if(is_null($id))
return -1;
else
return $id;
}
If someone knows how to do it or has an example or documentation that can help me, it will be a great help for me.
After searching and trying a few things, I have found a solution that works, and it consists of instantiating the enroll plugin with manual type so that the assignment of the students is done through the plugin.
The code would be as follows:
In my ignorance of both Moodle and PHP I found this way to enroll a student in a course. I share it because it seems a bit simpler than the accepted answer.
UPDATE : The platform I work for has asked me that students only have 60 days to complete the courses, so you have to specify the enrollment time when registering them. I add it to the code, at the end.