diff --git a/core/lib/Drupal/Core/Entity/EntityDisplayBase.php b/core/lib/Drupal/Core/Entity/EntityDisplayBase.php index 1724addaedf..768835903f6 100644 --- a/core/lib/Drupal/Core/Entity/EntityDisplayBase.php +++ b/core/lib/Drupal/Core/Entity/EntityDisplayBase.php @@ -117,6 +117,13 @@ abstract class EntityDisplayBase extends ConfigEntityBase implements EntityDispl */ protected $renderer; + /** + * A boolean indicating whether or not this display has been initialized. + * + * @var bool + */ + protected $initialized = FALSE; + /** * {@inheritdoc} */ @@ -156,7 +163,8 @@ abstract class EntityDisplayBase extends ConfigEntityBase implements EntityDispl */ protected function init() { // Only populate defaults for "official" view modes and form modes. - if ($this->mode !== static::CUSTOM_MODE) { + if (!$this->initialized && $this->mode !== static::CUSTOM_MODE) { + $this->initialized = TRUE; $default_region = $this->getDefaultRegion(); // Fill in defaults for extra fields. $context = $this->displayContext == 'view' ? 'display' : $this->displayContext; @@ -546,6 +554,8 @@ abstract class EntityDisplayBase extends ConfigEntityBase implements EntityDispl // __wakeup(). Because of the way __sleep() works, the data has to be // present in the object to be included in the serialized values. $keys[] = '_serializedKeys'; + // Keep track of the initialization status. + $keys[] = 'initialized'; $this->_serializedKeys = $keys; return $keys; } diff --git a/core/modules/field_ui/tests/src/Kernel/EntityFormDisplayTest.php b/core/modules/field_ui/tests/src/Kernel/EntityFormDisplayTest.php index b5697b3c787..b984ac70f20 100644 --- a/core/modules/field_ui/tests/src/Kernel/EntityFormDisplayTest.php +++ b/core/modules/field_ui/tests/src/Kernel/EntityFormDisplayTest.php @@ -282,4 +282,23 @@ class EntityFormDisplayTest extends KernelTestBase { $this->assertNull($display->getComponent($field_name)); } + /** + * Tests the serialization and unserialization of the class. + */ + public function testSerialization() { + /** @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface $display_repository */ + $display_repository = \Drupal::service('entity_display.repository'); + + $form_display = $display_repository->getFormDisplay('entity_test', 'entity_test'); + // Make sure the langcode base field is visible in the original form + // display. + $this->assertNotEmpty($form_display->getComponent('langcode')); + // Remove the langcode. + $form_display->removeComponent('langcode'); + + $unserialized = unserialize(serialize($form_display)); + // Verify that components are retained upon unserialization. + $this->assertEquals($form_display->getComponents(), $unserialized->getComponents()); + } + }