In a custom subtheme of classy base theme, I made a theme setting for referencing an image media file. Contents of file theme-settings.php:
<?php
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Theme\ThemeSettings;
use Drupal\system\Form\ThemeSettingsForm;
use Drupal\Core\Form;
function mytheme_form_system_theme_settings_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
$opts = [
'#type' => 'entity_autocomplete',
'#title' => t("Image on startpage"),
'#description' => t("Referencing an image."),
'#target_type' => 'media',
'#selection_settings' => ['target_bundles' => ['image']],
];
if ($default_id = theme_get_setting('startpage_image')) {
// 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['startpage_image'] = $opts;
}
?>
Contents of file mytheme.theme:
<?php
function mytheme_preprocess_page(&$variables) {
$media_id = theme_get_setting('startpage_image');
$media = \Drupal::entityTypeManager()->getStorage('media')->load($media_id);
$variables['media_build'] = \Drupal::entityTypeManager()->getViewBuilder('media')->view($media, 'media.full');
}
?>
And finally in the template page--front.html.twig
the image is called by {{ startpage_image }}
. But unfortunately, the image isn't shown (all caches rebuilt and flushed multiple times). In the last line in file mytheme.theme I also tried view($media, 'full')
because I wasn't sure if media.full
is the correct display mode that is built in into media core module — but this as well wasn't successfull.
Why is my code not working?