You are here

class MappingEditForm in GatherContent 8.5

Same name and namespace in other branches
  1. 8.4 gathercontent_ui/src/Form/MappingEditForm.php \Drupal\gathercontent_ui\Form\MappingEditForm

Class MappingEditForm.

@package Drupal\gathercontent\Form

Hierarchy

Expanded class hierarchy of MappingEditForm

File

gathercontent_ui/src/Form/MappingEditForm.php, line 20

Namespace

Drupal\gathercontent_ui\Form
View source
class MappingEditForm extends MappingEditFormBase {
  use StringTranslationTrait;

  /**
   * GatherContent client.
   *
   * @var \Drupal\gathercontent\DrupalGatherContentClient
   */
  protected $client;

  /**
   * Step object.
   *
   * @var \Drupal\gathercontent_ui\Form\MappingEditSteps\MappingSteps
   */
  protected $mappingStep;

  /**
   * Mapping step service object.
   *
   * @var \Drupal\gathercontent_ui\Form\MappingEditSteps\MappingStepService
   */
  protected $mappingService;

  /**
   * Migration definition creator.
   *
   * @var \Drupal\gathercontent\MigrationDefinitionCreator
   */
  protected $migrationDefinitionCreator;

  /**
   * MappingEditForm constructor.
   *
   * @param \Drupal\Core\Entity\EntityFieldManagerInterface $entityFieldManager
   *   EntityFieldManagerInterface.
   * @param \Cheppers\GatherContent\GatherContentClientInterface $client
   *   GatherContent client.
   * @param \Drupal\gathercontent_ui\Form\MappingEditSteps\MappingStepService $mapping_service
   *   MappingStepService.
   * @param \Drupal\gathercontent\MigrationDefinitionCreator $migrationDefinitionCreator
   *   MigrationDefinitionCreator.
   */
  public function __construct(EntityFieldManagerInterface $entityFieldManager, GatherContentClientInterface $client, MappingStepService $mapping_service, MigrationDefinitionCreator $migrationDefinitionCreator) {
    parent::__construct($entityFieldManager);
    $this->client = $client;
    $this->mappingService = $mapping_service;
    $this->migrationDefinitionCreator = $migrationDefinitionCreator;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity_field.manager'), $container
      ->get('gathercontent.client'), $container
      ->get('gathercontent_ui.mapping_service'), $container
      ->get('gathercontent.migration_creator'));
  }

  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {
    if (empty($this->step)) {
      $this->step = 'field_mapping';
    }
    $form['#attached']['library'][] = 'gathercontent_ui/theme';
    $form['#attached']['library'][] = 'gathercontent_ui/entity_references';

    /** @var \Drupal\gathercontent\Entity\MappingInterface $mapping */
    $mapping = $this->entity;
    $this->new = !$mapping
      ->hasMapping();
    $template = $this->client
      ->templateGet($mapping
      ->getGathercontentTemplateId());
    if ($this->step === 'field_mapping') {
      if (!$this->new) {
        $this->mappingStep = $this->mappingService
          ->getEditStep($mapping, $template);
      }
      else {
        $this->mappingStep = $this->mappingService
          ->getNewStep($mapping, $template);
      }
    }
    elseif ($this->step === 'er_mapping') {

      // Unset previous form.
      foreach ($form as $k => $item) {
        if (!in_array($k, [
          '#attributes',
          '#cache',
        ])) {
          unset($form[$k]);
        }
      }
      $this->mappingStep = $this->mappingService
        ->getEntityReferenceStep($mapping, $template);
      $this->mappingStep
        ->setErImportType($this->erImportType);
      $this->step = 'completed';
    }
    $form = $form + $this->mappingStep
      ->getForm($form_state);
    $this
      ->setEntityReferenceFields($this->mappingStep
      ->getEntityReferenceFields());
    $this
      ->setEntityReferenceFieldsOptions($this->mappingStep
      ->getEntityReferenceFieldsOptions());
    $form['#attached']['drupalSettings']['gathercontent'] = $this->entityReferenceFieldsOptions;
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    if ($form_state
      ->getTriggeringElement()['#id'] == 'edit-submit') {
      if ($this->step === 'field_mapping') {
        $this->mappingStep
          ->doValidate($form, $form_state);
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    if ($form_state
      ->getTriggeringElement()['#id'] == 'edit-submit') {

      /** @var \Drupal\gathercontent\Entity\MappingInterface $mapping */
      $mapping = $this->entity;
      $entityStorage = \Drupal::entityTypeManager()
        ->getStorage('taxonomy_term');
      if ($this->step === 'field_mapping') {
        $this->step = 'er_mapping';
        $this
          ->extractMappingData($form_state
          ->getValues());
        if ($this->new) {
          $this->contentType = $form_state
            ->getValue('content_type');
          $this->entityType = $form_state
            ->getValue('entity_type');
        }
        else {
          $this->contentType = $mapping
            ->getContentType();
          $this->entityType = $mapping
            ->getMappedEntityType();
        }
        $this->erImportType = $form_state
          ->getValue('er_mapping_type');
        if (empty($this->entityReferenceFields) || $this->erImportType === 'automatic') {
          $this->skip = TRUE;
        }
        if (!$this->skip) {
          $form_state
            ->setRebuild(TRUE);
        }
      }
      if ($this->step === 'completed' || $this->skip) {
        $this->erImported = 0;

        // TODO: make it changeable.
        if (!$mapping
          ->getMappedEntityType()) {
          $mapping
            ->setMappedEntityType($this->entityType);
        }
        if ($this->new) {
          $mapping
            ->setContentType($this->contentType);
          $bundles = $this->mappingStep
            ->getBundles($this->entityType);
          $mapping
            ->setContentTypeName($bundles[$this->contentType]);
        }
        $mapping
          ->setData(serialize($this->mappingData));
        $mapping
          ->setUpdatedDrupal(time());
        $template = $this->client
          ->templateGet($mapping
          ->getGathercontentTemplateId());
        $mapping
          ->setTemplate(serialize($this->client
          ->getBody(TRUE)));
        $mapping
          ->save();

        // We need to modify field for checkboxes and field instance for radios.
        foreach ($template['related']->structure->groups as $group) {
          foreach ($group->fields as $gcField) {
            $local_field_id = $this->mappingData[$group->id]['elements'][$gcField->id];
            if ($gcField->type === 'choice_checkbox') {
              if (!empty($local_field_id)) {
                $local_options = [];
                foreach ($gcField->metaData->choiceFields['options'] as $option) {
                  $local_options[$option['optionId']] = $option['label'];
                }
                $local_id_array = explode('||', $local_field_id);
                $field_info = FieldConfig::load($local_id_array[count($local_id_array) - 1]);
                if ($field_info
                  ->getType() === 'entity_reference') {
                  if ($this->erImportType === 'automatic') {
                    $this
                      ->automaticTermsGenerator($field_info, $local_options, isset($this->mappingData[$group->id]['language']) ? $this->mappingData[$group->id]['language'] : LanguageInterface::LANGCODE_NOT_SPECIFIED);
                  }
                }
                else {
                  $field_info = $field_info
                    ->getFieldStorageDefinition();

                  // Make the change.
                  $field_info
                    ->setSetting('allowed_values', $local_options);
                  try {
                    $field_info
                      ->save();
                  } catch (\Exception $e) {

                    // Log something.
                  }
                }
              }
            }
            elseif ($gcField->type === 'choice_radio') {
              if (!empty($local_field_id)) {
                $local_options = [];
                foreach ($gcField->metaData->choiceFields['options'] as $option) {
                  $local_options[$option['optionId']] = $option['label'];
                }
                $local_id_array = explode('||', $local_field_id);
                $field_info = FieldConfig::load($local_id_array[count($local_id_array) - 1]);
                if ($field_info
                  ->getType() === 'entity_reference') {
                  if ($this->erImportType === 'automatic') {
                    $this
                      ->automaticTermsGenerator($field_info, $local_options, isset($this->mappingData[$group->id]['language']) ? $this->mappingData[$group->id]['language'] : LanguageInterface::LANGCODE_NOT_SPECIFIED);
                  }
                }
                else {
                  $new_local_options = [];
                  foreach ($local_options as $name => $label) {
                    $new_local_options[] = $name . '|' . $label;
                  }
                  $entity = \Drupal::entityTypeManager()
                    ->getStorage('entity_form_display')
                    ->load('node.' . $mapping
                    ->getContentType() . '.default');

                  /** @var \Drupal\Core\Entity\Entity\EntityFormDisplay $entity */
                  $entity
                    ->getRenderer($field_info
                    ->getName())
                    ->setSetting('available_options', implode("\n", $new_local_options));
                }
              }
            }
          }
        }

        // If we went through mapping of er, we want to save them.
        if (!$this->skip) {
          $form_state
            ->cleanValues();
          $fields = $form_state
            ->getValues();

          // Prepare options for every language for every field.
          $options = $this
            ->prepareOptions($template);
          foreach ($fields as $field_id => $tables) {
            $field_id = str_replace('--', '.', $field_id);
            $vid = $this
              ->getVocabularyId($field_id);

            // Check if gathercontent_options_ids field exists.
            $this
              ->gcOptionIdsFieldExists($vid);
            foreach ($tables as $table) {
              foreach ($table as $row) {
                $languages = $this
                  ->getAvailableLanguages($row);
                if ($this->erImportType === 'manual') {
                  $this
                    ->manualErImport($languages, $entityStorage, $row);
                }
                else {
                  $this
                    ->semiErImport($languages, $entityStorage, $row, $options, $vid);
                }
              }
            }
          }
        }
        if ($this->new) {
          $this
            ->messenger()
            ->addMessage($this
            ->t('Mapping has been created.'));
        }
        else {
          $this
            ->messenger()
            ->addMessage($this
            ->t('Mapping has been updated.'));
        }
        $this->migrationDefinitionCreator
          ->setMapping($mapping)
          ->setMappingData($this->mappingData)
          ->createMigrationDefinition();
        if (!empty($this->entityReferenceFields)) {
          $this
            ->messenger()
            ->addMessage($this
            ->formatPlural($this->erImported, '@count term was imported', '@count terms were imported'));
        }
        $form_state
          ->setRedirect('entity.gathercontent_mapping.collection');
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  protected function actions(array $form, FormStateInterface $form_state) {
    $actions = parent::actions($form, $form_state);
    $actions['submit']['#value'] = $this->new ? $this
      ->t('Create mapping') : $this
      ->t('Update mapping');
    $actions['close'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Cancel'),
    ];
    unset($actions['delete']);
    return $actions;
  }

}

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
EntityForm::$entity protected property The entity being used by this form. 7
EntityForm::$entityTypeManager protected property The entity type manager. 3
EntityForm::$moduleHandler protected property The module handler service.
EntityForm::$operation protected property The name of the current operation.
EntityForm::$privateEntityManager private property The entity manager.
EntityForm::actionsElement protected function Returns the action form element for the current entity form.
EntityForm::afterBuild public function Form element #after_build callback: Updates the entity with submitted data.
EntityForm::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides EntityFormInterface::buildEntity 2
EntityForm::buildForm public function Form constructor. Overrides FormInterface::buildForm 10
EntityForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties 7
EntityForm::getBaseFormId public function Returns a string identifying the base form. Overrides BaseFormIdInterface::getBaseFormId 5
EntityForm::getEntity public function Gets the form entity. Overrides EntityFormInterface::getEntity
EntityForm::getEntityFromRouteMatch public function Determines which entity will be used by this form from a RouteMatch object. Overrides EntityFormInterface::getEntityFromRouteMatch 1
EntityForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId 10
EntityForm::getOperation public function Gets the operation identifying the form. Overrides EntityFormInterface::getOperation
EntityForm::init protected function Initialize the form state and the entity before the first form build. 3
EntityForm::prepareEntity protected function Prepares the entity object before the form is built first. 3
EntityForm::prepareInvokeAll protected function Invokes the specified prepare hook variant.
EntityForm::processForm public function Process callback: assigns weights and hides extra fields.
EntityForm::save public function Form submission handler for the 'save' action. Overrides EntityFormInterface::save 41
EntityForm::setEntity public function Sets the form entity. Overrides EntityFormInterface::setEntity
EntityForm::setEntityManager public function Sets the entity manager for this form. Overrides EntityFormInterface::setEntityManager
EntityForm::setEntityTypeManager public function Sets the entity type manager for this form. Overrides EntityFormInterface::setEntityTypeManager
EntityForm::setModuleHandler public function Sets the module handler for this form. Overrides EntityFormInterface::setModuleHandler
EntityForm::setOperation public function Sets the operation for this form. Overrides EntityFormInterface::setOperation
EntityForm::__get public function
EntityForm::__set public function
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.
MappingEditForm::$client protected property GatherContent client.
MappingEditForm::$mappingService protected property Mapping step service object.
MappingEditForm::$mappingStep protected property Step object.
MappingEditForm::$migrationDefinitionCreator protected property Migration definition creator.
MappingEditForm::actions protected function Returns an array of supported actions for the current entity form. Overrides EntityForm::actions
MappingEditForm::create public static function Instantiates a new instance of this class. Overrides MappingEditFormBase::create
MappingEditForm::form public function Gets the actual form array to be built. Overrides EntityForm::form
MappingEditForm::submitForm public function This is the default entity object builder function. It is called before any other submit handler to build the new entity object to be used by the following submit handlers. At this point of the form workflow the entity is validated and the form state… Overrides EntityForm::submitForm
MappingEditForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
MappingEditForm::__construct public function MappingEditForm constructor. Overrides MappingEditFormBase::__construct
MappingEditFormBase::$contentType protected property Machine name of content type.
MappingEditFormBase::$entityFieldManager protected property Entity field manager.
MappingEditFormBase::$entityReferenceFields protected property Array of entity reference fields in mapping.
MappingEditFormBase::$entityReferenceFieldsOptions protected property Array of entity reference fields in mapping.
MappingEditFormBase::$entityType protected property Machine name of entity type.
MappingEditFormBase::$erImported protected property Count of imported or updated taxonomy terms.
MappingEditFormBase::$erImportType protected property Type of import for entity reference fields.
MappingEditFormBase::$mappingData protected property Mapping data.
MappingEditFormBase::$new protected property Flag for mapping if it's new.
MappingEditFormBase::$skip protected property Flag for skipping ER mapping.
MappingEditFormBase::$step protected property Step in multipart form.
MappingEditFormBase::$template protected property GatherContent full template.
MappingEditFormBase::automaticTermsGenerator public function Generate automatically terms for local field from GatherContent options.
MappingEditFormBase::extractMappingData public function Extract mapping data from submitted form values.
MappingEditFormBase::gcOptionIdsFieldExists public function Validate if gathercontent_option_ids field exists on specified vocabulary.
MappingEditFormBase::getAvailableLanguages public function Get available languages from currect row.
MappingEditFormBase::getContentTypes public function Ajax callback for mapping multistep form.
MappingEditFormBase::getMappingTable public function Ajax callback for mapping multistep form.
MappingEditFormBase::getVocabularyId public function Get vocabulary identifier for field in content type.
MappingEditFormBase::manualErImport public function Handle manual type of taxonomy terms.
MappingEditFormBase::prepareOptions public function Prepare options for every language for every field.
MappingEditFormBase::semiErImport public function Handle semiautomatic import of taxonomy terms.
MappingEditFormBase::setEntityReferenceFields public function Sets entityReferenceFields variable.
MappingEditFormBase::setEntityReferenceFieldsOptions public function Sets entityReferenceFieldsOptions variable.
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.