Note:

If you want to create a new page for developers, you should create it on the Moodle Developer Resource site.

Using the File API in Moodle forms: Difference between revisions

From MoodleDocs
m (Protected "Using the File API in Moodle forms": Developer Docs Migration ([Edit=Allow only administrators] (indefinite)))
 
(122 intermediate revisions by 25 users not shown)
Line 1: Line 1:
{{Moodle 2.0}}In Moodle 2.0 onwards, we introduced [[Repository API|Repository API]] to fetch files from external sources, [[Repository API|Repository API]] will move to files into draft areas, then modules will process moving draft area files into a proper file areas, this documentation will demonstrate how to do that.
{{Template:Migrated|newDocId=/docs/apis/subsystems/form/usage/files}}
 
There are three form elements involved with [[Repository API|Repository API]], they are file manager, file picker and editor, the legacy upload button will be replaced by file picker or file manager, file picker and file manager work similar, the only difference is file manager can fetch multiple files, file picker only fetch one file. Editor element is introduced to replace legacy htmleditor element, I will talk about them respectively.
 
Modules are using [[File API|File API]] for management of own files, they do not need to be aware of any repositories.
 
==Form element: file picker==
 
File picker (''filepicker'') is a direct replacement of older ''file'' formslib element. It is intended for situations when user uploads one file, the file is immediately processed and then deleted. Examples are upload of users and grades from csv file.
 
=== Add filepicker element ===
 
<code php>
$mform->addElement('filepicker', 'userfile', get_string('file'));
</code>
 
=== Obtaining picked file ===
 
The API for getting file contents is exactly the same as for ''file'' element.
 
<code php>
$content = $mform->get_file_content('userfile');
</code>
 
==Form element: file manager==
File manager (''filemanager'') element is an improved file picker, the difference is it can be used for managing of one or more files. It is expected that the files are stored permanently for future use. Examples of use are forum and glossary attachments.
 
=== Create file manager element in moodle form ===
 
<code php>
$mform->addElement('filemanager', 'attachments', get_string('attachment', 'moodle'),
    array('subdirs' => 0, 'maxbytes' => $maxbytes, 'maxfiles' => 50, 'filetypes' => '*'));
</code>
You can specify what file types are accepted by filemanger, all file types are listed at moodle/lib/file/file_types.mm, this is a freemind file, you can edit it freely, the changes will be reflected in moodle.
 
=== Load existing files into draft area ===
 
<code php>
if (empty($entry->id)) {
  $entry = new object();
  $entry->id = null;
}
 
$draftitemid = file_get_submitted_draft_itemid('attachments');
file_prepare_draft_area($draftitemid, $context->id, 'glossary_attachment', $entry->id , false);
$entry->attachements = $draftitemid;
 
$mform->set_data($entry);
 
</code>
 
=== Store updated set of files ===
# Call file_get_draft_area_info to get how many files in this draft area
# Call file_save_draft_area_files to copy the files to their permanent home in a real file area.
 
==Form element: editor==
 
When using editor element you  need to preprocess and postprocess the data:
# detect if form was already submitted (usually means draft is area already exists) - ''file_get_submitted_draft_itemid()''
# prepare draft file area, temporary storage of all files attached to the text - ''file_prepare_draft_area()''
# convert encoded relative links to absolute links - ''file_prepare_draft_area()''
# create form and set current data
# after submission the changed files must be merged back into original area - ''file_save_draft_area_files()''
# absolute links have to be replaced by relative links - ''file_save_draft_area_files()''
 
===Replace old htmleditor with editor===
 
The file picker has been integrated with with TinyMCE to make the editor element. This new element should support all types on editors and should be able to switch them on-the-fly. Instances of the old htmleditor element in your forms should be replaced by the new editor element, this may need adding of new format and trusttext columns. For example:
<code php>
$mform->addElement('editor', 'message', get_string('message', 'forum'),
        array('maxfiles' => EDITOR_UNLIMITED_FILES, 'filearea' => 'forum_post'));
</code>
The editor element can take following options: maxfiles, maxbytes, filearea, subdirs and changeformat. Please note that the embedded files is optional feature and is not expected be used everywhere.
 
'''Note''': the editor element now includes text format option. You should no longer use the separate format element type.
 
===Prepare current data===
 
To retrieve editor content, you need to use following code:
<code php>
$mform = new mod_forum_post_form('post.php', array('course'=>$course, 'cm'=>$cm, 'coursecontext'=>$coursecontext, 'modcontext'=>$modcontext, 'forum'=>$forum, 'post'=>$post));
 
$draftitemid = file_get_submitted_draft_itemid('message');
file_prepare_draft_area($draftitemid, $modcontext->id, 'forum_post', empty($post->id)?null:$post->id , false);
 
//....
 
if ($fromform = $mform->get_data()) {
    // content of editor
    $messagetext = $fromform->message['text'];
    // format of content
    $messageformat  = $fromform->message['format'];
    // draft itemid
    $messageitemid = $fromform->message['itemid'];
}
</code>
If there are multiple files, they will share the same itemid.
 
===Save the draft files===
 
When a user selects a file using the file picker, the file is initially stored in a draft file area, and a URL is inserted into the HTML in the editor that lets the person editing the content (but no one else) see the file.
 
When the user submits the form, we then need to save the draft files to the correct place in permanent storage. (Just like you have to call $DB->update_record('tablename', $data); to have the other parts of the form submission stored correctly.)
 
The save_files_from_draft_area function does this.
<code php>
$messagetext = file_save_draft_area_files($post->message['itemid'],
        $context->id, 'proper_file_area', $post->id, true, $post->message['text']);
</code>
; $post->message['itemid'] : is the variable we retrieved above.
; $context->id, 'proper_file_area' and $post->id : correspond to the contextid, filearea and itemid columns in the [[File_API#Table:_files|files table]].
; $post->message['text'] : this is the message text. As the files are saved to the real file area, the URLs in this content are rewritten.
 
All URLs in content that point to files managed to the File API are converted to a form that starts '@@PLUGINFILE@@/' before the content is stored in the database. That is what we mean by rewriting.
 
===Move files into draft area===
 
In the section about the editor form element, we skipped over a stage, becuase we must prepare the draft area before we show the form, and copy any existing files into it.
 
The function to do that is prepare_draft_area, which is the opposite of save_files_from_draft_area:
<code php>
$draftitemid = file_get_submitted_draft_itemid('elementname');
file_prepare_draft_area($draftitemid, $context->id, $filearea, $itemid);
</code>
; $draftitemid : may be 0, in which case a new one will be created automatically. Normally you get this with file_get_submitted_draft_itemid.
; $context->id, $filearea and $itemid : correspond to the contextid, filearea and itemid columns in the [[File_API#Table:_files|files table]].
; $messagetext : as with save_files_from_draft_area, this function will rewrite the links in some content if you pass some content in. In this case, the links are rewritten from the '@@PLUGINFILE@@/' form to point to the actual files in the draft area.
 
===Convert relative links starting with @@PLUGINFILE@@ into correct format===
 
Before content is displayed to the user, any URLs in the '@@PLUGINFILE@@/' form in the content need to be rewritten to the real URL where the user can access the files.
<code php>
$messagetext = file_rewrite_pluginfile_urls($messagetext, 'pluginfile.php',
        "$context->id/proper_file_area/$itemid/");
</code>
; $messagetext : is the content containing the @@PLUGINFILE@@ URLs from the database.
; 'pluginfile.php' : there are a number of different scripts that can serve files with different permissions checks. You need to specify which one to use.
; "$context->id/proper_file_area/$itemid/" : uniquely identifies the file area, as before.
 
== See also ==
 
* [[File API]]
* [[Using the file API]]
* [[Repository API]]
* [[Portfolio API]]
* MDL-14589 - File API Meta issue
 
{{CategoryDeveloper}}
[[Category:Files]]
[[Category:Repositories]]

Latest revision as of 12:57, 16 January 2023

Important:

This content of this page has been updated and migrated to the new Moodle Developer Resources. The information contained on the page should no longer be seen up-to-date.

Why not view this page on the new site and help us to migrate more content to the new site!