1

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); $this->config('foundation.settings') ->set('icon', $form_state->getValue('icon')) ->save(); $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()?

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

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.