For this blog post we want to create a custom block plugin with additional configuration settings.

For this post, our main focus will be on making the custom plugin configuration translatable.
There is loads of information on creating custom block plugins, so we will not go in to deep on that.

Aanmaken van een blok plugin

Maak een MyCustomBlock.php bestand aan bij mymodule/src/Plugin/Block

<?php

namespace Drupal\mymodule\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Provides a custom block.
 *
 * @Block(
 *   id = "my_custom_block",
 *   admin_label = @Translation("My custom block")
 * )
 */
class MyCustomBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return array(
      'my_favorite_drink' => $this->t('My favorite drink'),
      );
  }

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {
    $form['my_favorite_drink'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('My favorite drink'),
      '#description' => $this->t('What would you like to drink?'),
      '#default_value' => $this->configuration['my_favorite_drink'],
    );

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    $this->configuration['my_favorite_drink'] = $form_state->getValue('my_favorite_drink');
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    $block = array();

    if ($this->configuration['my_favorite_drink']) {
      $block['label'] = array(
        '#type' => 'markup',
        '#markup' => $this->configuration['my_favorite_drink'],
      );
    }

    return $block;
  }
}

 

Configure block

Add the block to a region

You can now add your block to a region

No translation

Try to translate the configuration

You can now try to translate the block, but you will see that only the title is available for translation.

Missing schema

Schema configuration

Drupals fantastic multilingual system uses your config's schema information for making it translatable.
http://hojtsy.hu/blog/2014-may-19/drupal-8-multilingual-tidbits-15-confi...
http://hojtsy.hu/blog/2014-may-26/drupal-8-multilingual-tidbits-16-confi...

If we use the config_inspector module to inspect our custom block's schema, we see that the schema declaration for our custom properties are missing.

Schema found

We need to declare it at mymodule/config/schema in a mymodule.schema.yml file

block.settings.my_custom_block: type: block_settings label: 'My custom block' mapping: my_favorite_drink: type: label label: 'My favorite drink'

This will declare our configuration schema.
The datatype 'label' is an extension of 'string' and allows the multilingual system to translate our property.

Drupal 8 translate custom block plugin configuration

Translate our configuration

We can now translate the configuration at the block's translation page