You are here

class CloneContentTypeForm in Content Type Clone 8

Class CloneContentTypeForm.

@package Drupal\content_type_clone\Form

Hierarchy

Expanded class hierarchy of CloneContentTypeForm

1 string reference to 'CloneContentTypeForm'
content_type_clone.routing.yml in ./content_type_clone.routing.yml
content_type_clone.routing.yml

File

src/Form/CloneContentTypeForm.php, line 18

Namespace

Drupal\content_type_clone\Form
View source
class CloneContentTypeForm extends FormBase {

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

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

    //Get the requested node type from url parameter.
    $nodeTypeName = \Drupal::request()->query
      ->get('node_type');

    //Load the node type.
    $entity = NodeType::load($nodeTypeName);

    //Source content type fieldset.
    $form['source'] = array(
      '#type' => 'details',
      '#title' => t('Content type source'),
      '#open' => FALSE,
    );

    //Source content type name.
    $form['source']['source_name'] = array(
      '#type' => 'textfield',
      '#title' => t('Label'),
      '#required' => TRUE,
      '#default_value' => $entity
        ->label(),
      '#attributes' => array(
        'readonly' => 'readonly',
      ),
    );

    //Source content type machine name.
    $form['source']['source_machine_name'] = array(
      '#type' => 'textfield',
      '#title' => t('Machine name'),
      '#required' => TRUE,
      '#default_value' => $entity
        ->id(),
      '#attributes' => array(
        'readonly' => 'readonly',
      ),
    );

    //Source content type description.
    $form['source']['source_description'] = array(
      '#type' => 'textarea',
      '#title' => t('Description'),
      '#required' => FALSE,
      '#default_value' => $entity
        ->getDescription(),
      '#attributes' => array(
        'readonly' => 'readonly',
      ),
    );

    //Target content type fieldset.
    $form['target'] = array(
      '#type' => 'details',
      '#title' => t('Content type target'),
      '#open' => TRUE,
    );

    //Target content type name.
    $form['target']['target_name'] = array(
      '#type' => 'textfield',
      '#title' => t('Label'),
      '#required' => TRUE,
    );

    //Target content type machine name.
    $form['target']['target_machine_name'] = array(
      '#type' => 'machine_name',
      '#title' => t('Machine name'),
      '#required' => TRUE,
      '#description' => $this
        ->t('A unique name for this item. It must only contain lowercase letters, numbers, and underscores.'),
    );

    //Target content type description
    $form['target']['target_description'] = array(
      '#type' => 'textarea',
      '#title' => t('Description'),
      '#required' => FALSE,
    );

    //Copy nodes checkbox.
    $form['copy_source_nodes'] = array(
      '#type' => 'checkbox',
      '#title' => t('Copy all nodes from the source content type to the target content type'),
      '#required' => FALSE,
    );

    //Delete nodes checkbox.
    $form['delete_source_nodes'] = array(
      '#type' => 'checkbox',
      '#title' => t('Delete all nodes from the source content type after they have been copied to the target content type'),
      '#required' => FALSE,
    );

    //Token pattern fieldset.
    $form['patterns'] = array(
      '#type' => 'details',
      '#title' => t('Replacement patterns'),
      '#open' => FALSE,
    );

    //Display token options.
    if (\Drupal::moduleHandler()
      ->moduleExists('token')) {

      // Display the node title pattern field.
      $placeholder = t('Clone of @title', array(
        '@title' => '[node:title]',
      ));
      $form['patterns']['title_pattern'] = array(
        '#type' => 'textfield',
        '#title' => t('Node title pattern'),
        '#attributes' => array(
          'placeholder' => $placeholder,
        ),
      );
      $form['patterns']['token_tree'] = array(
        '#title' => t('Tokens'),
        '#theme' => 'token_tree_link',
        '#token_types' => array(
          'node',
        ),
        '#show_restricted' => TRUE,
        '#global_types' => TRUE,
        '#required' => TRUE,
      );
    }
    else {
      $form['patterns']['token_tree'] = array(
        '#markup' => '<p>' . t('Enable the <a href="@drupal-token">Token module</a> to view the available token browser.', array(
          '@drupal-token' => 'http://drupal.org/project/token',
        )) . '</p>',
      );
    }

    //Clone submit button.
    $form['cct_clone'] = array(
      '#type' => 'submit',
      '#value' => $this
        ->t('Clone content type'),
    );

    //Return the result.
    return $form;
  }

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

    //Get the submitted form values.
    $values = $form_state
      ->getValues();

    //Retrieve the existing content type names.
    $contentTypesNames = $this
      ->getContentTypesList();

    //Check if the machine name already exists.
    if (in_array($values['target_machine_name'], $contentTypesNames)) {
      $form_state
        ->setErrorByName('target_machine_name', $this
        ->t('The machine name of the target content type already exists.'));
    }
  }

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

    //Create the batch process.
    $batch = array(
      'title' => t('Batch operations'),
      'operations' => $this
        ->buildOperationsList($form_state),
      'finished' => '\\Drupal\\content_type_clone\\Form\\CloneContentType::cloneContentTypeFinishedCallback',
      'init_message' => t('Performing batch operations...'),
      'error_message' => t('Something went wrong. Please check the errors log.'),
    );

    //Set the batch.
    batch_set($batch);
  }

  /**
   * Builds the operations array for the batch process.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Object describing the current state of the form.
   * @return array
   *   An array of operations to perform
   */
  protected function buildOperationsList(FormStateInterface $form_state) {

    //Get the form values.
    $values = $form_state
      ->getValues();

    //Prepare the operations array.
    $operations = array();

    //Clone content type operation.
    $operations[] = [
      '\\Drupal\\content_type_clone\\Form\\CloneContentType::cloneContentType',
      [
        $values,
      ],
    ];

    //Clone fields operations.
    $fields = \Drupal::service('entity_field.manager')
      ->getFieldDefinitions('node', $values['source_machine_name']);
    foreach ($fields as $field) {
      if (!empty($field
        ->getTargetBundle())) {
        $data = [
          'field' => $field,
          'values' => $values,
        ];
        $operations[] = [
          '\\Drupal\\content_type_clone\\Form\\CloneContentType::cloneContentTypeField',
          [
            $data,
          ],
        ];
      }
    }

    //Clone nodes operations.
    if ((int) $values['copy_source_nodes'] == 1) {
      $nids = \Drupal::entityQuery('node')
        ->condition('type', $values['source_machine_name'])
        ->execute();
      foreach ($nids as $nid) {
        if ((int) $nid > 0) {
          $operations[] = [
            '\\Drupal\\content_type_clone\\Form\\CloneContentType::copyContentTypeNode',
            [
              $nid,
              $values,
            ],
          ];
        }
      }
    }

    //Return the result.
    return $operations;
  }
  protected function getContentTypesList() {

    // Get the existing content types.
    $contentTypes = \Drupal::service('entity.manager')
      ->getStorage('node_type')
      ->loadMultiple();

    //Retrieve the existing content type names.
    $contentTypesNames = [];
    foreach ($contentTypes as $contentType) {
      $contentTypesNames[] = $contentType
        ->id();
    }

    //Return the result.
    return $contentTypesNames;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
CloneContentTypeForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
CloneContentTypeForm::buildOperationsList protected function Builds the operations array for the batch process.
CloneContentTypeForm::getContentTypesList protected function
CloneContentTypeForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
CloneContentTypeForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
CloneContentTypeForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
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::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 87
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.