Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace Drupal\insa_blocks\Plugin\Block;
- use Drupal\Core\Block\BlockBase;
- use Drupal\media_entity\Entity\Media;
- use Drupal\file\Entity\File;
- use Drupal\Core\Cache\Cache;
- /**
- * Provides a 'Banner' block.
- *
- * @Block(
- * id = "banner",
- * admin_label = @Translation("Banner"),
- * )
- */
- class Banner extends BlockBase {
- /**
- * {@inheritdoc}
- */
- public function build() {
- $build = [];
- // Cas node uniquement.
- if ($node = \Drupal::service('current_route_match')->getParameter('node')) {
- // load the node.
- if (!method_exists($node, 'getType')) {
- $node = \Drupal\node\Entity\Node::load($node);
- }
- $node_type = $node->getType();
- // Vérification si field_banner est renseigné.
- if (!empty($node->field_banner[0]->target_id)) {
- $media_id = $node->field_banner[0]->target_id;
- $media = \Drupal::entityTypeManager()->getStorage('media')->load($media_id);
- $build['banner'] = \Drupal::entityTypeManager()->getViewBuilder('media')->view($media, 'wide');
- }
- else {
- $fid = FALSE;
- // Image par défaut.
- if (!empty(\Drupal::config('insa_config.adminsettings')->get($node_type)[0])) {
- $fid = \Drupal::config('insa_config.adminsettings')->get($node_type)[0];
- }
- if ($fid) {
- // Chargement de l'image.
- $file = File::load($fid);
- if ($file) {
- $build['banner'] = [
- '#theme' => 'responsive_image',
- '#uri' => $file->getFileUri(),
- '#responsive_image_style_id' => 'wide',
- ];
- }
- }
- }
- }
- return $build;
- }
- /**
- *
- */
- public function getCacheTags() {
- // With this when your node change your block will rebuild.
- if ($node = \Drupal::routeMatch()->getParameter('node')) {
- if (method_exists($node, 'id')) {
- // If there is node add its cachetag.
- return Cache::mergeTags(parent::getCacheTags(), array('node:' . $node->id()));
- } else {
- return Cache::mergeTags(parent::getCacheTags(), array('node:' . $node));
- }
- }
- else {
- // Return default tags instead.
- return parent::getCacheTags();
- }
- }
- /**
- *
- */
- public function getCacheContexts() {
- // If you depends on \Drupal::routeMatch()
- // you must set context of this block with 'route' context tag.
- // Every new route this block will rebuild.
- return Cache::mergeContexts(parent::getCacheContexts(), array('route'));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement