
// Code template for managing the form with filepicker
// ---------------------------------------------------

// From http://docs.moodle.org/dev/Using_the_File_API_in_Moodle_forms#filemanager
$itemid = 0; // This is used to distinguish between multiple file areas, e.g. different student's assignment submissions, or attachments to different forum posts, in this case we use '0' as there is no relevant id to use

// Fetches the file manager draft area, called 'attachment'
$draftitemid = file_get_submitted_draft_itemid('attachment');

// Copy all the files from the 'real' area, into the draft area
file_prepare_draft_area($draftitemid, $context->id, '{{ id }}', 'attachment', $itemid, $filemanageropts);

// Prepare the data to pass into the form - normally we would load this from a database, but, here, we have no 'real' record to load
$entry = new stdClass();
$entry->attachments = $draftitemid; // Add the draftitemid to the form, so that 'file_get_submitted_draft_itemid' can retrieve it

// Set form data
// This will load the file manager with your previous files
$mform->set_data($entry);

// ----------
// Form Submit Status
// ----------
if ($mform->is_cancelled()) {
    // CANCELLED
} else if ($data = $mform->get_data()) {
    // SUCCESS
    //In this case you process validated data. $mform->get_data() returns data posted in form

    // Save the files submitted
    file_save_draft_area_files($draftitemid, $context->id, '{{ id }}', 'attachment', $itemid, $filemanageropts);
} else {
    // FAIL / DEFAULT
    $mform->display();
}
