This is the original description of the task (now removed from the question):
Build the following:
- A Drupal content type to hold all their products
- A Drupal block that can be placed on any product page. The block, when placed on any product page, automatically shows the currently
displayed product's App Purchase Link as a QR code, that the site
visitors can scan using their mobile.
You can use the current route to get the node and add a unique block for each node:
/src/Plugin/Block/ExampleBlock.php:
<?php
namespace Drupal\mymodule\Plugin\Block;
use Drupal\Core\Block\BlockBase;
/**
* Provides an example block.
*
* @Block(
* id = "mymodule_example",
* admin_label = @Translation("Example"),
* category = @Translation("mymodule")
* )
*/
class ExampleBlock extends BlockBase {
public function build() {
$build = [];
$node = \Drupal::routeMatch()->getParameter('node');
if ($node instanceof \Drupal\node\NodeInterface) {
// calculate $qr_image with $node
$build = [
'#markup' => $qr_image,
'#cache' => ['tags' => $node->getCacheTags()],
];
}
$build['#cache']['contexts'] = ['route'];
return $build;
}
}
2. Version
Implementing the same block with a node context, as @leymann suggested:
/src/Plugin/Block/ExampleBlock.php:
<?php
namespace Drupal\mymodule\Plugin\Block;
use Drupal\Core\Block\BlockBase;
/**
* Provides an example block.
*
* @Block(
* id = "mymodule_example",
* admin_label = @Translation("Example"),
* category = @Translation("mymodule"),
* context_definitions = {
* "node" = @ContextDefinition("entity:node")
* }
* )
*/
class ExampleBlock extends BlockBase {
public function build() {
$node = $this->getContextValue('node');
// calculate $qr_image with $node
return [
'#markup' => $qr_image,
];
}
}
The advantage, you don't need to take care about caching, the context does this automatically. The disadvantage, you need to make the block dependent on a context when placing it in the block layout. Drupal is not yet able to map a block context automatically. You could, for example, add a visibility for the content type, which is probably a good idea anyway.