Blog Archive

Tuesday, 19 January 2016

How to use token replace in Drupal 8?

public function viewElements(FieldItemListInterface $items, $langcode) {
    $entity = $items->getEntity();

    $elements = array();
    foreach ($items as $delta => $item) {
      $value = $item->getValue();

      // Replace the tokens with their respective values.
      $data = array();
      foreach(unserialize($value['value']) as $key => $key_value) {
        $data[$key] = \Drupal::token()->replace($key_value, [$entity->getEntityTypeId() => $entity]);
        $data[$key] = preg_replace ('/<[^>]*>/', '', $data[$key]);
      }

      $elements[$delta] = [
        '#theme' => 'raw_formatter',
        '#raw_value' => json_encode($data),
      ];
    }
    return $elements;
  }

No comments:

Post a Comment