Skip to content

Instantly share code, notes, and snippets.

@johndevman
Last active July 6, 2018 13:40
Show Gist options
  • Save johndevman/8fd2df07b61928b4f4c825964ff9db57 to your computer and use it in GitHub Desktop.
Save johndevman/8fd2df07b61928b4f4c825964ff9db57 to your computer and use it in GitHub Desktop.
An example context aware block that combines two fields to be used in Layout Builder
<?php
namespace Drupal\example\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Component\Render\FormattableMarkup;
/**
* Provides the full name of the author of the given node from context.
*
* @Block(
* id = "full_name",
* admin_label = @Translation("Full name block"),
* context = {
* "node" = @ContextDefinition("entity:node", required = FALSE)
* }
* )
*/
class FullNameBlock extends BlockBase {
/**
* {@inheritdoc}
*/
public function build() {
/** @var \Drupal\node\NodeInterface $node */
$node = $this->getContextValue('node');
return [
'#markup' => new FormattableMarkup('@firstname @lastname', [
'@firstname' => $node->getOwner()->field_firstname->value,
'@lastname' => $node->getOwner()->field_lastname->value,
]),
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment