Drupal 8: How to Translate Your Custom Block Fields

Submitted by admin on Tue, 01/30/2018 - 15:11

If you want to create a module that provides your custom block(s) in Drupal 8, for instance, you can only write two source codes such as my_custom_block.info.yml and MyCustomBlock.php. This custom block has the only one text field called Translatable field(machine_name is translatable_field).
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

If you want to provide the only custom block, .module is not necessary to write. The following is the source code for a Plugin for Block.
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'],
]),
];
}
}

Then, how can you translate the configurable translatable_textfield? The answer is that you need to prepare the one more additional file as the schema file as follows:
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'

You can only see the text filed for the title to translate without that schema file. However the schema file enables/maps the configuration setting fields (translatable_field above)) as translatable fields.
Note that you need to enable a Configuration Translation module.
See also:

Translating custom block plugin configuration

Configuration schema/metadata

Tags