Skip to content

Instantly share code, notes, and snippets.

@wesruv
Created December 24, 2019 04:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wesruv/cad3e845081f4c976ccdb534e258c593 to your computer and use it in GitHub Desktop.
Save wesruv/cad3e845081f4c976ccdb534e258c593 to your computer and use it in GitHub Desktop.
<?php
// Code that accesses entity data for a template with lots of good examples of how to get information
/**
* Implements hook_preprocess_HOOK() for Paragraph templates.
*/
function THEMENAME_preprocess_paragraph(&$variables) {
$paragraphy_type = $variables['paragraph']->getType();
if ($paragraphy_type === 'hero') {
$variables['background_video'] = FALSE;
$hero_field_image_object = $variables['paragraph']->getFields()['field_image'];
$hero_field_image_data = $hero_field_image_object->getValue();
$variables['hero_media_type'] = 'null';
// Do we have a hero image/video.
if (isset($hero_field_image_data[0]['target_id'])) {
$hero_field_image_entity = \Drupal::entityTypeManager()->getStorage('media')->load($hero_field_image_data[0]['target_id']);
$variables['hero_media_type'] = $hero_field_image_entity->bundle();
// Is it a video?
if ($variables['hero_media_type'] === 'video') {
// Get a render array.
$hero_field_image_video_render = $hero_field_image_entity->field_video->view([
'label' => 'none',
'type' => 'video_embed_field_video',
'settings' => [
'autoplay' => TRUE,
'responsive' => TRUE,
],
])[0]['children'];
// If it's an externally hosted video,
// we need to provide the correct URL params.
if (isset($hero_field_image_video_render['#provider'])) {
// Apply the correct params.
switch ($hero_field_image_video_render['#provider']) {
case 'youtube':
$hero_field_image_video_render['#query'] = [
'autoplay' => 1,
'controls' => 0,
'loop' => 1,
'modestbranding' => 1,
'mute' => 1,
'rel' => 0,
];
break;
case 'vimeo':
$hero_field_image_video_render['#query'] = [
'background' => 1,
];
$hero_field_image_video_render['#attached']['library'][] = 'THEMENAME/background-vimeo-video';
break;
}
}
$variables['background_video'] = $hero_field_image_video_render;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment