I have a block plugin that allows users to upload an image to be used as a background. Below is what is inside my blockForm function.

    $form = [
        'image' => [
            '#type' => 'managed_file',
            '#title' => 'Image',
            '#upload_location' => 'public://my_style/images',
            '#default_value' => $this->configuration['image'],

And my block submit function is as follows.

public function blockSubmit($form, FormStateInterface $form_state) {
    $values = $form_state->getValues();

    foreach ($values as $index => $value) {
        $this->configuration[$index] = $value;

Initially this works just fine. The image is uploaded and appears in the background of my block plugin. However overnight it's always deleted. I did see this post Set image as permanent in custom block plugin, temporary URI however I don't see anything different that would cause issues with my code against the one provided in that post. Is there something missing? Or is there anything wrong with how I'm performing the submit function.

I suppose I could try to check if the formstate value is a file and then load the file and then set it to permanent and then save it. But even if that works why would it be necessary in this case but not in others?

1 Answer 1


As you guessed its must to set permanent while saving the file. You need to include, $file = File::load( $fid ); if ($file) { $file->setPermanent(); $file->save(); }

The files will be added to the {file_managed} table as temporary files. Temporary files are periodically cleaned. Use the 'file.usage' service to register the usage of the file which will automatically mark it as permanent.

  • Unfortunately after implementing this the issue wasn't resolved. Here's what I added to my block submit function. public function blockSubmit($form, FormStateInterface $form_state) { $values = $form_state->getValues(); foreach ($values as $index => $value) { $this->configuration[$index] = $value; $file = File::load($value); if ($file) { $file->setPermanent(); $file->save(); } else { } } }
    – Amy
    Commented Oct 23, 2017 at 15:40
  • Did you check what you get on $file? If you could, pls check the file_managed table with your $value against fid column and check if the status changed to 1.Also pls check JayKandari's comment in this link drupal.stackexchange.com/questions/198135/…
    – Kana
    Commented Oct 23, 2017 at 17:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.