0

In a Drupal 8 website I created a custom token that is working in basic page.

Then I created a custom block with a WYSIWYG field :

class Myblock extends BlockBase {

  public function __construct(array $configuration, $plugin_id, $plugin_definition) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
  }

  public function getMachineName() {
    return 'my_custom_blcok';
  }


  public function label() {
    return $this->t('Block label');
  }

  public function blockForm($form, FormStateInterface $form_state) {
    $form = parent::blockForm($form, $form_state);
    $config = $this->getConfiguration();

    $form['my_field'] = [
      '#type' => 'text_format',
      '#format' => 'content_manager',
      '#title' => $this->t('Field name'),
      '#default_value' => isset($config['my_field']['value']) ? $config['my_field']['value'] : '',
    ];

    return $form;
  }

  public function blockSubmit($form, FormStateInterface $form_state) {
    $this->setConfigurationValue('my_field', $form_state->getValue('my_field'));
  }


  public function build() {
    $config = $this->getConfiguration();
    $content = $config['my_field']['value'];

    return [
        '#theme' => 'simulator_block',
        '#content' => $content,
      ];
  }
}

If I type My content [module:my_token] in the WYSIWYG.

The following content is display :

<p>My content [module:my_token]</p>

How can I replace the token ?

1

Place the formatted text in a render element processed_text:

 $content = [
    '#type' => 'processed_text',
    '#text' => $config['my_field']['value'],
    '#format' => 'content_manager',
  ];

  return [
    '#theme' => 'simulator_block',
    '#content' => $content,
  ];

Configure the text format to include the token filter.

| improve this answer | |
  • It's not working. I think that 'processed_text' is a Drupal 7 type was removed in Drupal 8 ... – Promo Oct 24 '18 at 12:09
  • 1
    It's in Drupal 8, see api.drupal.org/api/drupal/…. I think when you use an input element for formatted text you should use one for output too. Otherwise this is not safe, because, besides the token filter, dependent on what content you allow in the text format, you might need to apply more filters before you can output the content. – 4k4 Oct 24 '18 at 12:50
  • I missed that what you did was in build() and not in blockForm() so indeed it's working and your solution is better. – Promo Oct 24 '18 at 13:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.