1

I am adding a folder module to a Moodle course using the API:

folder_add_instance($data, null);

I am getting the error below when running the script using CMD:

!!! Invalid course module ID !!!

I looked into the folder_add_instance() function in the library, the error is occurring when trying to get the context:

$context = context_module::instance($cmid)//$cmid = 8

i looked into the mdl_context table in Moodle database but couldn't understand the values and their relation to the error i am getting.

Will deleting the mdl_context values from the database will help? or i am missing something here?

Note that the script was working fine, until i deleted all the courses i had on Moodle using the web interface.(i deleted the category containing all the courses).

Johnny Zghaib
  • 518
  • 1
  • 12
  • 30

2 Answers2

1

To programmatically create a module in Moodle you should use function add_moduleinfo().

Look at the example in the folder generator: https://github.com/moodle/moodle/blob/master/mod/forum/tests/generator/lib.php#L67

Will be something like:

require_once($CFG->dirroot.'/course/modlib.php');
$foldername = 'YOUR NAME HERE';
$courseid = 12345;
$sectionnum = 0;

$course = get_course($courseid);
$moduleid = $DB->get_field('modules', 'id', array('name' => 'folder'));

$data = (object)array(
    'name' => $foldername,
    'intro' => '',
    'display' => FOLDER_DISPLAY_PAGE,
    'revision' => 1,
    'showexpanded' => 1,
    'files' => file_get_unused_draft_itemid(),
    'visible' => 1,
    'modulename' => 'folder',
    'module' => $moduleid,
    'section' => $sectionnum,
    'introformat' => FORMAT_HTML,
    'cmidnumber' => '',
    'groupmode' => NOGROUPS,
    'groupingid' => 0,
    'availability' => null,
    'completion' => 0,
    'completionview' => 0,
    'completionexpected' => 0,
    'conditiongradegroup' => array(),
    'conditionfieldgroup' => array(),
    'conditioncompletiongroup' => array()
);
return add_moduleinfo($data, $course, $mform = null);
Marina
  • 491
  • 3
  • 9
1

Invalid course module ID . That means moodle can find a course module record, but the cm doesn't actually exist in the course object when fetching all the course data.

What you can do to fix it is add the broken module back into a section of this course. It might be in a section that exists, then you also need to add the cmid to the sequence field. (Just add this cmid on the end of the existing sequence).

update mdl_course_modules set section=<existingsection> where id=cmid;
update mdl_course_sections set sequence='XX,YY,ZZ,cmid' where id =<existingsection>;

Then after you purge caches, you should now be able to view the module again, eg. for an assignment:

https://moodle.com/mod/assign/view.php?id=cmid

kristian
  • 11
  • 1
  • 1