File upload - Form

File upload - Form

by Linux Educacional -
Number of replies: 4

I made a form containing file uploads via filepicker.

But I can not work with the files.

How do? following codes:

Form.php

require_once("$CFG->libdir/formslib.php");
 
class simplehtml_form extends moodleform {
 
    function definition() {
        global $CFG;
 
        $mform =& $this->_form; // Don't forget the underscore! 
		$mform->addElement('hidden','id','0');
		$mform->addElement('text', 'nome', get_string('nome_parceiro'), 'maxlength="100" size="91" ');
		$mform->addElement('htmleditor', 'descricao', get_string('descricao'), 'wrap="virtual" rows="40" cols="50"');
		$mform->addElement('filepicker', 'image', get_string('files'));
        $buttonarray=array();
		$buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
		$buttonarray[] = &$mform->createElement('cancel');
		$mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
		$mform->closeHeaderBefore('buttonar');
 
    }                           // Close the function
}  


File edit.php

require_once('form.php');
$mform = new simplehtml_form();//name of the form you defined in file above.
//default 'action' for form is strip_querystring(qualified_me())

$p = optional_param('p', null, PARAM_INT);
if (!empty($p)) {
    if ($idparceiro = $DB->get_record_sql('SELECT * FROM {parceiros} WHERE id='.$p)) {
		$mform->set_data($idparceiro);
		$mform->display();
    } else {
			echo 'Não foi possível localizar';
	}
} else {
	if ($mform->is_cancelled()){
		//you need this section if you have a cancel button on your form
		//here you tell php what to do if your user presses cancel
		//probably a redirect is called for!
		redirect($CFG->wwwroot.'/a');
	}
	else if ($fromform=$mform->get_data()){
        $par = new stdClass();
		$par->id = $fromform->id;
		$par->nome         = $fromform->nome;
        $par->descricao    = $fromform->descricao;
        $par->image        = $fromform->image;		
		if ($par->id != 0) {
			if (!$DB->update_record('parceiros', $fromform)) {
				print_error('Erro ao atualizar');
			} else {
				echo 'Alterado com sucesso';
			}
		} else {
			$newid = $DB->insert_record('parceiros', $par);
			echo 'Inserido sobre id numero: '.$newid.'';
		}
	} else {
		$mform->display();
	}
}
 


How to fix? and then how to view files?


Average of ratings: -
In reply to Linux Educacional

Re: File upload - Form

by Davo Smith -
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers

If you want to do some processing to the file and then discard it, then take a look at the documentation here:

http://docs.moodle.org/dev/Using_the_File_API_in_Moodle_forms#filepicker

If you want to associate your file with your record for use in the future (and possibly allow users to go back later and update the image), then you should probably use a filemanager instead of a filepicker:

http://docs.moodle.org/dev/Using_the_File_API_in_Moodle_forms#filemanager

The best way to learn how to use these, is to search for somewhere that uses them already (e.g. the user profile form or the forum post form) and then see how they do it.

Average of ratings: Useful (1)
In reply to Davo Smith

Re: File upload - Form

by Linux Educacional -

Thanks for the quick response. I have looked at these links 100 times and could not understand.

In reply to Linux Educacional

Re: File upload - Form

by Davo Smith -
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers

OK. The first thing to realise is that you won't be saving the details of the image in your 'parceiros' table.

What you do instead, is store the details of the image in the 'files' table and reference it by the following imformation:

  • the name of your plugin (I'll call it 'mod_mymodname' below, but you will have to insert the correct name)
  • the contextid of the particular instance of your plugin
  • a file area (this can be any name you like, as long as you keep it the same - I'll call it 'imagearea')
  • (optional) an item id

So assuming the form has been submitted, you should be able to call the following (after you have inserted / updated your record - note I assume that you have set $par->id to the $newid when inserting a new record):

$context = get_context_instance(CONTEXT_MODULE, $cm->id);
$formitemname = 'image';
$filearea = 'imagearea';
$filepath = '/';
$filename = null;  // This means 'get from the uploaded file'
$mform->save_stored_file('image', $context->id, 'mod_mymodname', $filearea, $par->id, $filepath, $filename);

When you come to display the file, you will need to do two things.

First, detect the file exists and output a URL to retreive it:

$fs = get_file_storage();
$files = $fs->get_area_files($context->id, 'mod_mymodname', 'imagearea', $par->id, 'id', false);
foreach ($files as $file) {
  $url = make_pluginfile_url($file->get_contextid(), $file->get_component(), $file->get_filearea(), $file->get_itemid(), $file->get_filepath(), $file->get_filename());
  echo html_writer::empty_tag('img', array('src' => $url));

Finally, add some code to your plugins 'lib.php' file to check the user is allowed to access the file and send it back to their browser:

function mod_mymodname_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload) {
// look inside any standard lib.php to see how to write this function

 

   

Average of ratings: Useful (1)
In reply to Davo Smith

Re: File upload - Form

by Linux Educacional -

Expressed myself poorly, would not be a module, but a plugin site.

I know that the process would be similar but could not.

Sorry, the code in the topic could make the insert, update, delete and view. But working with files in moodle for me is still a mystery.