You are here

public function FieldsSettingsForm::submitForm in Diff 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 ConfigFormBase::submitForm

File

src/Form/FieldsSettingsForm.php, line 438

Class

FieldsSettingsForm
Configure fields with their diff builder plugin settings.

Namespace

Drupal\diff\Form

Code

public function submitForm(array &$form, FormStateInterface $form_state) {
  $form_values = $form_state
    ->getValues();
  $plugin_settings = $form_state
    ->get('plugin_settings');
  $fields = $form_values['fields'];
  $config = $this
    ->config('diff.plugins');

  // Save the settings.
  foreach ($fields as $field_key => $field_values) {
    $config_key = preg_replace('/__/', '.', $field_key, 1);
    if ($field_values['plugin']['type'] == 'hidden') {
      $config
        ->set('fields.' . $config_key, [
        'type' => 'hidden',
        'settings' => [],
      ]);
    }
    else {

      // Initialize the plugin, if the type is unchanged then with the
      // existing settings, otherwise let it fall back to the default
      // settings.
      $configuration = [];
      if ($config
        ->get('fields.' . $config_key . '.type') == $field_values['plugin']['type'] && $config
        ->get('fields.' . $config_key . '.settings')) {
        $configuration = $config
          ->get('fields.' . $config_key . '.settings');
      }
      $plugin = $this->diffBuilderManager
        ->createInstance($field_values['plugin']['type'], $configuration);

      // Get plugin settings. They lie either directly in submitted form
      // values (if the whole form was submitted while some plugin settings
      // were being edited), or have been persisted in $form_state.
      $values = NULL;

      // Form submitted without pressing update button on plugin settings form.
      if (isset($field_values['settings_edit_form']['settings'])) {
        $values = $field_values['settings_edit_form']['settings'];
      }
      elseif (isset($plugin_settings[$field_key]['settings'])) {
        $values = $plugin_settings[$field_key]['settings'];
      }

      // Build a FormState object and call the plugin submit handler.
      if ($values) {
        $state = new FormState();
        $state
          ->setValues($values);
        $plugin
          ->submitConfigurationForm($form, $state);
      }
      $config
        ->set('fields.' . $config_key, [
        'type' => $field_values['plugin']['type'],
        'settings' => $plugin
          ->getConfiguration(),
      ]);
    }
  }
  $config
    ->save();
  $this
    ->messenger()
    ->addStatus($this
    ->t('Your settings have been saved.'));
}