File uploads: upload location in submit function
Hi.
Have been through all the "working with files" videos and now need something not covered (from what I can make out). Where your upload location is set in the managed files upload form, I need it to be set in the submit function as the directory is dependent on another field in the form. Do I have to change the $file->uri to what I want inside _submit()? How do I do this?
Thanks,
Bruce
I used a bit of your code from unmanaged file uploads and combined with the managed.
First I commented out the #upload_location in the form and added the field on which the location would depend (for my purposes it was the client identifier).
'#type' => 'select',
'#title' => t('Client'),
'#options' => $clients,
'#default_value' => $default_cid,
'#required' => TRUE
);
$form['managed_file'] = array(
'#title' => t('File'),
'#type' => 'managed_file',
'#upload_validators' => array('file_validate_extensions' => array('jpeg jpg png gif')),
// '#upload_location' => 'private://assets/managed',
'#progress_indicator' => 'bar',
'#progress_message' => 'One moment while we save your file...',
);
Next, I changed the submit function, using some of the unmanaged file code to create the directory and move the file from TMP to its permanent position
// Make the file permanent.
$file = file_load($form_state['values']['managed_file']);
$file->status = FILE_STATUS_PERMANENT;
$directory = 'private://assets/managed/'. $form_state['values']['cid'];
file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
$file->uri = file_unmanaged_copy($file->uri, $directory, FILE_EXISTS_REPLACE);
// reassign the $file->uri otherwise the managed file table entry shows the TMP location
drupal_chmod($file->uri);
file_save($file);
// Need to add an entry in the file_usage table.
file_usage_add($file, 'optitectPCA', 'image', 1);
drupal_set_message(t("Your file has been uploaded!"));
}
Awesome, thank you so much for sharing this!
Hi Bruce,
I haven't been working in the file system for several months, so I'm a bit rusty there. But it does seem like changing the URI in the submit function would be a good thing to try. Just thinking off the top of my head, you should be able to test against the values in $form_state to decide where that file should go.
Keep us posted on if you get solution figured out for this.
Cheers!
Chris