You are here

class ContactForm in Email Contact 8

Hierarchy

Expanded class hierarchy of ContactForm

2 files declare their use of ContactForm
ContactController.php in src/Controller/ContactController.php
EmailContactInlineFormatter.php in src/Plugin/Field/FieldFormatter/EmailContactInlineFormatter.php

File

src/Form/ContactForm.php, line 10

Namespace

Drupal\email_contact\Form
View source
class ContactForm extends FormBase {
  private $entity_type;
  private $entity_id;
  private $field_name;
  private $field_settings;
  public function __construct($entity_type = NULL, $entity_id = NULL, $field_name = NULL, $field_settings = NULL) {
    $this->entity_type = $entity_type;
    $this->entity_id = $entity_id;
    $this->field_name = $field_name;
    $this->field_settings = $field_settings;
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    $form_id = 'email_contact_mail';
    if ($this->entity_id) {
      $form_id .= '_' . $this->entity_id;
    }
    return $form_id . '_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    // $this->entity_id = $id;
    $user = \Drupal::currentUser();
    $emails = email_contact_get_emails_from_field($this->entity_type, $this->entity_id, $this->field_name);
    $form['emails'] = array(
      '#type' => 'value',
      '#value' => serialize($emails),
    );
    $form['name'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Your name'),
      '#maxlength' => 255,
      '#default_value' => $user
        ->id() ? $user
        ->getDisplayName() : '',
      '#required' => TRUE,
    ];
    $form['mail'] = array(
      '#type' => 'textfield',
      '#title' => $this
        ->t('Your e-mail address'),
      '#maxlength' => 255,
      '#default_value' => $user
        ->id() ? $user
        ->getEmail() : '',
      '#required' => TRUE,
    );
    $form['subject'] = array(
      '#type' => 'textfield',
      '#title' => $this
        ->t('Subject'),
      '#maxlength' => 255,
      '#required' => TRUE,
    );
    $form['message'] = array(
      '#type' => 'textarea',
      '#title' => $this
        ->t('Message'),
      '#required' => TRUE,
    );
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => $this
        ->t('Send e-mail'),
    );
    if (!$form_state
      ->get('settings')) {
      $form_state
        ->set('settings', $this->field_settings);
    }
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    if (!\Drupal::service('email.validator')
      ->isValid($form_state
      ->getValue('mail'))) {
      $form_state
        ->setErrorByName('mail', $this
        ->t('You must enter a valid e-mail address.'));
    }
    if (preg_match("/\r|\n/", $form_state
      ->getValue('subject'))) {
      $form_state
        ->setErrorByName('subject', $this
        ->t('The subject cannot contain linebreaks.'));
      $msg = 'Email injection exploit attempted in email form subject: @subject';
      $this
        ->logger('email_contact')
        ->notice($msg, [
        '@subject' => $form_state['values']['subject'],
      ]);
    }
  }

  /**
   * {@inheritdoc}
   */
  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);
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ContactForm::$entity_id private property
ContactForm::$entity_type private property
ContactForm::$field_name private property
ContactForm::$field_settings private property
ContactForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
ContactForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
ContactForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
ContactForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
ContactForm::__construct public function
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 87
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.