Unapedra Unapedra - 1 year ago 76
PHP Question

Create forum in Moodle via external PHP

I would like to create a forum into a Moodle course (specified by the user) using PHP.

I've tried to search it for the net but I haven't found nothing, even in Moodle webservices (in which I cannot find a function to create a forum).

The idea is the user to choose a course (one in which he/she'll be studying), select a "unit", insert a title and the content, and submit it (the rest of the options can be the default ones).

I can retrieve all the data I want from Database but I cannot create any forum. I've tried adding it via SQL too, but I haven't been able neither.

Hope someone here can help me!

Thanks for your time.

Answer Source

If you directly want to create a forum then you need to do following steps -

  1. Insert new record into mdl_forum table and get inserted id
  2. Insert new record into mdl_course_module table with following values course=courseid,module=7(for forum, in moodle 2.9 the forum id is 9),instance=fourmid,visible=1,showavailability=1
  3. Insert record if not exist or Update record into mdl_course_section with following values and get sectionid course = courseid, visible = 1, sequence = moduleid(comma seprated),

  4. Update mdl_course_module table and update sectionid

Finally rebuild moodle coures cache

Here is the moodle code to create a new fourm.

$forum = new stdClass();
$forum->course = $courseid;
$forum->type = "general";    
$forum->timemodified = time();
$forum->id = $DB->insert_record("forum", $forum);

if (! $module = $DB->get_record("modules", array("name" => "forum"))) {
    echo $OUTPUT->notification("Could not find forum module!!");
    return false;
$mod = new stdClass();
$mod->course = $courseid;
$mod->module = $module->id;
$mod->instance = $forum->id;
$mod->section = 0;
if (! $mod->coursemodule = add_course_module($mod) ) {   // assumes course/lib.php is loaded
    echo $OUTPUT->notification("Could not add a new course module to the course '" . $courseid . "'");
    return false;
if (! $sectionid = add_mod_to_section($mod) ) {   // assumes course/lib.php is loaded
    echo $OUTPUT->notification("Could not add the new course module to that section");
    return false;
$DB->set_field("course_modules", "section", $sectionid, array("id" => $mod->coursemodule));

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download