diff --git a/core/modules/field/lib/Drupal/field/Tests/DisplayApiTest.php b/core/modules/field/lib/Drupal/field/Tests/DisplayApiTest.php index 6f7d159..0933641 100644 --- a/core/modules/field/lib/Drupal/field/Tests/DisplayApiTest.php +++ b/core/modules/field/lib/Drupal/field/Tests/DisplayApiTest.php @@ -210,4 +210,36 @@ function testFieldViewValue() { $this->assertText($setting . '|' . $value['value'], format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta))); } } + + /** + * Tests that the prepareView() formatter method still fires for empty values. + */ + function testFieldEmpty() { + // Uses \Drupal\field_test\Plugin\field\formatter\TestFieldEmptyFormatter. + $display = array( + 'label' => 'hidden', + 'type' => 'field_empty_test', + 'settings' => array( + 'test_empty_string' => '**EMPTY FIELD**' . $this->randomName(), + ), + ); + // $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. + $output = field_view_field($this->entity, $this->field_name, $display); + $view = drupal_render($output); + $this->content = $view; + // 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->field_name}[LANGUAGE_NOT_SPECIFIED] = array(); + field_test_entity_save($this->entity); + $output = field_view_field($this->entity, $this->field_name, $display); + $view = drupal_render($output); + $this->content = $view; + // This time, as the field values have been removed, we *should* show the + // default "empty" text. + $this->assertText($display['settings']['test_empty_string']); + } } diff --git a/core/modules/field/tests/modules/field_test/lib/Drupal/field_test/Plugin/field/formatter/TestFieldEmptyFormatter.php b/core/modules/field/tests/modules/field_test/lib/Drupal/field_test/Plugin/field/formatter/TestFieldEmptyFormatter.php new file mode 100644 index 0000000..9632420 --- /dev/null +++ b/core/modules/field/tests/modules/field_test/lib/Drupal/field_test/Plugin/field/formatter/TestFieldEmptyFormatter.php @@ -0,0 +1,60 @@ + $entity_items) { + if (empty($entity_items)) { + // For fields with no value, just add the configured "empty" value. + $items[$id][0]['value'] = $this->getSetting('test_empty_string'); + } + } + } + + /** + * {@inheritdoc} + */ + public function viewElements(EntityInterface $entity, $langcode, array $items) { + $elements = array(); + + if (!empty($items)) { + foreach ($items as $delta => $item) { + // This formatter only needs to output raw for testing. + $elements[$delta] = array('#markup' => $item['value']); + } + } + + return $elements; + } + +}