You are here

public function WebformCiviCRMSettingsForm::submitForm in Webform CiviCRM Integration 8.5

@todo find a more elegant way to handle the handler creation/removal.

Overrides FormInterface::submitForm

File

src/Form/WebformCiviCRMSettingsForm.php, line 63

Class

WebformCiviCRMSettingsForm

Namespace

Drupal\webform_civicrm\Form

Code

public function submitForm(array &$form, FormStateInterface $form_state) {
  $webform = $this
    ->getWebform();
  $handler_collection = $webform
    ->getHandlers('webform_civicrm');
  $values = $form_state
    ->getValues();

  // Check if this is the confirmation form for removed fields.
  if (!isset($values['nid']) && isset($values['delete'], $values['disable'], $values['cancel'])) {
    $triggering_element = $form_state
      ->getTriggeringElement();
    if ($triggering_element['#parents'][0] === 'cancel') {
      $this
        ->messenger()
        ->addMessage('Cancelled');
      return;
    }
    if ($triggering_element['#parents'][0] === 'delete') {

      // Restore the form state values.
      $values += $form_state
        ->get('vals') ?: [];
      $form_state
        ->setValues($values);
    }
    if ($triggering_element['#parents'][0] === 'disable') {

      // @todo probably restore as well, but flag later on not to delete.
      $this
        ->messenger()
        ->addMessage('Disable is not yet supported, canceled form save.');
      return;
    }
  }
  $has_handler = $handler_collection
    ->has('webform_civicrm');
  $remove_handler = empty($values['nid']);
  if (!$has_handler && $remove_handler) {
    $this
      ->messenger()
      ->addWarning('No changes made to CiviCRM settings');
    return;
  }

  /** @var \Drupal\webform\Plugin\WebformHandlerInterface $handler */
  if (!$has_handler) {
    $handler = $this->webformHandlerManager
      ->createInstance('webform_civicrm');
    $handler
      ->setWebform($webform);
    $handler
      ->setHandlerId('webform_civicrm');
    $handler
      ->setStatus(TRUE);
    $webform
      ->addWebformHandler($handler);
  }
  else {
    $handler = $handler_collection
      ->get('webform_civicrm');
  }
  if ($remove_handler) {
    $webform
      ->deleteWebformHandler($handler);
    $this
      ->messenger()
      ->addMessage('Removed CiviCRM');
    return;
  }
  $admin_form = \Drupal::service('webform_civicrm.admin_form')
    ->initialize($form, $form_state, $webform);
  $form_state
    ->cleanValues();
  $admin_form
    ->setSettings($form_state
    ->getValues());
  $admin_form
    ->rebuildData();
  $settings = $admin_form
    ->getSettings();
  $handler_configuration = $handler
    ->getConfiguration();
  $handler_configuration['settings'] = $settings;
  $handler
    ->setConfiguration($handler_configuration);
  $admin_form
    ->postProcess();
  if (empty($admin_form->confirmPage)) {
    $webform
      ->save();
    $this
      ->messenger()
      ->addMessage('Saved CiviCRM settings');
  }
}