EntityTypeCloneController.php in Entity Type Clone 8
File
src/Controller/EntityTypeCloneController.php
View source
<?php
namespace Drupal\entity_type_clone\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\JsonResponse;
class EntityTypeCloneController extends ControllerBase {
public static function arrayReplace($find, $replace, $arr) {
$newArray = [];
foreach ($arr as $key => $value) {
if (is_array($value)) {
$newArray[$key] = self::arrayReplace($find, $replace, $value);
}
else {
$newArray[$key] = str_replace($find, $replace, $value);
}
}
return $newArray;
}
public static function copyFieldDisplay($display, $mode, $data) {
$storage = 'entity_' . $display . '_display';
$sourceFieldName = $data['field']
->getName();
$sourceDisplay = \Drupal::entityTypeManager()
->getStorage($storage)
->load($data['values']['show']['entity_type'] . '.' . $data['values']['show']['type'] . '.' . $mode)
->toArray();
$targetDisplay = EntityTypeCloneController::arrayReplace($data['values']['show']['type'], $data['values']['clone_bundle_machine'], $sourceDisplay);
unset($targetDisplay['uuid'], $targetDisplay['_core']);
if ($display === 'form') {
$displayConfig = \Drupal::configFactory()
->getEditable('core.' . $storage . '.' . $data['values']['show']['entity_type'] . '.' . $data['values']['clone_bundle_machine'] . '.' . $mode)
->setData($targetDisplay)
->save();
}
elseif ($display === 'view') {
$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]);
}
if (isset($targetDisplay['hidden'][$sourceFieldName]) && (int) $targetDisplay['hidden'][$sourceFieldName] === 1) {
$entityDisplay
->removeComponent($sourceFieldName);
}
$entityDisplay
->save();
}
return new JsonResponse(t('Success'));
}
}