Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A Drupal 8 block plugin which needs to be shown only on node pages (using context)
<?php
namespace Drupal\my_module\Plugin\Block;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\node\NodeInterface;
use Drupal\my_module_lists\ProfilesService;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides a 'TextAdsBlock' block.
*
* @Block(
* id = "text_ads",
* admin_label = @Translation("Text Ads"),
* category = @Translation("Ads"),
* context_definitions = {
* "node" = @ContextDefinition("entity:node", label = @Translation("Node"))
* }
* )
*/
class TextAdsBlock extends BlockBase implements ContainerFactoryPluginInterface {
/**
* Drupal\my_lists\ProfilesService definition.
*
* @var \Drupal\my_lists\ProfilesService
*/
protected $profilesService;
public function __construct(
array $configuration,
$plugin_id,
$plugin_definition,
ProfilesService $profiles_service
) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->profilesService = $profiles_service;
}
/**
* {@inheritdoc}
*/
public function blockAccess(AccountInterface $account) {
return AccessResult::allowedIf($this->getContextValue('node')->bundle() == 'my_node_type');
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('my_lists.profiles')
);
}
/**
* {@inheritdoc}
*/
public function build() {
$location = $this->getLocation($this->getContextValue('node'));
$profiles = empty($location)
? $this->profilesService->getProfiles()
: $this->profilesService->getProfilesInLocation($location['country_code'], $location['administrative_area'], $location['locality']);
shuffle($profiles);
// If there are no profiles, we don't want to render anything at all.
return count($profiles) ? [
'#theme' => 'text_ads',
'#profiles' => array_slice($profiles, 0, 20),
] : NULL;
}
/**
* {@inheritdoc}
*
* Let's cache this block for a definite time.
*/
public function getCacheMaxAge() {
return 43200;
}
protected function getLocation(NodeInterface $node) : array {
$location = $node->get('field_location')->getValue();
return $location ? $location[0] : [];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.