I have a custom module and I want a field to upload a picture. Chrome appears to upload the file, but it’s not working and I get the error below. Can someone please point me in the right direction?
function nafa_adoption_form($form_state)
{
$form['#attributes'] = array('enctype' => "multipart/form-data");
...
$form['picture'] = array(
'#type' => 'file',
'#title' => t('Picture'),
'#size' => 20,
'#upload_location' => 'public://uploads'
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Save'),
);
return $form;
}
Submit function:
function nafa_adoption_form_submit($form, &$form_state)
{
dvm($form_state['values']); //field 'picture' is blank
$file = file_load($form_state['values']['picture']);
$file->status = FILE_STATUS_PERMANENT;
file_save($file);
$fileid = file_load($file);
variable_set('adoption_picture', $fileid->uri);
if ($file)
{
drupal_set_message("File uploaded ");
}
else
{
drupal_set_message("File could not be uploaded");
}
drupal_set_message(t('Your form has been saved.'));
}
I also get the following error:
Notice: Undefined property: stdClass::$uri in file_save() (line 573 of /home/amn7940/nafa.achristiansen.com/includes/file.inc).
If you look at the docs for the
fileelement type you’ll notice there is no#upload_locationproperty. This is because when using afiletype you are expected to move the temporary file into the permanent location yourself.From the code you’re using in your submit function I’m pretty sure you’re looking for the
managed_filetype. If you use that instead your code should start working perfectly: