|
<?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; |
|
} |
|
} |