You are here

class SimpleNodeImporterMappingForm in Simple Node Importer 8

Flexible Mapping Form for the Simple Node Importer.

Hierarchy

Expanded class hierarchy of SimpleNodeImporterMappingForm

1 string reference to 'SimpleNodeImporterMappingForm'
simple_node_importer.routing.yml in ./simple_node_importer.routing.yml
simple_node_importer.routing.yml

File

src/Form/SimpleNodeImporterMappingForm.php, line 23

Namespace

Drupal\simple_node_importer\Form
View source
class SimpleNodeImporterMappingForm extends FormBase {
  protected $services;
  protected $sessionVariable;
  protected $sessionManager;
  protected $currentUser;
  protected $entityTypeManager;
  protected $fileUsage;
  protected $logger;

  /**
   * Confirmation form for the start node import.
   *
   * @param Drupal\simple_node_importer\Services\GetServices $getServices
   *   Constructs a Drupal\simple_node_importer\Services object.
   * @param Drupal\Core\TempStore\PrivateTempStoreFactory $sessionVariable
   *   Constructs a Drupal\Core\TempStore\PrivateTempStoreFactory object.
   * @param Drupal\Core\Session\SessionManagerInterface $session_manager
   *   Constructs a Drupal\Core\Session\SessionManagerInterface object.
   * @param Drupal\Core\Session\AccountInterface $current_user
   *   Constructs a Drupal\Core\Session\AccountInterface object.
   * @param Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   Constructs a Drupal\Core\Entity\EntityTypeManagerInterface object.
   * @param Drupal\file\FileUsage\FileUsageInterface $file_usage
   *   Constructs a Drupal\file\FileUsage\FileUsageInterface object.
   * @param Drupal\Core\Logger\LoggerChannelFactoryInterface $logger
   *   Constructs a Drupal\Core\Logger\LoggerChannelFactoryInterface object.
   */
  public function __construct(GetServices $getServices, PrivateTempStoreFactory $sessionVariable, SessionManagerInterface $session_manager, AccountInterface $current_user, EntityTypeManagerInterface $entity_type_manager, FileUsageInterface $file_usage, LoggerChannelFactoryInterface $logger) {
    $this->services = $getServices;
    $this->sessionVariable = $sessionVariable
      ->get('simple_node_importer');
    $this->sessionManager = $session_manager;
    $this->currentUser = $current_user;
    $this->entityTypeManager = $entity_type_manager;
    $this->fileUsage = $file_usage;
    $this->logger = $logger;
  }

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

  /**
   * Builds Flexible Mapping UI.
   */
  public function buildForm(array $form, FormStateInterface $form_state, $option = NULL, NodeInterface $node = NULL) {
    global $base_url;
    $type = 'module';
    $module = 'simple_node_importer';
    $filepath = $base_url . '/' . drupal_get_path($type, $module) . '/css/files/mapping.png';
    $fid = $node
      ->get('field_upload_csv')
      ->getValue()[0]['target_id'];
    $file = File::load($fid);
    $uri = $file
      ->getFileUri();
    if (empty($node)) {
      $type = 'Simple Node Importer';
      $message = 'Node object is not valid.';
      $this->logger
        ->get($type)
        ->error($message, []);
    }
    elseif ($this->sessionVariable
      ->get('file_upload_session') == FALSE) {
      $response = new RedirectResponse('/node/add/simple-node');
      $response
        ->send();
    }
    else {

      // Options to be listed in File Column List.
      $headers = $this->services
        ->simpleNodeImporterGetAllColumnHeaders($uri);
      $selected_content_type = $node
        ->get('field_select_content_type')
        ->getValue()[0]['value'];
      $entity_type = $node
        ->getEntityTypeId();
      $type = 'mapping';
      $get_field_list = $this->services
        ->snpGetFieldList($entity_type, $selected_content_type, $type);

      // Add HelpText to the mapping form.
      $form['helptext'] = [
        '#theme' => 'mapping_help_text_info',
        '#fields' => [
          'filepath' => $filepath,
        ],
      ];

      // Add theme table to the mapping form.
      $form['mapping_form']['#theme'] = 'simple_node_import_table';

      // Mapping form.
      foreach ($get_field_list as $key => $field) {

        // code...
        if (method_exists($field
          ->getLabel(), 'render')) {
          $form['mapping_form'][$key] = [
            '#type' => 'select',
            '#title' => $field
              ->getLabel()
              ->render(),
            '#options' => $headers,
            '#empty_option' => $this
              ->t('Select'),
            '#empty_value' => '',
          ];
        }
        else {
          $field_name = $field
            ->getName();
          $field_label = $field
            ->getLabel();
          $field_info = FieldStorageConfig::loadByName('node', $field_name);
          if (!empty($field_info) && ($field_info
            ->get('cardinality') == -1 || $field_info
            ->get('cardinality') > 1)) {
            $form['mapping_form'][$key] = [
              '#type' => 'select',
              '#title' => $field_label,
              '#options' => $headers,
              '#multiple' => TRUE,
              '#required' => $field
                ->isRequired() ? TRUE : FALSE,
              '#empty_option' => $this
                ->t('Select'),
              '#empty_value' => '',
            ];
          }
          else {
            $form['mapping_form'][$key] = [
              '#type' => 'select',
              '#title' => $field_label,
              '#options' => $headers,
              '#required' => $field
                ->isRequired() ? TRUE : FALSE,
              '#empty_option' => $this
                ->t('Select'),
              '#empty_value' => '',
            ];
          }
        }
      }

      // Get the preselected values for form fields.
      $form = $this->services
        ->simpleNodeImporterGetPreSelectedValues($form, $headers);
      $form['snp_nid'] = [
        '#type' => 'hidden',
        '#value' => $node
          ->id(),
      ];
      $form['import'] = [
        '#type' => 'submit',
        '#value' => $this
          ->t('Import'),
        '#weight' => 49,
      ];
      $parameters = [
        'option' => $option,
        'node' => $node
          ->id(),
      ];
      $this->sessionVariable
        ->set('parameters', $parameters);
      $form['cancel'] = [
        '#type' => 'submit',
        '#value' => $this
          ->t('cancel'),
        '#weight' => 3,
        '#submit' => [
          '::snpRedirectToCancel',
        ],
      ];
      return $form;
    }
  }

  /**
   * Validates form.
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $valarray = [];
    $duplicates = [];
    $count_array = [];
    $form_state
      ->cleanValues();
    foreach ($form_state
      ->getValues() as $key => $val) {
      if ($val && is_array($val)) {
        foreach ($val as $v) {
          $valarray[] = $v;
        }
      }
      elseif ($val) {
        $valarray[] = $val;
      }
    }
    $count_array = array_count_values($valarray);
    foreach ($count_array as $field => $count) {
      if ($count > 1) {
        $duplicates[] = $field;
      }
    }
    foreach ($duplicates as $duplicate_val) {
      foreach ($form_state
        ->getValues() as $key => $val) {
        if ($val == $duplicate_val) {
          $form_state
            ->setErrorByName($key, $this
            ->t('Duplicate Mapping detected for %duplval', [
            '%duplval' => $duplicate_val,
          ]));
        }
        elseif (is_array($val)) {
          foreach ($val as $v) {
            if ($v == $duplicate_val) {
              $form_state
                ->setErrorByName($key, $this
                ->t('Duplicate Mapping detected for %duplval', [
                '%duplval' => $duplicate_val,
              ]));
            }
          }
        }
      }
    }

    // Remove Duplicate Error Messages.
    if (isset($_SESSION['messages']['error'])) {
      $_SESSION['messages']['error'] = array_unique($_SESSION['messages']['error']);
    }
  }

  /**
   * Submit form.
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    // Remove unnecessary values.
    $form_state
      ->cleanValues();
    $haystack = 'snp_';
    foreach ($form_state
      ->getValues() as $key => $val) {
      if (strpos($key, $haystack) === FALSE) {
        $mapvalues[$key] = $val;
      }
    }
    $node_storage = $this->entityTypeManager
      ->getStorage('node');
    $snp_nid = $form_state
      ->getValue('snp_nid');
    $node = $node_storage
      ->load($snp_nid);
    $bundleType = $node
      ->get('field_select_content_type')
      ->getValue()[0]['value'];
    $this->sessionVariable
      ->set('mapvalues', $mapvalues);
    $parameters = [
      'type' => $bundleType,
      'node' => $snp_nid,
    ];
    $form_state
      ->setRedirect('simple_node_importer.confirm_importing', $parameters);
  }

  /**
   * {@inheritdoc}
   */
  public function snpRedirectToCancel(array &$form, FormStateInterface $form_state) {
    $parameters = $this->sessionVariable
      ->get('parameters');
    $form_state
      ->setRedirect('simple_node_importer.delete_node', $parameters);
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('snp.get_services'), $container
      ->get('user.private_tempstore'), $container
      ->get('session_manager'), $container
      ->get('current_user'), $container
      ->get('entity_type.manager'), $container
      ->get('file.usage'), $container
      ->get('logger.factory'));
  }

}

Members

Namesort descending Modifiers Type Description Overrides
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.
SimpleNodeImporterMappingForm::$currentUser protected property
SimpleNodeImporterMappingForm::$entityTypeManager protected property
SimpleNodeImporterMappingForm::$fileUsage protected property
SimpleNodeImporterMappingForm::$logger protected property
SimpleNodeImporterMappingForm::$services protected property
SimpleNodeImporterMappingForm::$sessionManager protected property
SimpleNodeImporterMappingForm::$sessionVariable protected property
SimpleNodeImporterMappingForm::buildForm public function Builds Flexible Mapping UI. Overrides FormInterface::buildForm
SimpleNodeImporterMappingForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
SimpleNodeImporterMappingForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
SimpleNodeImporterMappingForm::snpRedirectToCancel public function
SimpleNodeImporterMappingForm::submitForm public function Submit form. Overrides FormInterface::submitForm
SimpleNodeImporterMappingForm::validateForm public function Validates form. Overrides FormBase::validateForm
SimpleNodeImporterMappingForm::__construct public function Confirmation form for the start node import.
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.