You are here

public function FieldTest::testTokenViewMode in Token 8

Test tokens on node with the token view mode overriding default formatters.

File

tests/src/Kernel/FieldTest.php, line 371

Class

FieldTest
Tests field tokens.

Namespace

Drupal\Tests\token\Kernel

Code

public function testTokenViewMode() {
  $value = 'A really long string that should be trimmed by the special formatter on token view we are going to have.';

  // The formatter we are going to use will eventually call Unicode::strlen.
  // This expects that the Unicode has already been explicitly checked, which
  // happens in DrupalKernel. But since that doesn't run in kernel tests, we
  // explicitly call this here.
  Unicode::check();

  // Create a node with a value in the text field and test its token.
  $entity = Node::create([
    'title' => 'Test node title',
    'type' => 'article',
    'test_field' => [
      'value' => $value,
      'format' => $this->testFormat
        ->id(),
    ],
  ]);
  $entity
    ->save();
  $this
    ->assertTokens('node', [
    'node' => $entity,
  ], [
    'test_field' => Markup::create($value),
  ]);

  // Now, create a token view mode which sets a different format for
  // test_field. When replacing tokens, this formatter should be picked over
  // the default formatter for the field type.
  // @see field_tokens().
  $view_mode = EntityViewMode::create([
    'id' => 'node.token',
    'targetEntityType' => 'node',
  ]);
  $view_mode
    ->save();
  $entity_display = \Drupal::service('entity_display.repository')
    ->getViewDisplay('node', 'article', 'token');
  $entity_display
    ->setComponent('test_field', [
    'type' => 'text_trimmed',
    'settings' => [
      'trim_length' => 50,
    ],
  ]);
  $entity_display
    ->save();
  $this
    ->assertTokens('node', [
    'node' => $entity,
  ], [
    'test_field' => Markup::create(substr($value, 0, 50)),
  ]);
}