Drupal image uploader set permanent´

Written by Arvind

This happened to me every morning, every time I boot up my computer and load up the site, the logo of the site is not showing up. I think drupal is doing something in the back. I did some digging and found out that the image that I uploaded was not permanent. One solution I found was to save the file permanently and save the path on another variable.

Form Field:

$form['logo_upload'] = [
  '#title' => $this->t('Upload Logo'),
  '#description' => $this->t('Choose file'),
  '#type' => 'managed_file',
  '#name' => 'logo',
  '#size' => 20,
  '#upload_location' => 'public://img/logo',

Form Submit Function:

public function submitForm(array &$form, FormStateInterface $form_state) {
  $form_file = $form_state->getValue('logo_upload', 0);
  $logo_path = $config->getItem('logo_path');
  if (!empty($form_file) && is_array($form_file)) {
    $file = File::load($form_file[0]);
    $file_uri = $file->getFileUri();
    $image_path = file_url_transform_relative(file_create_url($file_uri));
    if ($logo_path != $image_path) {
        ->setValue('logo_path', $image_path)
        ->setValue('logo_upload', '');

I added this $image_path = file_url_transform_relative(file_create_url($file_uri)); to create a relative path and save it to logo_path variable. This development in for Drupal 8.