function DisplayApiTest::testFieldEmpty

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

Tests that the prepareView() formatter method still fires for empty values.

File

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

Class

DisplayApiTest
Tests the field display API.

Namespace

Drupal\Tests\field\Kernel

Code

public function testFieldEmpty() : void {
    // Uses \Drupal\field_test\Plugin\Field\FieldFormatter\TestFieldEmptyFormatter.
    $display = [
        'label' => 'hidden',
        'type' => 'field_empty_test',
        'settings' => [
            'test_empty_string' => '**EMPTY FIELD**' . $this->randomMachineName(),
        ],
    ];
    // $this->entity is set by the setUp() method and by default contains 4
    // numeric values.  We only want to test the display of this one field.
    $build = $this->entity
        ->get($this->fieldName)
        ->view($display);
    $this->render($build);
    // The test field by default contains values, so should not display the
    // default "empty" text.
    $this->assertNoText($display['settings']['test_empty_string']);
    // Now remove the values from the test field and retest.
    $this->entity->{$this->fieldName} = [];
    $this->entity
        ->save();
    $build = $this->entity
        ->get($this->fieldName)
        ->view($display);
    $this->render($build);
    // This time, as the field values have been removed, we *should* show the
    // default "empty" text.
    $this->assertText($display['settings']['test_empty_string']);
}

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