You are here

public function ExampleForm::submitForm in Mime Mail 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

modules/mimemail_example/src/Form/ExampleForm.php, line 199

Class

ExampleForm
The example email contact form.

Namespace

Drupal\mimemail_example\Form

Code

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

  // First, assemble arguments for MailManager::mail().
  $module = 'mimemail_example';
  $key = $form_state
    ->getValue('key');
  $to = $form_state
    ->getValue('to');
  $langcode = $this->languageManager
    ->getDefaultLanguage()
    ->getId();
  $params = $form_state
    ->getValue('params');
  $reply = $params['headers']['Reply-to'];
  $send = TRUE;

  // Second, add values to $params and/or modify submitted values.
  // Set From header.
  if (!empty($form_state
    ->getValue('from_mail'))) {
    $params['headers']['From'] = MimeMailFormatHelper::mimeMailAddress([
      'name' => $form_state
        ->getValue('from'),
      'mail' => $form_state
        ->getValue('from_mail'),
    ]);
  }
  elseif (!empty($form_state
    ->getValue('from'))) {
    $params['headers']['From'] = $from = $form_state
      ->getValue('from');
  }
  else {

    // Empty 'from' will result in the default site email being used.
  }

  // Handle empty attachments - we require this to be an array.
  if (empty($params['attachments'])) {
    $params['attachments'] = [];
  }

  // Remove empty values from $param['headers'] - this will force the
  // the formatting mailsystem and the sending mailsystem to use the
  // default values for these elements.
  foreach ($params['headers'] as $header => $value) {
    if (empty($value)) {
      unset($params['headers'][$header]);
    }
  }

  // Finally, call MailManager::mail() to send the mail.
  $result = $this->mailManager
    ->mail($module, $key, $to, $langcode, $params, $reply, $send);
  if ($result['result'] == TRUE) {
    $this
      ->messenger()
      ->addMessage($this
      ->t('Your message has been sent.'));
  }
  else {

    // This condition is also logged to the 'mail' logger channel by the
    // default PhpMail mailsystem.
    $this
      ->messenger()
      ->addError($this
      ->t('There was a problem sending your message and it was not sent.'));
  }
}