Skip to content

Instantly share code, notes, and snippets.

@cyberlex404
Created September 17, 2016 18:11
Show Gist options
  • Select an option

  • Save cyberlex404/4f6e843fc89aa582a553a28de4135416 to your computer and use it in GitHub Desktop.

Select an option

Save cyberlex404/4f6e843fc89aa582a553a28de4135416 to your computer and use it in GitHub Desktop.
Блок с контекстом
<?php
namespace Drupal\hoover\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\file\Entity\File;
use Drupal\image\Entity\ImageStyle;
use Drupal\Core\Entity\Query\QueryInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Template\Attribute;
/**
* Provides a 'HooverMediaBlock' block.
*
* @Block(
* id = "hoover_media_block",
* admin_label = @Translation("Hoover media block"),
* context = {
* "hoover" = @ContextDefinition(
* "entity:node",
* label = @Translation("Hoover Node")
* )
* }
* )
*/
class HooverMediaBlock extends BlockBase {
/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
return [
'large_style' => 'hoover_medium',
'thumbnail' => 'thumbnail',
];
}
/**
* {@inheritdoc}
*/
public function blockForm($form, FormStateInterface $form_state) {
$image_styles = \Drupal::entityQuery('image_style')->execute();
// dpm($image_styles);
$form['large_style'] = [
'#type' => 'select',
'#title' => $this->t('Image style'),
'#options' => $image_styles,
'#description' => $this->t('Image style'),
'#default_value' => $this->configuration['large_style'],
];
$form['thumbnail'] = [
'#type' => 'select',
'#title' => $this->t('Thumbnail Image style'),
'#options' => $image_styles,
'#description' => $this->t('Thumbnail Image style'),
'#default_value' => $this->configuration['thumbnail'],
];
return $form;
}
/**
* {@inheritdoc}
*/
public function blockSubmit($form, FormStateInterface $form_state) {
$this->configuration['large_style']
= $form_state->getValue('large_style');
$this->configuration['thumbnail']
= $form_state->getValue('thumbnail');
}
/**
* {@inheritdoc}
*/
public function build() {
$build = [];
$hoover = $this->getContextValue('hoover');
if($hoover->hasField('field_photos')) {
$node = $hoover->toArray();
$photos = $node['field_photos'];
foreach ($photos as $key => $photo) {
$file = File::load($photo['target_id']);
$photos[$key]['large_img'] = ImageStyle::load($this->configuration['large_style'])->buildUrl($file->getFileUri());
$photos[$key]['thumbnail'] = ImageStyle::load($this->configuration['thumbnail'])->buildUrl($file->getFileUri());
$classes = array(
'fid-' . $file->id(),
);
$photos[$key]['attributes'] = new Attribute($photos[$key]['attributes']);
$photos[$key]['attributes']->addClass($classes);
}
$build['hoover_media_block'] = array(
'#theme' => 'hoover_media_block',
'#items' => $photos,
);
}
return $build;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment