You are here

public function ContactForm::submitForm in Email Contact 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/ContactForm.php, line 100

Class

ContactForm

Namespace

Drupal\email_contact\Form

Code

public function submitForm(array &$form, FormStateInterface $form_state) {
  $emails = unserialize($form_state
    ->getValue('emails'));

  // E-mail address of the sender: as the form field is a text field,
  // all instances of \r and \n have been automatically stripped from it.
  $reply_to = $form_state
    ->getValue('mail');
  $settings = $form_state
    ->get('settings');
  $params['subject'] = $form_state
    ->getValue('subject');
  $params['name'] = $form_state
    ->getValue('name');
  $params['default_message'] = $settings['default_message'];
  $message = '';
  if ($settings['include_values']) {
    $message .= 'Name: ' . $params['name'] . '<br/>' . 'Email: ' . $reply_to . '<br/>';
  }
  $message .= '<br/>Message: ' . $form_state
    ->getValue('message');
  $params['message'] = Markup::create($message);

  // Send the e-mail to the recipients.
  $mailManager = \Drupal::service('plugin.manager.mail');
  $to = implode(', ', $emails);
  $module = 'email_contact';
  $key = 'contact';
  $langcode = \Drupal::currentUser()
    ->getPreferredLangcode();
  $send = true;
  $result = $mailManager
    ->mail($module, $key, $to, $langcode, $params, $reply_to, $send);
  if ($result['result'] !== true) {
    $this
      ->messenger()
      ->addError($this
      ->t('There was a problem sending your message and it was not sent.'));
  }
  else {
    $this
      ->messenger()
      ->addStatus($this
      ->t('Your message has been sent.'));
    $msg = 'Email sent from: @replyto to: @to about: "@subject" containing: "@message"';
    $this
      ->logger('email_contact')
      ->notice($msg, [
      '@name' => $params['name'],
      '@replyto' => $reply_to,
      '@to' => $to,
      '@subject' => $params['subject'],
      '@message' => $params['message'],
    ]);
  }
  $redirect = '/';
  if (!empty($settings['redirection_to'])) {
    switch ($settings['redirection_to']) {
      case 'current':
        $redirect = NULL;
        break;
      case 'custom':
        $redirect = $settings['custom_path'];
        break;
      default:

        // TODO: $form_state['redirect'] = $path.
        break;
    }
  }
  if ($redirect) {
    $url = Url::fromUserInput($redirect);
    $form_state
      ->setRedirectUrl($url);
  }
}