首先,添加一个文件,位置如下:Drupal\mymodule\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)
{
$results = \Drupal::database()->select('mymodule_blocks_data', 'n')
->fields('n', array('delta','title', 'content_type'))
->condition('n.form_type', 'Add', '=')
->execute();
foreach ($results as $result) {
$this->derivatives[$result->delta] = $base_plugin_definition;
$this->derivatives[$result->delta]['admin_label'] = t('Title: @name content type: @ctype ', array('@name' => $result->title, '@ctype' => $result->content_type));
}
return $this->derivatives;
}
}
其次,再增加一个YourBlock.php在 Drupal\mymodule\Plugin\Block.
注意:这个与普通的block不一样,有一个deriver,这个表示对应响应的dervitive。
/**
* Display all instances for 'YourBlock' block plugin.
*
* @Block(
* id = "mymodule_block",
* admin_label = @Translation("Your block"),
* deriver = "Drupal\mymodule\Plugin\Derivative\YourBlock"
* )
*/
class YourBlock extends BlockBase implements ContainerFactoryPluginInterface {
public function build() {
$id = $this->getDerivativeId();
return array(
'#markup' => 'Data',
'#cache' => array(
'max-age' => 0,
),
);
}
}
注意:getDerivativeId()方法
详情参考:
https://www.sitepoint.com/tutorial-on-using-drupal-8-plugin-derivatives-effectively/