function DisplayApiTest::setUp

Same name in other branches
  1. 9 core/modules/field/tests/src/Kernel/DisplayApiTest.php \Drupal\Tests\field\Kernel\DisplayApiTest::setUp()
  2. 8.9.x core/modules/field/tests/src/Kernel/DisplayApiTest.php \Drupal\Tests\field\Kernel\DisplayApiTest::setUp()
  3. 11.x core/modules/field/tests/src/Kernel/DisplayApiTest.php \Drupal\Tests\field\Kernel\DisplayApiTest::setUp()

Overrides FieldKernelTestBase::setUp

File

core/modules/field/tests/src/Kernel/DisplayApiTest.php, line 70

Class

DisplayApiTest
Tests the field display API.

Namespace

Drupal\Tests\field\Kernel

Code

protected function setUp() : void {
    parent::setUp();
    // Create a field and its storage.
    $this->fieldName = 'test_field';
    $this->label = $this->randomMachineName();
    $this->cardinality = 4;
    $field_storage = [
        'field_name' => $this->fieldName,
        'entity_type' => 'entity_test',
        'type' => 'test_field',
        'cardinality' => $this->cardinality,
    ];
    $field = [
        'field_name' => $this->fieldName,
        'entity_type' => 'entity_test',
        'bundle' => 'entity_test',
        'label' => $this->label,
    ];
    $this->displayOptions = [
        'default' => [
            'type' => 'field_test_default',
            'settings' => [
                'test_formatter_setting' => $this->randomMachineName(),
            ],
        ],
        'teaser' => [
            'type' => 'field_test_default',
            'settings' => [
                'test_formatter_setting' => $this->randomMachineName(),
            ],
        ],
    ];
    
    /** @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface $display_repository */
    $display_repository = \Drupal::service('entity_display.repository');
    FieldStorageConfig::create($field_storage)->save();
    FieldConfig::create($field)->save();
    // Create a display for the default view mode.
    $display_repository->getViewDisplay($field['entity_type'], $field['bundle'])
        ->setComponent($this->fieldName, $this->displayOptions['default'])
        ->save();
    // Create a display for the teaser view mode.
    EntityViewMode::create([
        'id' => 'entity_test.teaser',
        'label' => 'Teaser',
        'targetEntityType' => 'entity_test',
    ])->save();
    $display_repository->getViewDisplay($field['entity_type'], $field['bundle'], 'teaser')
        ->setComponent($this->fieldName, $this->displayOptions['teaser'])
        ->save();
    // Create an entity with values.
    $this->values = $this->_generateTestFieldValues($this->cardinality);
    $this->entity = EntityTest::create();
    $this->entity->{$this->fieldName}
        ->setValue($this->values);
    $this->entity
        ->save();
}

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