You are here

public function AvatarKitEntityMappingForm::submitForm in Avatar Kit 8.2

Form submission handler.

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 ConfigFormBase::submitForm

File

src/Form/AvatarKitEntityMappingForm.php, line 164

Class

AvatarKitEntityMappingForm
Configure Avatar Kit entity maps.

Namespace

Drupal\avatars\Form

Code

public function submitForm(array &$form, FormStateInterface $form_state) {
  parent::submitForm($form, $form_state);

  /** @var \Drupal\avatars\Entity\AvatarKitEntityMapInterface[] $entityMaps */
  $entityMaps = $this->entityMappingStorage
    ->loadMultiple();
  $map = $form_state
    ->getValue('map');
  foreach ($map as $key => $values) {
    [
      $entityType,
      $bundle,
    ] = explode(':', $key);
    $mapKey = $entityType . '.' . $bundle . '.default';

    // Check if a map exists already.
    $entityMap = $entityMaps[$mapKey] ?? NULL;
    $fieldName = $values['field'];
    if (!$fieldName) {
      continue;
    }
    unset($entityMaps[$mapKey]);
    if (!$entityMap) {

      // Otherwise create one.
      $entityMap = $this->entityMappingStorage
        ->create([
        'entity_type' => $entityType,
        'bundle' => $bundle,
      ]);
    }
    $entityMap
      ->set('field_name', $fieldName);
    $entityMap
      ->save();
  }

  // Delete any left over mappings.
  foreach ($entityMaps as $entityMap) {
    $entityMap
      ->delete();
  }
}