function EntityField::addSelfTokens

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()
  2. 8.9.x core/modules/views/src/Plugin/views/field/EntityField.php \Drupal\views\Plugin\views\field\EntityField::addSelfTokens()
  3. 11.x 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 984

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 . ' }}'] = $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 . ' }}'] = $property->getString();
        }
        else {
          // Make sure that empty values are replaced as well.
          $tokens['{{ ' . $this->options['id'] . '__' . $id . ' }}'] = '';
        }
      }
    }
  }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.