You are here

class CloneEntityType in Entity Type Clone 8

Class CloneEntityType.

@package Drupal\entity_type_clone\Form

Hierarchy

Expanded class hierarchy of CloneEntityType

1 string reference to 'CloneEntityType'
entity_type_clone.routing.yml in ./entity_type_clone.routing.yml
entity_type_clone.routing.yml

File

src/Form/CloneEntityType.php, line 16

Namespace

Drupal\entity_type_clone\Form
View source
class CloneEntityType extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'entity_type_clone_form';
  }

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;
  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
  }
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity_type.manager'));
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $params = \Drupal::request()->query;
    $disbaled = FALSE;
    if ($params) {
      $entity_type = $params
        ->get('entity');
      $bundle_type = $params
        ->get('bundle');
      if ($entity_type && $bundle_type) {
        $disbaled = TRUE;
      }
    }
    $form['displays'] = [];
    $input =& $form_state
      ->getUserInput();
    $wrapper = 'entity-wrapper';

    // Create the part of the form that allows the user to select the basic
    // properties of what the entity to delete.
    $form['displays']['show'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Entity Clone Settings'),
      '#tree' => TRUE,
      '#attributes' => [
        'class' => [
          'container-inline',
        ],
      ],
    ];
    $content_entity_types = [];
    $entity_type_definations = $this->entityTypeManager
      ->getDefinitions();

    /* @var $definition \Drupal\Core\Entity\EntityTypeInterface */
    $clone_types = [
      'node',
      'paragraph',
      'taxonomy_term',
      'profile',
    ];
    foreach ($entity_type_definations as $definition) {
      if ($definition instanceof ContentEntityType) {
        if (in_array($definition
          ->id(), $clone_types)) {
          $content_entity_types[$definition
            ->id()] = $definition
            ->getLabel();
        }
      }
    }
    $form['displays']['show']['entity_type'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Select Entity Type'),
      '#options' => $content_entity_types,
      '#empty_option' => $this
        ->t('- Select Entity Type -'),
      '#size' => 1,
      '#required' => TRUE,
      '#disabled' => $disbaled,
      '#default_value' => isset($entity_type) ? $entity_type : '',
      '#suffix' => '<div id="' . $wrapper . '"></div>',
      '#ajax' => [
        'callback' => [
          $this,
          'ajaxCallChangeEntity',
        ],
        'wrapper' => $wrapper,
      ],
    ];
    if (isset($input['show']['entity_type']) || isset($entity_type)) {
      $entity_type_selected = isset($input['show']['entity_type']) ? $input['show']['entity_type'] : $entity_type;
      $default_bundles = \Drupal::service('entity_type.bundle.info')
        ->getBundleInfo($entity_type_selected);

      // If the current base table support bundles and has more than one (like user).
      if (!empty($default_bundles)) {

        // Get all bundles and their human readable names.
        foreach ($default_bundles as $type => $bundle) {
          $type_options[$type] = $bundle['label'];
        }
        $form['displays']['show']['type']['#options'] = $type_options;
      }
    }
    if (isset($type_options)) {
      $form['displays']['show']['type'] = [
        '#type' => 'select',
        '#title' => $this
          ->t('of type'),
        '#options' => $type_options,
        '#disabled' => $disbaled,
        '#default_value' => $bundle_type,
        '#prefix' => '<div id="' . $wrapper . '">',
        '#suffix' => '</div>',
      ];
    }

    // Target content type fieldset.
    $form['target'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Target Entity details'),
      '#open' => TRUE,
    ];
    $form['target']['clone_bundle'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Target bundle name'),
      '#required' => TRUE,
    ];
    $form['target']['clone_bundle_machine'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Target bundle machine name'),
      '#required' => TRUE,
    ];
    $form['target']['target_description'] = [
      '#type' => 'textarea',
      '#title' => $this
        ->t('Description'),
      '#required' => FALSE,
    ];
    $form['message'] = [
      '#markup' => $this
        ->t('Note: Use <b>ENTITY TYPE CLONE</b> only to clone Content Type, Paragraph, Taxonomy.<br>'),
    ];
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Clone'),
    ];
    $form['reset'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Reset'),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function ajaxCallChangeEntity(array &$form, FormStateInterface $form_state) {
    return $form['displays']['show']['type'];
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {

    // Get the form state values.
    $values = $form_state
      ->getValues();
    $entity_type = $values['show']['entity_type'];

    // Get the existing entity type machine names.
    $entityTypesNames = $this
      ->getMachineNamesof($entity_type);
    if ($entityTypesNames && in_array($values['clone_bundle_machine'], $entityTypesNames)) {
      $form_state
        ->setErrorByName('clone_bundle_machine', $this
        ->t('The machine name of the target entity type already exists.'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    // Get the form state values.
    $values = $form_state
      ->getValues();
    $op = (string) $values['op'];
    if ($op == $this
      ->t('Reset')) {
      $form_state
        ->setRedirect('entity_type_clone.type');
    }
    elseif ($op == $this
      ->t('Clone')) {

      // Create the batch process for clone operations.
      $batch = [
        'title' => $this
          ->t('Cloning in process.'),
        'operations' => $this
          ->cloneEntityType($form_state),
        'init_message' => $this
          ->t('Performing clone operations...'),
        'finished' => '\\Drupal\\entity_type_clone\\Form\\CloneEntityTypeData::cloneEntityTypeFinishedCallback',
        'error_message' => $this
          ->t('Something went wrong. Please check the errors log.'),
      ];
      batch_set($batch);
    }
  }

  /**
   * Implements to perform batch operations.
   *
   * @param FormStateInterface $form_state
   *
   * @return array
   */
  public function cloneEntityType(FormStateInterface $form_state) {

    // Get the form state values.
    $values = $form_state
      ->getValues();
    $entity_type = $values['show']['entity_type'];
    $operations = [];

    // Clone entity type operation.
    $operations[] = [
      '\\Drupal\\entity_type_clone\\Form\\CloneEntityTypeData::cloneEntityTypeData',
      [
        $values,
      ],
    ];

    // Clone fields operations.
    $fields = \Drupal::service('entity_field.manager')
      ->getFieldDefinitions($entity_type, $values['show']['type']);
    foreach ($fields as $field) {
      if (!empty($field
        ->getTargetBundle()) && !($entity_type === 'taxonomy_term' && $field
        ->getName() === 'parent')) {
        $data = [
          'field' => $field,
          'values' => $values,
        ];
        $operations[] = [
          '\\Drupal\\entity_type_clone\\Form\\CloneEntityTypeData::cloneEntityTypeField',
          [
            $data,
          ],
        ];
      }
    }
    return $operations;
  }

  /**
   * Implement to get Machine Names of entity type.
   *
   * @param string $entity_type
   *
   * @return array
   */
  protected function getMachineNamesof($entity_type) {

    // Get the existing content type machine names.
    $entityTypesNames = [];
    if ($entity_type === 'node') {
      $contentTypes = \Drupal::service('entity_type.manager')
        ->getStorage('node_type')
        ->loadMultiple();
      $entityTypesNames = [];
      foreach ($contentTypes as $contentType) {
        $entityTypesNames[] = $contentType
          ->id();
      }
    }
    elseif ($entity_type === 'taxonomy_term') {
      $taxonomyTypes = taxonomy_vocabulary_get_names();
      foreach ($taxonomyTypes as $taxonomyType) {
        $entityTypesNames[] = $taxonomyType;
      }
    }

    // Return the result of entity type with machine names.
    return $entityTypesNames;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
CloneEntityType::$entityTypeManager protected property The entity type manager.
CloneEntityType::ajaxCallChangeEntity public function
CloneEntityType::buildForm public function Form constructor. Overrides FormInterface::buildForm
CloneEntityType::cloneEntityType public function Implements to perform batch operations.
CloneEntityType::create public static function Instantiates a new instance of this class. Overrides FormBase::create
CloneEntityType::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
CloneEntityType::getMachineNamesof protected function Implement to get Machine Names of entity type.
CloneEntityType::submitForm public function Form submission handler. Overrides FormInterface::submitForm
CloneEntityType::validateForm public function Form validation handler. Overrides FormBase::validateForm
CloneEntityType::__construct public function
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.