+
+ $already_enabled = isset($this->original) ? $this->original->isLayoutBuilderEnabled() : FALSE;
+ $set_enabled = $this->isLayoutBuilderEnabled();
+ if ($already_enabled !== $set_enabled) {
+ if ($set_enabled) {
+ // Loop through all existing field-based components and add them as
+ // section-based components.
+ $components = $this->getComponents();
+ // Sort the components by weight.
+ uasort($components, 'Drupal\Component\Utility\SortArray::sortByWeightElement');
+ foreach ($components as $name => $component) {
+ $this->setComponent($name, $component);
+ }
+ }
+ else {
+ // When being disabled, remove all existing section data.
+ while (count($this) > 0) {
+ $this->removeSection(0);
+ }
+ }
+ }
+ }
+
+ /**
+ * Removes a layout section field if it is no longer needed.
+ *
+ * Because the field is shared across all view modes, the field will only be
+ * removed if no other view modes are using it.
+ *
+ * @param string $entity_type_id
+ * The entity type ID.
+ * @param string $bundle
+ * The bundle.
+ * @param string $field_name
+ * The name for the layout section field.
+ */
+ protected function removeSectionField($entity_type_id, $bundle, $field_name) {
+ $query = $this->entityTypeManager()->getStorage($this->getEntityTypeId())->getQuery()
+ ->condition('targetEntityType', $this->getTargetEntityTypeId())
+ ->condition('bundle', $this->getTargetBundle())
+ ->condition('mode', $this->getMode(), '<>')
+ ->condition('third_party_settings.layout_builder.allow_custom', TRUE);
+ $enabled = (bool) $query->count()->execute();
+ if (!$enabled && $field = FieldConfig::loadByName($entity_type_id, $bundle, $field_name)) {
+ $field->delete();
+ }