3 namespace Drupal\{{ machine_name }}\Plugin\Block;
5 use Drupal\Core\Access\AccessResult;
6 use Drupal\Core\Block\BlockBase;
7 use Drupal\Core\Form\FormStateInterface;
8 use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
9 use Drupal\Core\Routing\RouteMatchInterface;
10 use Drupal\Core\Session\AccountInterface;
11 use Symfony\Component\DependencyInjection\ContainerInterface;
14 * Provides a '{{ plugin_label }}' block.
17 * id = "{{ plugin_id }}",
18 * admin_label = @Translation("{{ plugin_label }}"),
19 * category = @Translation("{{ category }}")
22 class {{ class }} extends BlockBase implements ContainerFactoryPluginInterface {
27 * @var \Drupal\Core\Routing\RouteMatchInterface
29 protected $routeMatch;
32 * Constructs a new {{ class }} instance.
34 * @param array $configuration
35 * The plugin configuration, i.e. an array with configuration values keyed
36 * by configuration option name. The special key 'context' may be used to
37 * initialize the defined contexts by setting it to an array of context
38 * values keyed by context names.
39 * @param string $plugin_id
40 * The plugin_id for the plugin instance.
41 * @param mixed $plugin_definition
42 * The plugin implementation definition.
43 * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
46 public function __construct(array $configuration, $plugin_id, $plugin_definition, RouteMatchInterface $route_match) {
47 parent::__construct($configuration, $plugin_id, $plugin_definition);
48 $this->routeMatch = $route_match;
54 public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
59 $container->get('current_route_match')
66 public function defaultConfiguration() {
68 'content' => $this->t('Hello world!'),
75 public function blockForm($form, FormStateInterface $form_state) {
77 '#type' => 'textarea',
78 '#title' => $this->t('Block content'),
79 '#default_value' => $this->configuration['content'],
87 public function blockSubmit($form, FormStateInterface $form_state) {
88 $this->configuration['content'] = $form_state->getValue('content');
94 * @DCG Remove this method of you do not need any access restrictions.
96 protected function blockAccess(AccountInterface $account) {
97 $route_name = $this->routeMatch->getRouteName();
98 // Display the block only for anonymous users.
99 if ($account->isAnonymous() && $route_name != 'user.register') {
100 return AccessResult::allowed()
101 ->addCacheContexts(['route.name', 'user.roles:anonymous']);
103 return AccessResult::forbidden();
109 public function build() {
110 $build['content'] = [
111 '#markup' => $this->configuration['content'],