function EntityViewControllerTest::testFieldItemAttributes

Same name in other branches
  1. 9 core/modules/system/tests/src/Functional/Entity/EntityViewControllerTest.php \Drupal\Tests\system\Functional\Entity\EntityViewControllerTest::testFieldItemAttributes()
  2. 10 core/modules/system/tests/src/Functional/Entity/EntityViewControllerTest.php \Drupal\Tests\system\Functional\Entity\EntityViewControllerTest::testFieldItemAttributes()
  3. 11.x core/modules/system/tests/src/Functional/Entity/EntityViewControllerTest.php \Drupal\Tests\system\Functional\Entity\EntityViewControllerTest::testFieldItemAttributes()

Tests field item attributes.

File

core/modules/system/tests/src/Functional/Entity/EntityViewControllerTest.php, line 91

Class

EntityViewControllerTest
Tests EntityViewController functionality.

Namespace

Drupal\Tests\system\Functional\Entity

Code

public function testFieldItemAttributes() {
    // Make sure the test field will be rendered.
    \Drupal::service('entity_display.repository')->getViewDisplay('entity_test', 'entity_test')
        ->setComponent('field_test_text', [
        'type' => 'text_default',
    ])
        ->save();
    // Create an entity and save test value in field_test_text.
    $test_value = $this->randomMachineName();
    $entity = EntityTest::create();
    $entity->field_test_text = $test_value;
    $entity->save();
    // Browse to the entity and verify that the attribute is rendered in the
    // field item HTML markup.
    $this->drupalGet('entity_test/' . $entity->id());
    $xpath = $this->xpath('//div[@data-field-item-attr="foobar"]/p[text()=:value]', [
        ':value' => $test_value,
    ]);
    $this->assertNotEmpty($xpath, 'The field item attribute has been found in the rendered output of the field.');
    // Enable the RDF module to ensure that two modules can add attributes to
    // the same field item.
    \Drupal::service('module_installer')->install([
        'rdf',
    ]);
    $this->resetAll();
    // Set an RDF mapping for the field_test_text field. This RDF mapping will
    // be turned into RDFa attributes in the field item output.
    $mapping = rdf_get_mapping('entity_test', 'entity_test');
    $mapping->setFieldMapping('field_test_text', [
        'properties' => [
            'schema:text',
        ],
    ])
        ->save();
    // Browse to the entity and verify that the attributes from both modules
    // are rendered in the field item HTML markup.
    $this->drupalGet('entity_test/' . $entity->id());
    $xpath = $this->xpath('//div[@data-field-item-attr="foobar" and @property="schema:text"]/p[text()=:value]', [
        ':value' => $test_value,
    ]);
    $this->assertNotEmpty($xpath, 'The field item attributes from both modules have been found in the rendered output of the field.');
}

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