CSV file upload in Moodle/Totara

| By Webner

Step 1: Firstly, create a form using forms API. Create a class that will extend the “moodleform” class defined in “../lib/formslib.php”. Then override the definition() function of this class to include your form elements.

Step 2: To browse the CSV file, use the file picker element of File API.
require_once($CFG->libdir . '/formslib.php');
class bulkupload_form extends moodleform {
function definition() {
$mform = $this->_form;
$fileoptions = array('accepted_types' => array('.csv'));
$mform->addElement('filepicker', 'fileupload', ‘File Upload’, null, $fileoptions);
$mform->setType('fileupload', PARAM_FILE);
$mform->addRule('fileupload', null, 'required');
$encodings = core_text::get_encodings();
$mform->addElement('select', 'encoding', ‘Encoding’, $encodings);
$this->add_action_buttons(true, ‘Submit’);

In the above code, we are allowing users to only select the CSV file by passing “accepted_types =>array(‘.csv’)” in options array(5th parameter of addElement() function).

Step 3: Now, on submit of this form, we will read the CSV file content by using the “csv_import_reader” class which is defined in “../lib/csvlib.class.php”.
$mform = new bulkupload_form(null);
if($formdata- = $mform->get_data()){ //Form is submitted
$importid = csv_import_reader::get_new_iid('uploadlist');
$cir = new csv_import_reader($importid, 'uploadlist');
$filecontent = $mform->get_file_content(‘fileupload’);
$readcount = $cir->load_csv_content($filecontent, $formdata->encoding, 'comma');
if (!$readcount) {
$errors[] = $cir->get_error();
$headers = $cir->get_columns();
if (!$headers) {
$errors[] = ‘Cannot parse submitted CSV file.’;
$fieldnames = array();
foreach ($headers as $header) {
$fieldnames[] = $header;
$iteration = 0;
$csvData = array();
while ($rowdata = $cir->next()) {
$iteration ++;
$csvData[] = array_combine($fieldnames, $rowdata);

Step 4: Now, data extracted from the CSV file is stored in the $csvData variable. You can save it in your database.

For example, the uploaded CSV file has two columns: ‘username’, ‘signupnote’, and two rows.

$csvData will contain the following data:

[0] => Array
[username] => student1
[signupnote] => Signup note for student1
[1] => Array
[username] => student2
[signupnote] => Signup note for student2

Leave a Reply

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