public function FieldTest::testEntityReferenceTokensCardinality in Token 8
Tests support for cardinality > 1 for entity reference tokens.
File
- tests/
src/ Kernel/ FieldTest.php, line 548
Class
- FieldTest
- Tests field tokens.
Namespace
Drupal\Tests\token\KernelCode
public function testEntityReferenceTokensCardinality() {
/** @var \Drupal\field\FieldStorageConfigInterface $storage */
$storage = FieldStorageConfig::load('node.test_term_reference');
$storage
->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);
$storage
->save();
// Add a few terms.
$terms = [];
$terms_value = [];
foreach (range(1, 3) as $i) {
$terms_value[$i] = $this
->randomString();
$terms[$i] = $this
->createTerm($this->vocabulary, [
'name' => $this
->randomString(),
'term_field' => [
'value' => $terms_value[$i],
'format' => $this->testFormat
->id(),
],
]);
}
$entity = Node::create([
'title' => 'Test multivalue chained tokens',
'type' => 'article',
'test_term_reference' => [
[
'target_id' => $terms[1]
->id(),
],
[
'target_id' => $terms[2]
->id(),
],
[
'target_id' => $terms[3]
->id(),
],
],
]);
$entity
->save();
$this
->assertTokens('node', [
'node' => $entity,
], [
'test_term_reference:0:entity:term_field' => Html::escape($terms[1]->term_field->value),
'test_term_reference:1:entity:term_field' => Html::escape($terms[2]->term_field->value),
'test_term_reference:2:entity:term_field' => Html::escape($terms[3]->term_field->value),
'test_term_reference:0:target_id' => $terms[1]
->id(),
'test_term_reference:1:target_id' => $terms[2]
->id(),
'test_term_reference:2:target_id' => $terms[3]
->id(),
// Expects the entity's label to be returned for :entity tokens.
'test_term_reference:0:entity' => $terms[1]
->label(),
'test_term_reference:1:entity' => $terms[2]
->label(),
'test_term_reference:2:entity' => $terms[3]
->label(),
// To make sure tokens without an explicit delta can also be replaced in
// the same token replacement call.
'test_term_reference:entity:term_field' => Html::escape($terms[1]->term_field->value),
'test_term_reference:target_id' => $terms[1]
->id(),
]);
// Test some non existent tokens.
$this
->assertNoTokens('node', [
'node' => $entity,
], [
'test_term_reference:3:term_field',
'test_term_reference:0:does_not_exist',
'test_term_reference:1:does:not:exist',
'test_term_reference:1:2:does_not_exist',
]);
}