You are here

public function MappingEditForm::submitForm in GatherContent 8.3

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 can be updated, this way the subsequently invoked handlers can retrieve a regular entity object to act on. Generally this method should not be overridden unless the entity requires the same preparation for two actions, see \Drupal\comment\CommentForm for an example with the save and preview actions.

Parameters

array $form: An associative array containing the structure of the form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Overrides EntityForm::submitForm

File

src/Form/MappingEditForm.php, line 802

Class

MappingEditForm
Class MappingEditForm.

Namespace

Drupal\gathercontent\Form

Code

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';
      $mapping_data = $this
        ->extractMappingData($form_state
        ->getValues());
      if ($this->new) {
        $this->contentType = $form_state
          ->getValue('content_type');
      }
      else {
        $this->contentType = $mapping
          ->getContentType();
      }
      $this->erImportType = $form_state
        ->getValue('er_mapping_type');
      $this
        ->getEntityReferenceFields();
      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;
      if ($this->new) {
        $mapping
          ->setContentType($this->contentType);
        $content_types = node_type_get_names();
        $mapping
          ->setContentTypeName($content_types[$this->contentType]);
      }
      $mapping
        ->setData(serialize($this->mappingData));
      $mapping
        ->setUpdatedDrupal(time());
      $tmp = new Template();
      $template = $tmp
        ->getTemplate($mapping
        ->getGathercontentTemplateId());
      $mapping
        ->setTemplate(serialize($template));
      $mapping
        ->save();

      // We need to modify field for checkboxes and field instance for radios.
      foreach ($template->config as $i => $fieldset) {
        if ($fieldset->hidden === FALSE) {
          foreach ($fieldset->elements as $gc_field) {
            $local_field_name = $this->mappingData[$fieldset->name]['elements'][$gc_field->name];
            if ($gc_field->type === 'choice_checkbox') {
              if (!empty($local_field_name)) {
                $local_options = [];
                foreach ($gc_field->options as $option) {
                  $local_options[$option->name] = $option->label;
                }
                $field_info = FieldConfig::loadByName('node', $mapping
                  ->getContentType(), $local_field_name);
                if ($field_info
                  ->getType() === 'entity_reference') {
                  if ($this->erImportType === 'automatic') {
                    $this
                      ->automaticTermsGenerator($field_info, $local_options, isset($this->mappingData[$fieldset->name]['language']) ? $this->mappingData[$fieldset->name]['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 ($gc_field->type === 'choice_radio') {
              if (!empty($mapping_data[$fieldset->name]['elements'][$gc_field->name])) {
                $local_options = [];
                foreach ($gc_field->options as $option) {
                  if (!isset($option->value)) {
                    $local_options[$option->name] = $option->label;
                  }
                }
                $field_info = FieldConfig::loadByName('node', $mapping
                  ->getContentType(), $local_field_name);
                if ($field_info
                  ->getType() === 'entity_reference') {
                  if ($this->erImportType === 'automatic') {
                    $this
                      ->automaticTermsGenerator($field_info, $local_options, isset($this->mappingData[$fieldset->name]['language']) ? $this->mappingData[$fieldset->name]['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($local_field_name)
                    ->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();
        foreach ($fields as $field_name => $tables) {
          $vid = $this
            ->getVocabularyId($field_name);

          // 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) {
        drupal_set_message(t('Mapping has been created.'));
      }
      else {
        drupal_set_message(t('Mapping has been updated.'));
      }
      if (!empty($this->entityReferenceFields)) {
        drupal_set_message($this
          ->formatPlural($this->erImported, '@count term was imported', '@count terms were imported'));
      }
      $form_state
        ->setRedirect('entity.gathercontent_mapping.collection');
    }
  }
}