I have a custom module in Drupal 8. I am creating a file upload field with below code. Once file is uploaded and form data is saved, i can see uploaded image and path, so i can retrieve the image where ever i need in the front end. But after couple of hours image is deleting automatically from the folder location even i set the status to permanent.

$form['basic']['background_image'] = array(
'#type' => 'managed_file',
'#name' => 'background_image',
'#default_value' => $config->get('background_image'),
'#title' => t('Banner image'),
'#upload_location' => 'public://general',
'#required' => TRUE,

public function submitForm(array &$form, FormStateInterface $form_state) {
$config = \Drupal::service('config.factory')->getEditable('custom.settings');

$bgfile = file_load($form_state->getValue('background_image'));
$bgfile->status = FILE_STATUS_PERMANENT;

$config->set('background_image', $form_state->getValue('background_image'))
parent::submitForm($form, $form_state);

Can you please help me on this ?


bhanojeerao created an issue. See original summary.

serg2’s picture

swentel’s picture

Category: Bug report » Support request
Priority: Critical » Normal
Status: Active » Fixed

Well, half duplicate.

What you need todo after setting it to file_permanent, is call $bgfile->save() on the file object so the file is effectively marked as that.

bhanojeerao’s picture

Image should be saved permanently in the mentioned location. If i use $bgfile->save(), then i am getting "Fatal error: Call to undefined method stdClass::save()". Do i need to include anything ? I am implementing this code in custom module block.

swentel’s picture

Well, then it means something is wrong with the $file itself, maybe it's not a file object at all.
Also you should be able to use setPermanent() on that object.

bhanojeerao’s picture

Issue fixed myself, these few lines saved my time. It may help others.

$getbgfile = $form_state->getValue ('background_image');
$bgfile = File::load ($getbgfile[0]);
$file_usage = \Drupal::service('file.usage');
if(gettype($bgfile) == 'object'){
$file_usage->add($bgfile, 'nau', 'file', $getbgfile[0]);

And we should use: use Drupal\file\Entity\File;

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.