You are here

class HtmlMailTestForm in HTML Mail 8

Same name and namespace in other branches
  1. 8.3 src/Form/HtmlMailTestForm.php \Drupal\htmlmail\Form\HtmlMailTestForm

Class HtmlMailTestForm.

@package Drupal\htmlmail\Form

Hierarchy

Expanded class hierarchy of HtmlMailTestForm

1 string reference to 'HtmlMailTestForm'
htmlmail.routing.yml in ./htmlmail.routing.yml
htmlmail.routing.yml

File

src/Form/HtmlMailTestForm.php, line 18

Namespace

Drupal\htmlmail\Form
View source
class HtmlMailTestForm extends FormBase {
  protected $mailManager;
  protected $accountInterface;
  const KEY_NAME = 'test';
  const DEFAULT_MAIL = 'user@example.com';

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('plugin.manager.mail'), $container
      ->get('current_user'));
  }

  /**
   * HtmlMailTestForm constructor.
   *
   * @param \Drupal\Core\Mail\MailManagerInterface $mailManager
   *   The mail manager service.
   * @param \Drupal\Core\Session\AccountInterface $account
   *   The user account service.
   */
  public function __construct(MailManagerInterface $mailManager, AccountInterface $account) {
    $this->mailManager = $mailManager;
    $this->accountInterface = $account;
  }

  /**
   * Returns a unique string identifying the form.
   *
   * @return string
   *   The unique string identifying the form.
   */
  public function getFormId() {
    return 'htmlmail_test';
  }

  /**
   * Form constructor.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @return array
   *   The form structure.
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this
      ->config('htmlmail.settings');
    $defaults = $config
      ->get('htmlmail_test');
    if (empty($defaults)) {
      $defaults = [
        'to' => $config
          ->get('site_mail') ?: self::DEFAULT_MAIL,
        'subject' => self::KEY_NAME,
        'body' => [
          'value' => self::KEY_NAME,
        ],
        'class' => HtmlMailHelper::getModuleName(),
      ];
    }
    if (empty($defaults['body']['format'])) {
      $defaults['body']['format'] = filter_default_format();
    }
    $form['to'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('To'),
      '#default_value' => $defaults['to'],
      '#maxlength' => 128,
      '#required' => TRUE,
    ];
    $form['subject'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Subject'),
      '#default_value' => $defaults['subject'],
      '#maxlength' => 128,
      '#required' => TRUE,
    ];
    $form['body'] = [
      '#type' => 'text_format',
      '#title' => $this
        ->t('Body'),
      '#rows' => 20,
      '#default_value' => $defaults['body']['value'],
      '#format' => $defaults['body']['format'],
      '#required' => TRUE,
    ];
    $form['class'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Test mail sending class'),
      '#options' => $this
        ->getOptions(),
      '#default_value' => $defaults['class'],
      '#description' => $this
        ->t('Select the MailSystemInterface implementation to be tested.'),
    ];
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Send test message'),
    ];
    return $form;
  }

  /**
   * Returns a list with all mail plugins.
   *
   * @return string[]
   *   List of mail plugin labels, keyed by ID.
   */
  protected function getOptions() {
    $list = [];

    // Append all MailPlugins.
    foreach ($this->mailManager
      ->getDefinitions() as $definition) {
      $list[$definition['id']] = $definition['label'];
    }
    if (empty($list)) {
      $list['htmlmail'] = 'HTMLMailSystem';
    }
    return $list;
  }

  /**
   * Form submission handler.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    // Get the form values.
    $defaults = [
      'to' => $form_state
        ->getValue('to'),
      'subject' => $form_state
        ->getValue('subject'),
      'body' => $form_state
        ->getValue('body'),
      'class' => $form_state
        ->getValue('class'),
    ];

    // Set the defaults for reuse.
    $config = $this
      ->configFactory()
      ->getEditable('htmlmail.settings');
    $config
      ->set('htmlmail_test', $defaults)
      ->save();

    // Send the email.
    $params = [
      'subject' => $defaults['subject'],
      'body' => check_markup($defaults['body']['value'], $defaults['body']['format']),
    ];

    // Send the email.
    $langcode = $this->accountInterface
      ->getPreferredLangcode();
    $config = $this
      ->configFactory()
      ->getEditable('mailsystem.settings');
    $config
      ->set('defaults.sender', $defaults['class'])
      ->set('defaults.formatter', $defaults['class'])
      ->save();
    $result = $this->mailManager
      ->mail(HtmlMailHelper::getModuleName(), self::KEY_NAME, $defaults['to'], $langcode, $params, NULL, TRUE);
    if ($result['result'] === TRUE) {
      drupal_set_message($this
        ->t('HTML Mail test message sent.'));
    }
    else {
      drupal_set_message($this
        ->t('Something went wrong. Please check @logs for details.', [
        '@logs' => Link::createFromRoute($this
          ->t('logs'), 'dblog.overview')
          ->toString(),
      ]), 'error');
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
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::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.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
HtmlMailTestForm::$accountInterface protected property
HtmlMailTestForm::$mailManager protected property
HtmlMailTestForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
HtmlMailTestForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
HtmlMailTestForm::DEFAULT_MAIL constant
HtmlMailTestForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
HtmlMailTestForm::getOptions protected function Returns a list with all mail plugins.
HtmlMailTestForm::KEY_NAME constant
HtmlMailTestForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
HtmlMailTestForm::__construct public function HtmlMailTestForm constructor.
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.