Drupal - How do I make a block that pulls the current node content?
There are two completely different kinds of contexts.
Cache contexts, which have nothing to do with this. They're not used to invalidate something, but vary by something (e.g. cache differently for different user permisisons). Cache tags are for invalidation.
What you mean are plugin contexts. And yes, blocks are able to use them since a short while (They always could, but the block.module didn't support it properly). As @larowlan said, core uses them mostly for visibility conditions but it works the same for blocks.
One such example that you can look at is the NodeType condition. What you need to do is add the context annotation and then you can use it as $this->getContextValue('node')
. The advantage of this is that your block is more flexible and doesn't need to know where the node is coming from exactly, that's up to the user configuring it.
Note that this is not visible in the UI currently unless there is actually more than one node to chose from.
For using node in block, i use context. For example: this block display links for edition and deleting current node:
/**
* @file
* Contains \Drupal\my_module\Plugin\Block\NodeMenuBlock.
*/
namespace Drupal\my_module\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Link;
use Drupal\Core\Url;
/**
* @Block(
* id = "node_menu_block",
* admin_label = @Translation("Node Menu Block"),
* category = @Translation("My Group"),
* context = {
* "node" = @ContextDefinition(
* "entity:node",
* label = @Translation("Current Node")
* )
* }
* )
*/
class NodeMenuBlock extends BlockBase {
/**
* {@inheritdoc}
*/
public function build() {
$node = $this->getContextValue('node');
$nid_fld = $node->nid->getValue();
$nid = $nid_fld[0]['value'];
$markup = '';
$links = ['entity.node.edit_form' => 'Edit', 'entity.node.delete_form' => 'Delete', ];
foreach($links as $rout=>$text) {
$url = Url::fromRoute($rout, array('node' => $nid));
$link = Link::fromTextAndUrl(t($text), $url)->toRenderable();
$link['#attributes'] = array('class' => array('button', 'button-action'));
$markup .= render($link).' ';
}
$block = [
'#type' => 'markup',
'#markup' => $markup,
];
return $block;
}
}