In a custom theme (Drupal 8.4.3) I would like to add a theme setting, where I can reference (not upload) an image to use as a background image. Like in a normal reference field, already uploaded images should be choosable; these images are stored in media entities. How can I build such a theme setting? I only found information about Uploading images in theme settings.


I haven't been able to find an example of this, either, but here's a simple demo setting a reference to a media/image in theme settings (with the autocomplete widget):

use Drupal\Core\Form\FormStateInterface;

function THEME_form_system_theme_settings_alter(&$form, FormStateInterface &$form_state, $form_id = NULL) {
  // Work-around for a core bug affecting admin themes. See issue #943212.
  if (isset($form_id)) {

  $opts = [
    '#type'          => 'entity_autocomplete',
    '#title'         => t("Call to Action Background"),
    '#description'   => t("Default call to action background media image; may be overridden on individual elements."),
    '#target_type'   => 'media',
    '#selection_settings' => ['target_bundles' => ['image']],
  if ($default_id = theme_get_setting('call_to_action_background')) {
    // element stores an int ID, but default value has to be the loaded entity
    $image = \Drupal::entityTypeManager()->getStorage('media')->load($default_id);
    $opts['#default_value'] = $image;
  $form['call_to_action_background'] = $opts;


To retrieve and render, use a THEME_preprocess hook with parameter &$variables:

$media_id = theme_get_setting('call_to_action_background');
$media = \Drupal::entityTypeManager()->getStorage('media')->load($media_id);
$variables['media_build'] = \Drupal::entityTypeManager()->getViewBuilder('media')->view(‌​$media, 'some_media_display_mode');

The render array is then available in twig:

{{ media_build }}
  • Thank you very much. Do you also know how to retrieve the image in a function like THEME_preprocess_html()? – Madam Adam Dec 1 '18 at 9:07
  • Well, can't get that to format. I'll update the answer above. – ahebrank Dec 2 '18 at 14:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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