I am trying to create sections within a Moodle course using a Script but I can not. I am using the function course_create_sections_if_missing
of Moodle but I can not show that the sections on the web and in the database are created.
The code I am using is the following:
if($numSecciones >0){
foreach ($secciones as $nombreSeccion ) {
$idSeccion = comprobarSections($curso_moodle , $nombreSeccion );
if($idSeccion == -1){
//creamos las secciones
m("crear seccion: ". $nombreSeccion );
$maxSection = getMaxSections($curso_moodle );
if($maxSection != -1){
m("max seccion: " . $maxSection);
$idSec = $maxSection + 1;
course_create_sections_if_missing($curso_moodle , $idSec);
$res = updateNameSection($curso_moodle , $nombreSeccion , $idSec);
m("resultado update: " . $res);
}else{
m("el curso no tiene secciones");
}
}else{
m("ya existe la seccion: ". $nombreSeccion );
}
}
}else{
m("No hay secciones para la comunidad. ");
}
Note: the m ("") function is responsible for displaying the text in the console
the verifySections function is as follows:
/**
* Comprueba si existe una seccion.
*
* @param $course id del curso.
* @param $section nombre de la seccion
*
* @return id de la seccion
*/
function comprobarSections($course , $section){
global $DB;
$id = null;
$sql = "SELECT id FROM mdl_course_sections where course = ? and name = ? ";
$sections = $DB->get_records_sql($sql, array($course, $section));
foreach ( $sections as $r ) {
$id = $r->id;
}
if(is_null($id))
return -1;
else
return $id;
}
the getMaxSections function is as follows:
/**
* Devuelve el id de la seccion mas alto para un curso.
*
* @param $course id del curso.
*
* @return id de la seccion
*/
function getMaxSections($course){
global $DB;
$id = null;
$sql = "SELECT max(section) as sec FROM mdl_course_sections where course = ? ";
$sections = $DB->get_records_sql($sql, array($course));
foreach ( $sections as $r ) {
$id = $r->sec;
}
if(is_null($id))
return -1;
else
return $id;
}
the updateNameSection function is as follows:
/**
* Actualiza el nombre de una seccion.
*
* @param $course id del curso.
* @param $nameSection nombre de la seccion.
* @param $idSection id de la seccion.
*
* @return resultado
*/
function updateNameSection($course, $nameSection , $idSection){
global $DB;
$id = null;
$sql = "update mdl_course_sections set name = ? where course = ? and section = ?";
$result = $DB->execute($sql, array($nameSection , $course, $idSection));
return $result;
}
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.