Drupal 8 で、カスタムブロックを作成するには、my_custom_block.info.ymlとMyCustomBlock.phpの 2つのファイルを書くだけでよい。このブロックは、Translatable field(machine_name はtranslatable_field)という1つの設定フィールドを持つ。
my_custom_block/my_custom_block.info.yml
name: My Custom Block
type: module
description: A custom Block ecample for block settings translatations
core: 8.x
dependencies:
- block
ブロックだけなら.moduleファイルは必要ない。以下は、ブロックに対するプラグインのコードである。
my_custom_block/src/Plugin/Block/MyCustomBlock.php
<?php
/**
* @file
* Contains \Drupal\my_custom_block\Plugin\Block\MyCustomBlock.
*/
namespace Drupal\ my_custom_block\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
/**
* @Block (
* id = "my_custom_block",
* admin_label = @Translation("My Custom Block"),
* category = @Translation("Custom")
* )
*/
class MyCustomBlock extends BlockBase {
/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
return [
'translatable_field' => '',
'label_display' => FALSE,
];
}
/**
* {@inheritdoc}
*/
public function blockForm($form, FormStateInterface $form_state) {
$form['translatable_field'] = [
'#type' => 'textfield',
'#title' => t('Translatable field'),
'#default_value' => $this->t($this->configuration['translatable_field']),
];
return $form;
}
/**
* {@inheritdoc}
*/
public function blockSubmit($form, FormStateInterface $form_state) {
$this->configuration['translatable_field'] = $form_state->getValue('translatable_field');
}
/**
* {@inheritdoc}
*/
public function build() {
return ['#type' => 'markup',
'#markup' => $this->t('@translatable_field', [
'@translatable_field' => $this->configuration['translatable_field'],
]),
];
}
}
さて、このフィールドは任意の文字列を入力・保存可能であるが、その文字列を翻訳可能にするにはどうすればよいのだろうか?答えは、translatable_fieldを翻訳可能フィールドであるとマッピング(マーク)するもう1つスキーマファイルを用意するだけでよかった。
my_custom_block/config/schema/my_custom_block.yml
block.settings.my_custom_block:
type: block_settings
label: 'My custom block'
mapping:
translatable_field:
type: label
label: 'Translatable field'
このスキーマファイルがないと、このカスタムブロックの翻訳インターフェイスには、ブロックのタイトルしか翻訳可能なフィールドとして表示されないが、このファイルを 1つ追加するだけで翻訳インターフェイスにTranslatable fieldが翻訳可能なフィールドとして追加される。
また、注意事項として、Configuration Translationモジュールはオンにしておくこと。
参考リンク