You are here

public static function EntityTypeCloneController::copyFieldDisplay in Entity Type Clone 8

1 call to EntityTypeCloneController::copyFieldDisplay()
CloneEntityTypeData::cloneEntityTypeField in src/Form/CloneEntityTypeData.php
Clones a entity type field.

File

src/Controller/EntityTypeCloneController.php, line 40

Class

EntityTypeCloneController
Class EntityTypeCloneController.

Namespace

Drupal\entity_type_clone\Controller

Code

public static function copyFieldDisplay($display, $mode, $data) {

  // Prepare the storage string
  $storage = 'entity_' . $display . '_display';

  // Get the source field name.
  $sourceFieldName = $data['field']
    ->getName();

  // Get the source form display.
  $sourceDisplay = \Drupal::entityTypeManager()
    ->getStorage($storage)
    ->load($data['values']['show']['entity_type'] . '.' . $data['values']['show']['type'] . '.' . $mode)
    ->toArray();

  // Prepare the target form display.
  $targetDisplay = EntityTypeCloneController::arrayReplace($data['values']['show']['type'], $data['values']['clone_bundle_machine'], $sourceDisplay);
  unset($targetDisplay['uuid'], $targetDisplay['_core']);

  // Save the target display.
  if ($display === 'form') {

    // Save the form display.
    $displayConfig = \Drupal::configFactory()
      ->getEditable('core.' . $storage . '.' . $data['values']['show']['entity_type'] . '.' . $data['values']['clone_bundle_machine'] . '.' . $mode)
      ->setData($targetDisplay)
      ->save();
  }
  elseif ($display === 'view') {

    // Save the view display.
    $entityDisplay = \Drupal::service('entity_display.repository')
      ->getViewDisplay($data['values']['show']['entity_type'], $data['values']['clone_bundle_machine'], $mode);
    if (isset($targetDisplay['content'][$sourceFieldName])) {
      $entityDisplay
        ->setComponent($sourceFieldName, $targetDisplay['content'][$sourceFieldName]);
    }

    // Hide the field if needed.
    if (isset($targetDisplay['hidden'][$sourceFieldName]) && (int) $targetDisplay['hidden'][$sourceFieldName] === 1) {
      $entityDisplay
        ->removeComponent($sourceFieldName);
    }

    // Save the display.
    $entityDisplay
      ->save();
  }
  return new JsonResponse(t('Success'));
}