You are here

public function FieldClonerForm::submitForm in Scheduled Updates 8

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

File

src/Form/FieldClonerForm.php, line 186
Contains \Drupal\scheduled_updates\Form\FieldClonerForm.

Class

FieldClonerForm
Class FieldClonerForm.

Namespace

Drupal\scheduled_updates\Form

Code

public function submitForm(array &$form, FormStateInterface $form_state) {
  $base_fields = array_filter($form_state
    ->getValue('base_fields'));
  $new_map = [];

  // Clone Base Fields
  foreach ($base_fields as $base_field) {

    /** @var \Drupal\field\Entity\FieldConfig $new_field */
    $new_field = $this->fieldManager
      ->cloneField($this->entity, $base_field);
    $new_map[$new_field
      ->getName()] = $base_field;
  }

  // Clone Configurable Fields
  if ($config_field_ids = $form_state
    ->getValue('config_fields')) {
    foreach ($config_field_ids as $config_field_id) {

      /** @var FieldConfig $config_definition */
      if ($config_definition = FieldConfig::load($config_field_id)) {
        $field_name = $config_definition
          ->getFieldStorageDefinition()
          ->getName();
        $new_field = $this->fieldManager
          ->cloneField($this->entity, $field_name, $config_definition
          ->id());
        $new_map[$new_field
          ->getName()] = $field_name;
      }
    }
  }
  if ($new_map) {

    // Update Map
    $this->entity
      ->addNewFieldMappings($new_map);
    $this->entity
      ->save();
    $this
      ->messenger()
      ->addStatus($this
      ->t('The fields have been created and mapped.'));
    if ($this
      ->currentUser()
      ->hasPermission('administer scheduled_update form display')) {

      // Redirect to form display so user and adjust settings.
      $form_state
        ->setRedirectUrl(Url::fromRoute("entity.entity_form_display.scheduled_update.default", array(
        $this->entity
          ->getEntityTypeId() => $this->entity
          ->id(),
      )));
    }
    else {
      $this
        ->messenger()
        ->addWarning($this
        ->t('You do not have permission to administer fields on Scheduled Updates.'));
    }
  }
}