Skip to content

Instantly share code, notes, and snippets.

@4aficiona2
Last active April 12, 2017 12:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 4aficiona2/e6855c9b0f6a6158ba98fe602c52ed38 to your computer and use it in GitHub Desktop.
Save 4aficiona2/e6855c9b0f6a6158ba98fe602c52ed38 to your computer and use it in GitHub Desktop.
Random Teaser Image Field for Drupal 8 (valid for content type teaserbox in viewmode teaser)
<?php
namespace Drupal\yokai_helper\Plugin\DsField;
use Drupal\Component\Utility\UrlHelper;
use Drupal\Component\Utility\Html;
use Drupal\Core\Url;
use Drupal\ds\Plugin\DsField\DsFieldBase;
// more details here:
// https://github.com/upchuk/d8-demo-modules/tree/master/demo/src/Plugin/DsField
// http://bramg.github.io/reveal.js/#/9
/**
* Plugin that renders a random image out of multiple (or just one) multi value image field.
*
* @DsField(
* id = "teaserbox_random_image",
* title = @Translation("Teaserbox random image"),
* entity_type = "node",
* provider = "yokai_helper"
* )
*/
class TeaserboxRandomImage extends DsFieldBase {
/**
* {@inheritdoc}
*/
public function build() {
$random_teaser_image = array();
$node = $this->entity();
if ($node) {
// get images from field_teaserbox_img
$images = $node->get('field_teaserbox_img');
if($images) {
// pick a random image from all images
$randomImageNumber = rand(0, ($images->count() - 1));
$image = $images[$randomImageNumber]->entity;
$variables = array(
'responsive_image_style_id' => 'squared',
'uri' => $image->getFileUri(),
);
// The image.factory service will check if our image is valid.
$picture = \Drupal::service('image.factory')->get($image->getFileUri());
if ($picture->isValid()) {
$variables['width'] = $picture->getWidth();
$variables['height'] = $picture->getHeight();
}
else {
$variables['width'] = $variables['height'] = NULL;
}
$random_teaser_image = [
'#theme' => 'responsive_image',
'#width' => $variables['width'],
'#height' => $variables['height'],
'#responsive_image_style_id' => $variables['responsive_image_style_id'],
'#uri' => $variables['uri'],
];
}
}
// return responsive image array
return array(
$random_teaser_image
);
}
/**
* {@inheritdoc}
*/
public function isAllowed() {
if ($this->bundle() != 'teaserbox') {
return FALSE;
}
else if ($this->viewMode() != 'teaser') {
return FALSE;
}
return TRUE;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment