You are here

class MailingListImportForm in Mailing List 8

Mailing list import.

Hierarchy

Expanded class hierarchy of MailingListImportForm

1 string reference to 'MailingListImportForm'
mailing_list.routing.yml in ./mailing_list.routing.yml
mailing_list.routing.yml

File

src/Form/MailingListImportForm.php, line 19

Namespace

Drupal\mailing_list\Form
View source
class MailingListImportForm extends FormBase {

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The mailing list to work with.
   *
   * @var \Drupal\mailing_list\MailingListInterface
   */
  protected $mailingList;

  /**
   * The email validator.
   *
   * @var \Egulias\EmailValidator\EmailValidator
   */
  protected $emailValidator;

  /**
   * Constructs a MailingListImportForm object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
   *   The string translation service.
   * @param \Egulias\EmailValidator\EmailValidator $email_validator
   *   The email validator.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, TranslationInterface $string_translation, EmailValidator $email_validator) {
    $this->entityTypeManager = $entity_type_manager;
    $this->stringTranslation = $string_translation;
    $this->emailValidator = $email_validator;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity_type.manager'), $container
      ->get('string_translation'), $container
      ->get('email.validator'));
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'mailing_list_import';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, MailingListInterface $mailing_list = NULL) {
    $this->mailingList = $mailing_list;
    $form['#title'] = $this
      ->t('Import subscriptions into %label mailing list', [
      '%label' => $mailing_list
        ->label(),
    ]);
    $form['emails'] = [
      '#type' => 'textarea',
      '#title' => $this
        ->t('Email addresses'),
      '#description' => $this
        ->t('The email addresses to subscribe, one per line.'),
      '#required' => TRUE,
      '#rows' => 10,
      '#resizable' => 'vertical',
      '#default_value' => '',
    ];
    $form['no_duplicate'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Prevent duplicates'),
      '#description' => $this
        ->t('Do not create new subscriptions for already existent subscribed emails'),
      '#default_value' => TRUE,
    ];
    $form['activate'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Create as active'),
      '#description' => $this
        ->t('Set active status for new subscriptions.'),
      '#default_value' => TRUE,
    ];
    $form['activate_existent'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Active existent'),
      '#description' => $this
        ->t('Enable to activate existing inactive subscriptions.'),
      '#default_value' => FALSE,
      '#states' => [
        'disabled' => [
          ':input[name="activate"]' => [
            'checked' => FALSE,
          ],
        ],
      ],
    ];
    $form['anonymous'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Anonymous subscriber'),
      '#description' => $this
        ->t('New subscriptions will be owned by the anonymous user. Existing subscriptions will not be altered.'),
      '#default_value' => TRUE,
    ];
    $form['actions']['import'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Import'),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);
    foreach (preg_split("/\\r\\n|\\r|\\n/", $form_state
      ->getValue('emails')) as $email) {
      if (!empty($email) && !$this->emailValidator
        ->isValid($email)) {
        $form_state
          ->setErrorByName('emails', $this
          ->t('%recipient is an invalid email address.', [
          '%recipient' => $email,
        ]));
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $storage = $this->entityTypeManager
      ->getStorage('mailing_list_subscription');

    /** @var \Drupal\mailing_list\SubscriptionInterface[] $existent_subscriptions */
    $existent_subscriptions = [];
    if ($no_duplicate = $form_state
      ->getValue('no_duplicate', TRUE)) {
      $query = $storage
        ->getQuery()
        ->condition('mailing_list', $this->mailingList
        ->id());

      /** @var \Drupal\mailing_list\SubscriptionInterface $subscription */
      foreach ($storage
        ->loadMultiple($query
        ->execute()) as $subscription) {
        $existent_subscriptions[$subscription
          ->getEmail()] = $subscription;
      }
    }
    $activate = $form_state
      ->getValue('activate', TRUE);
    $activate_existent = !$activate ?: $form_state
      ->getValue('activate_existent', FALSE);
    $uid = $form_state
      ->getValue('anonymous', TRUE) ? User::getAnonymousUser()
      ->id() : $this
      ->currentUser()
      ->id();
    $count = 0;
    foreach (preg_split("/\\r\\n|\\r|\\n/", $form_state
      ->getValue('emails')) as $email) {
      if (isset($existent_subscriptions[$email])) {
        $subscription = $existent_subscriptions[$email];
        if ($activate && $activate_existent && !$subscription
          ->isActive()) {
          $subscription
            ->setStatus(SubscriptionInterface::ACTIVE)
            ->save();
          $count++;
        }
      }
      else {
        $subscription = Subscription::create([
          'title' => $email,
          'mailing_list' => $this->mailingList
            ->id(),
          'email' => $email,
          'status' => $activate ? SubscriptionInterface::ACTIVE : SubscriptionInterface::INACTIVE,
          'uid' => $uid,
        ]);
        $existent_subscriptions[$email] = $subscription;
        $subscription
          ->save();
        $count++;
      }
    }
    drupal_set_message(!$count ? $this
      ->t('No subscriptions added.') : $this
      ->formatPlural($count, '1 subscription added to %label mailing list.', '@count new subscriptions added to %label mailing list.', [
      '@count' => $count,
      '%label' => $this->mailingList
        ->label(),
    ]));
    $form_state
      ->setRedirect('entity.mailing_list.collection');
  }

}

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.
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.
MailingListImportForm::$emailValidator protected property The email validator.
MailingListImportForm::$entityTypeManager protected property The entity type manager.
MailingListImportForm::$mailingList protected property The mailing list to work with.
MailingListImportForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
MailingListImportForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
MailingListImportForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
MailingListImportForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
MailingListImportForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
MailingListImportForm::__construct public function Constructs a MailingListImportForm object.
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.