EDIT: The code below works - there was a problem with my local machine - read more at the end for why it did not work
I want to create multiple blocks that don't need custom setttings from the interface and get their content from a custom function based on their name.
So basically I a need a bunch of blocks with names in order to be able to be placed in regions from the UI.
I tried this tutorial but I realize that its from early 2014 and things might have changed so I ended up following the the 1st solution to this question which seems newer.
modules/mymodule/src/Plugin/Block/YourBlock.php
<?php
namespace Drupal\mymodule\Plugin\Block;
use Drupal\Core\Block\BlockBase;
/**
* Display all instances for 'YourBlock' block plugin.
*
* @Block(
* id = "mymodule_block",
* admin_label = @Translation("Your block"),
* category = @Translation("Your block"),
* deriver = "Drupal\mymodule\Plugin\Derivative\YourBlock"
* )
*/
class YourBlock extends BlockBase {
/**
* Build the content for mymodule block.
*/
public function build() {
$block_id = $this->getDerivativeId();
return array(
'#markup' => $block_id,
);
}
}
modules/mymodule/src/Plugin/Derivative/YourBlock.php
<?php
namespace Drupal\mymodule\Plugin\Derivative;
use Drupal\Component\Plugin\Derivative\DeriverBase;
class YourBlock extends DeriverBase {
public function getDerivativeDefinitions($base_plugin_definition) {
$myblocks = array(
'mymodule_block_1' => t('My Module: Block 1'),
'mymodule_block_2' => t('My Module: Block 2'),
);
foreach ($myblocks as $block_id => $block_label) {
$this->derivatives[$block_id] = $base_plugin_definition;
$this->derivatives[$block_id]['admin_label'] =
t('Title: @name content type: @ctype ', array('@name' => $block_label, '@ctype' => "My Module"));
}
return $this->derivatives;
}
}
above is the complete code I have tried
I have done drush cache-rebuild
but the 2 blocks don't appear when I press "place blocks" in admin/structure/block
What am I doing wrong ?
EDIT: Found a solution it turns out that enabling this module on a different system the blocks where discovered so there was nothing wrong with the code
The setup that had a problem was with php 5.5.9 and mysql 5.5 and the system that was working well had php7.1 and mysql 5.7 so this might be the case