Last active
July 6, 2018 13:40
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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