Moodle php code : To create a course with enrolment method and course overview file


// 1: category object

$cat = $DB->get_record("course_categories", array("id" => <get category>));
   
        $catcontext  = \context_coursecat::instance($cat->id);
   
     // Prepare course and the editor.
        $editoroptions = array('maxfiles' => EDITOR_UNLIMITED_FILES, 'maxbytes' => $CFG->maxbytes, 'trusttext' => false, 'noclean' => true);
        // Editor should respect category context if course context is not set.
        $editoroptions['context'] = $catcontext;
        $editoroptions['subdirs'] = 0;

        $data = new \stdClass();
        $data->summary_editor['text'] = "course description";
        $data = file_prepare_standard_editor($data, 'summary', $editoroptions, null, 'course', 'summary', null);

        $data->fullname = "Course FullName";
        $data->idnumber = "Course id number";
        $data->shortname = "Course shortname :Unique";
        $data->category = $cat->id;
        $data->startdate = time();
        $data->format = 'topic';
        $data->lang = '';
        $data->showgrades = '1';
        $data->showreports = '0';
        $data->enablecompletion = '1';
        $data->groupmode = '0';
        $data->tags =array("Sample Course")
       
        $course = create_course($data, $editoroptions);
        
        // once the course has been created let 's create and enrolment method
// if you want to add any enrolment method which is not created at course creation automatically

        $enrolM = enrol_get_plugin('manual');
        $fields = array('status' => ENROL_INSTANCE_ENABLED, 'enrolperiod' => $enrolM->get_config('enrolperiod', 0), 'roleid' => $enrolM->get_config('roleid', 0));
        $enrolM->add_instance($course, $fields);

// Course over view image
$image = file_get_contents("/var/www/html/a.png");
         if($image){
            $fs = get_file_storage();
            $coursecontext = \context_course::instance($course->id);
            $file_record = new \stdClass;
            $file_record->component = 'course';
            $file_record->contextid = $coursecontext->id;
            $file_record->userid = $USER->id; // logged in User
            $file_record->filearea = 'overviewfiles';
            $file_record->filename = "oveerview.png";
            $file_record->filepath = '/';
            $file_record->itemid = 0;
            $file_record->license = $CFG->sitedefaultlicense;
            $file_record->author = fullname($USER);
            $file_record->source = '';
            $fs->create_file_from_string($file_record, $image);
           
        }

Leave a Reply

Your email address will not be published. Required fields are marked *