You are here

class NodeTabForm in Simplenews 8.2

Same name and namespace in other branches
  1. 8 src/Form/NodeTabForm.php \Drupal\simplenews\Form\NodeTabForm
  2. 3.x src/Form/NodeTabForm.php \Drupal\simplenews\Form\NodeTabForm

Configure simplenews subscriptions of a user.

Hierarchy

Expanded class hierarchy of NodeTabForm

1 string reference to 'NodeTabForm'
simplenews.routing.yml in ./simplenews.routing.yml
simplenews.routing.yml

File

src/Form/NodeTabForm.php, line 18

Namespace

Drupal\simplenews\Form
View source
class NodeTabForm extends FormBase {

  /**
   * The spool storage.
   *
   * @var \Drupal\simplenews\Spool\SpoolStorageInterface
   */
  protected $spoolStorage;

  /**
   * The currently authenticated user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  /**
   * The simplenews mailer.
   *
   * @var \Drupal\simplenews\Mail\MailerInterface
   */
  protected $mailer;

  /**
   * The email validator.
   *
   * @var \Drupal\Component\Utility\EmailValidatorInterface
   */
  protected $emailValidator;

  /**
   * Constructs a new NodeTabForm.
   *
   * @param \Drupal\simplenews\Spool\SpoolStorageInterface $spool_storage
   *   The spool storage.
   * @param \Drupal\Core\Session\AccountInterface $current_user
   *   The currently authenticated user.
   * @param \Drupal\simplenews\Mail\MailerInterface $simplenews_mailer
   *   The simplenews mailer service.
   * @param \Drupal\Component\Utility\EmailValidatorInterface $email_validator
   *   The email validator.
   */
  public function __construct(SpoolStorageInterface $spool_storage, AccountInterface $current_user, MailerInterface $simplenews_mailer, EmailValidatorInterface $email_validator) {
    $this->spoolStorage = $spool_storage;
    $this->currentUser = $current_user;
    $this->mailer = $simplenews_mailer;
    $this->emailValidator = $email_validator;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('simplenews.spool_storage'), $container
      ->get('current_user'), $container
      ->get('simplenews.mailer'), $container
      ->get('email.validator'));
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, NodeInterface $node = NULL) {
    $config = $this
      ->config('simplenews.settings');
    $status = $node->simplenews_issue->status;
    $summary = $this->spoolStorage
      ->issueSummary($node);
    $form['#title'] = $this
      ->t('<em>Newsletter issue</em> @title', [
      '@title' => $node
        ->getTitle(),
    ]);

    // We will need the node.
    $form_state
      ->set('node', $node);

    // Show newsletter sending options if newsletter has not been send yet.
    // If send a notification is shown.
    if ($status == SIMPLENEWS_STATUS_SEND_NOT) {
      $form['test'] = [
        '#type' => 'details',
        '#open' => TRUE,
        '#title' => $this
          ->t('Test'),
      ];
      $form['test']['test_address'] = [
        '#type' => 'textfield',
        '#title' => $this
          ->t('Test email addresses'),
        '#description' => $this
          ->t('A comma-separated list of email addresses to be used as test addresses.'),
        '#default_value' => $this->currentUser
          ->getEmail(),
        '#size' => 60,
        '#maxlength' => 128,
      ];
      $form['test']['submit'] = [
        '#type' => 'submit',
        '#value' => $this
          ->t('Send test newsletter issue'),
        '#name' => 'send_test',
        '#submit' => [
          '::submitTestMail',
        ],
        '#validate' => [
          '::validateTestAddress',
        ],
      ];
      $form['send'] = [
        '#type' => 'details',
        '#open' => TRUE,
        '#title' => $this
          ->t('Send'),
      ];

      // Add some text to describe the send situation.
      $form['send']['count'] = [
        '#type' => 'item',
        '#markup' => $this
          ->t('Send newsletter issue to @count subscribers.', [
          '@count' => $summary['count'],
        ]),
      ];
      if (!$node
        ->isPublished()) {
        $send_text = $this
          ->t('Mails will be sent when the issue is published.');
        $button_text = $this
          ->t('Send on publish');
      }
      elseif (!$config
        ->get('mail.use_cron')) {
        $send_text = $this
          ->t('Mails will be sent immediately.');
      }
      else {
        $send_text = $this
          ->t('Mails will be sent when cron runs.');
      }
      $form['send']['method'] = [
        '#type' => 'item',
        '#markup' => $send_text,
      ];
      $form['send']['send'] = [
        '#type' => 'submit',
        '#button_type' => 'primary',
        '#value' => $button_text ?? $this
          ->t('Send now'),
      ];
    }
    else {
      $form['status'] = [
        '#type' => 'item',
        '#title' => $summary['description'],
      ];
      if ($status != SIMPLENEWS_STATUS_SEND_READY) {
        $form['actions'] = [
          '#type' => 'actions',
        ];
        $form['actions']['stop'] = [
          '#type' => 'submit',
          '#submit' => [
            '::submitStop',
          ],
          '#value' => $this
            ->t('Stop sending'),
        ];
      }
    }
    return $form;
  }

  /**
   * Validates the test address.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Form state.
   */
  public function validateTestAddress(array $form, FormStateInterface $form_state) {
    $test_address = $form_state
      ->getValue('test_address');
    $test_address = trim($test_address);
    if (!empty($test_address)) {
      $mails = explode(',', $test_address);
      foreach ($mails as $mail) {
        $mail = trim($mail);
        if (!$this->emailValidator
          ->isValid($mail)) {
          $form_state
            ->setErrorByName('test_address', $this
            ->t('Invalid email address "%mail".', [
            '%mail' => $mail,
          ]));
        }
      }
      $form_state
        ->set('test_addresses', $mails);
    }
    else {
      $form_state
        ->setErrorByName('test_address', $this
        ->t('Missing test email address.'));
    }
  }

  /**
   * Submit handler for sending test mails.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Form state.
   */
  public function submitTestMail(array &$form, FormStateInterface $form_state) {
    $this->mailer
      ->sendTest($form_state
      ->get('node'), $form_state
      ->get('test_addresses'));
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $this->spoolStorage
      ->addIssue($form_state
      ->get('node'));
  }

  /**
   * Submit handler for stopping published newsletter issue.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Form state.
   */
  public function submitStop(array &$form, FormStateInterface $form_state) {
    $this->spoolStorage
      ->deleteIssue($form_state
      ->get('node'));
  }

  /**
   * Checks access for the simplenews node tab.
   *
   * @param \Drupal\node\NodeInterface $node
   *   The node where the tab should be added.
   *
   * @return \Drupal\Core\Access\AccessResult
   *   An access result object.
   */
  public function checkAccess(NodeInterface $node) {
    $account = $this
      ->currentUser();
    if ($node
      ->hasField('simplenews_issue') && $node->simplenews_issue->target_id != NULL) {
      return AccessResult::allowedIfHasPermission($account, 'administer newsletters')
        ->orIf(AccessResult::allowedIfHasPermission($account, 'send newsletter'));
    }
    return AccessResult::neutral();
  }

}

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
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.
NodeTabForm::$currentUser protected property The currently authenticated user.
NodeTabForm::$emailValidator protected property The email validator.
NodeTabForm::$mailer protected property The simplenews mailer.
NodeTabForm::$spoolStorage protected property The spool storage.
NodeTabForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
NodeTabForm::checkAccess public function Checks access for the simplenews node tab.
NodeTabForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
NodeTabForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
NodeTabForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
NodeTabForm::submitStop public function Submit handler for stopping published newsletter issue.
NodeTabForm::submitTestMail public function Submit handler for sending test mails.
NodeTabForm::validateTestAddress public function Validates the test address.
NodeTabForm::__construct public function Constructs a new NodeTabForm.
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.