Score:0

Referencing media from theme settings and display it on front page

mx flag

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?

Score:1
li flag

First you should add a test to see if it's the homepage or not, using

\Drupal::service('path.matcher')->isFrontPage()

Then if you add a variables in your hook_page for exemple $variables['media_build'] you could get in the twig with {{ media_build }}.

Madam Adam avatar
mx flag
Thank you, now it's working!
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.