You are here

protected function EntityField::addSelfTokens in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/views/src/Plugin/views/field/EntityField.php \Drupal\views\Plugin\views\field\EntityField::addSelfTokens()

Add any special tokens this field might use for itself.

This method is intended to be overridden by items that generate fields as a list. For example, the field that displays all terms on a node might have tokens for the tid and the term.

By convention, tokens should follow the format of {{ token__subtoken }} where token is the field ID and subtoken is the field. If the field ID is terms, then the tokens might be {{ terms__tid }} and {{ terms__name }}.

Overrides FieldPluginBase::addSelfTokens

File

core/modules/views/src/Plugin/views/field/EntityField.php, line 957

Class

EntityField
A field that displays entity field data.

Namespace

Drupal\views\Plugin\views\field

Code

protected function addSelfTokens(&$tokens, $item) {
  $field = $this
    ->getFieldDefinition();
  foreach ($field
    ->getColumns() as $id => $column) {

    // Use \Drupal\Component\Utility\Xss::filterAdmin() because it's user data
    // and we can't be sure it is safe. We know nothing about the data,
    // though, so we can't really do much else.
    if (isset($item['raw'])) {
      $raw = $item['raw'];
      if (is_array($raw)) {
        if (isset($raw[$id]) && is_scalar($raw[$id])) {
          $tokens['{{ ' . $this->options['id'] . '__' . $id . ' }}'] = Xss::filterAdmin($raw[$id]);
        }
        else {

          // Make sure that empty values are replaced as well.
          $tokens['{{ ' . $this->options['id'] . '__' . $id . ' }}'] = '';
        }
      }
      if (is_object($raw)) {
        $property = $raw
          ->get($id);

        // Check if TypedDataInterface is implemented so we know how to render
        // the item as a string.
        if (!empty($property) && $property instanceof TypedDataInterface) {
          $tokens['{{ ' . $this->options['id'] . '__' . $id . ' }}'] = Xss::filterAdmin($property
            ->getString());
        }
        else {

          // Make sure that empty values are replaced as well.
          $tokens['{{ ' . $this->options['id'] . '__' . $id . ' }}'] = '';
        }
      }
    }
  }
}