I used a form controller to store an image in configuration settings. Like so.

public function buildForm(array $form, FormStateInterface $form_state) {

$config = $this->config('custom.settings');

$form['icon'] = [
   '#type' => 'managed_file',
   '#default_value' => $config->('icon'),
   '#upload_location' => 'public://',


public function submitForm(array&$form, FormStateInterface $form_state){
        if (!empty($form_state->getValue('icon'))) {
            $image_fid = $form_state->getValue('icon');

            $file_name = File::load($image_fid[0])->getFilename();
            $file_url  = '/sites/default/files'.$file_name;

            $file_uri = File::load($image_fid[0])->getFileUri();
            file_save_data(file_get_contents($file_uri), $file_uri, FILE_EXISTS_REPLACE);
                 ->set('icon', $form_state->getValue('icon'))

            $file       = \Drupal\file\Entity\File::load($image_fid[0]);
            $file_usage = \Drupal::service('file.usage');
            $file_usage->add($file, 'Standard', 'file', $image_fid[0]);

I then attempt to grab the file in my .theme file to be used in twig templates like so

function AAEP_foundation_preprocess_page(&$variables){  
    $variables['icons'] = [
        'icon1_file' => \Drupal::config('foundation.settings')->get('icon'),

I then use {{ icons.icon1_file[0] }} in my template but it only produces the file ID rather than the actual url to the image. Also after searching through sites/default/files I can't seem to find the images that were meant to uploaded so I'm concerned that the files were not actually saved. How would I get the URL based on the image id? Also is there any issue with how I saved the file in submitForm()?

  • Does this not answer your question: drupal.stackexchange.com/questions/105064/… ??
    – bleen
    Sep 19, 2016 at 20:01
  • I believe that answer is for drupal 7
    – Amy
    Sep 19, 2016 at 20:10
  • Sorry bout that ... how bout this: $file_url = File::load($image_fid[0])->url();
    – bleen
    Sep 19, 2016 at 20:11
  • I can't see where your $file_url variable is used.
    – Jonathan
    Sep 20, 2016 at 10:55


Your Answer

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

Browse other questions tagged or ask your own question.