You are here

class EnrollInviteEmailForm in Open Social 10.3.x

Same name and namespace in other branches
  1. 8.9 modules/social_features/social_event/modules/social_event_invite/src/Form/EnrollInviteEmailForm.php \Drupal\social_event_invite\Form\EnrollInviteEmailForm
  2. 10.0.x modules/social_features/social_event/modules/social_event_invite/src/Form/EnrollInviteEmailForm.php \Drupal\social_event_invite\Form\EnrollInviteEmailForm
  3. 10.1.x modules/social_features/social_event/modules/social_event_invite/src/Form/EnrollInviteEmailForm.php \Drupal\social_event_invite\Form\EnrollInviteEmailForm
  4. 10.2.x modules/social_features/social_event/modules/social_event_invite/src/Form/EnrollInviteEmailForm.php \Drupal\social_event_invite\Form\EnrollInviteEmailForm

Class EnrollInviteForm.

Hierarchy

Expanded class hierarchy of EnrollInviteEmailForm

1 string reference to 'EnrollInviteEmailForm'
social_event_invite.routing.yml in modules/social_features/social_event/modules/social_event_invite/social_event_invite.routing.yml
modules/social_features/social_event/modules/social_event_invite/social_event_invite.routing.yml

File

modules/social_features/social_event/modules/social_event_invite/src/Form/EnrollInviteEmailForm.php, line 21

Namespace

Drupal\social_event_invite\Form
View source
class EnrollInviteEmailForm extends InviteEmailBaseForm {

  /**
   * The node storage for event enrollments.
   *
   * @var \Drupal\Core\entity\EntityStorageInterface
   */
  protected $entityStorage;

  /**
   * Drupal\Core\TempStore\PrivateTempStoreFactory definition.
   *
   * @var \Drupal\Core\TempStore\PrivateTempStoreFactory
   */
  private $tempStoreFactory;

  /**
   * The Config factory.
   *
   * @var \Drupal\Core\Config\ConfigFactory
   */
  protected $configFactory;

  /**
   * The token service.
   *
   * @var \Drupal\Core\Utility\Token
   */
  protected $token;

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

  /**
   * {@inheritdoc}
   */
  public function __construct(RouteMatchInterface $route_match, EntityTypeManagerInterface $entity_type_manager, LoggerChannelFactoryInterface $logger_factory, EntityStorageInterface $entity_storage, PrivateTempStoreFactory $tempStoreFactory, ConfigFactoryInterface $config_factory, Token $token) {
    parent::__construct($route_match, $entity_type_manager, $logger_factory);
    $this->entityStorage = $entity_storage;
    $this->tempStoreFactory = $tempStoreFactory;
    $this->configFactory = $config_factory;
    $this->token = $token;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('current_route_match'), $container
      ->get('entity_type.manager'), $container
      ->get('logger.factory'), $container
      ->get('entity_type.manager')
      ->getStorage('event_enrollment'), $container
      ->get('tempstore.private'), $container
      ->get('config.factory'), $container
      ->get('token'));
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildForm($form, $form_state);
    $form['#attributes']['class'][] = 'form--default';
    $params = [
      'user' => $this
        ->currentUser(),
      'node' => $this->routeMatch
        ->getParameter('node'),
    ];

    // Load event invite configuration.
    $invite_config = $this->configFactory
      ->get('social_event_invite.settings');

    // Cleanup message body and replace any links on invite preview page.
    $body = $this->token
      ->replace($invite_config
      ->get('invite_message'), $params);
    $body = preg_replace('/href="([^"]*)"/', 'href="#"', $body);

    // Get default logo image and replace if it overridden with email settings.
    $theme_id = $this->configFactory
      ->get('system.theme')
      ->get('default');
    $logo = $this
      ->getRequest()
      ->getBaseUrl() . theme_get_setting('logo.url', $theme_id);
    $email_logo = theme_get_setting('email_logo', $theme_id);
    if (is_array($email_logo) && !empty($email_logo)) {
      $file = File::load(reset($email_logo));
      if ($file instanceof File) {
        $logo = file_create_url($file
          ->getFileUri());
      }
    }
    $form['email_preview'] = [
      '#type' => 'fieldset',
      '#title' => [
        'text' => [
          '#markup' => t('Preview your email invite'),
        ],
        'icon' => [
          '#markup' => '<svg class="icon icon-expand_more"><use xlink:href="#icon-expand_more" /></svg>',
          '#allowed_tags' => [
            'svg',
            'use',
          ],
        ],
      ],
      '#tree' => TRUE,
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
      '#attributes' => [
        'class' => [
          'form-horizontal',
          'form-preview-email',
        ],
      ],
    ];
    $form['email_preview']['preview'] = [
      '#theme' => 'invite_email_preview',
      '#logo' => $logo,
      '#subject' => $this->token
        ->replace($invite_config
        ->get('invite_subject'), $params),
      '#body' => $body,
      '#helper' => $this->token
        ->replace($invite_config
        ->get('invite_helper'), $params),
    ];
    $form['event'] = [
      '#type' => 'hidden',
      '#value' => $this->routeMatch
        ->getRawParameter('node'),
    ];
    $form['actions']['submit_cancel'] = [
      '#type' => 'submit',
      '#weight' => 999,
      '#value' => $this
        ->t('Back to event'),
      '#submit' => [
        [
          $this,
          'cancelForm',
        ],
      ],
      '#limit_validation_errors' => [],
    ];
    return $form;
  }

  /**
   * Cancel form taking you back to an event.
   *
   * @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 cancelForm(array &$form, FormStateInterface $form_state) {
    $form_state
      ->setRedirect('view.event_manage_enrollments.page_manage_enrollments', [
      'node' => $this->routeMatch
        ->getRawParameter('node'),
    ]);
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);
    $nid = $form_state
      ->getValue('event');

    // Check if the user is already enrolled.
    foreach ($form_state
      ->getValue('users_fieldset')['user'] as $user) {

      // Check if the user is a filled in email.
      $email = $this
        ->extractEmailsFrom($user);
      if ($email) {
        $conditions = [
          'field_email' => $email,
          'field_event' => $nid,
        ];
      }
      else {
        $conditions = [
          'field_account' => $user,
          'field_event' => $nid,
        ];
      }
      $enrollments = $this->entityStorage
        ->loadByProperties($conditions);
      if (!empty($enrollments)) {

        /** @var \Drupal\social_event\Entity\EventEnrollment $enrollment */
        $enrollment = end($enrollments);

        // Of course, only delete the previous invite if it was declined
        // or if it was invalid or expired.
        $status_checks = [
          EventEnrollmentInterface::REQUEST_OR_INVITE_DECLINED,
          EventEnrollmentInterface::INVITE_INVALID_OR_EXPIRED,
        ];
        if (in_array($enrollment->field_request_or_invite_status->value, $status_checks)) {
          $enrollment
            ->delete();
          unset($enrollments[$enrollment
            ->id()]);
        }
      }

      // If enrollments can be found this user is already invited or joined.
      if (!empty($enrollments)) {

        // If the user is already enrolled, don't enroll them again.
        $form_state
          ->unsetValue([
          'users_fieldset',
          'user',
          $user,
        ]);
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    parent::submitForm($form, $form_state);
    $params['recipients'] = $form_state
      ->getValue('users_fieldset')['user'];
    $params['nid'] = $form_state
      ->getValue('event');
    $tempstore = $this->tempStoreFactory
      ->get('event_invite_form_values');
    try {
      $tempstore
        ->set('params', $params);

      // Create batch for sending out the invites.
      $batch = [
        'title' => $this
          ->t('Sending invites...'),
        'init_message' => $this
          ->t("Preparing to send invites..."),
        'operations' => [
          [
            '\\Drupal\\social_event_invite\\SocialEventInviteBulkHelper::bulkInviteUsersEmails',
            [
              $params['recipients'],
              $params['nid'],
            ],
          ],
        ],
        'finished' => '\\Drupal\\social_event_invite\\SocialEventInviteBulkHelper::bulkInviteUserEmailsFinished',
      ];
      batch_set($batch);
    } catch (\Exception $error) {
      $this->loggerFactory
        ->get('event_invite_form_values')
        ->alert(t('@err', [
        '@err' => $error,
      ]));
      $this->messenger
        ->addWarning(t('Unable to proceed, please try again.'));
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
EnrollInviteEmailForm::$configFactory protected property The Config factory. Overrides FormBase::$configFactory
EnrollInviteEmailForm::$entityStorage protected property The node storage for event enrollments.
EnrollInviteEmailForm::$tempStoreFactory private property Drupal\Core\TempStore\PrivateTempStoreFactory definition.
EnrollInviteEmailForm::$token protected property The token service.
EnrollInviteEmailForm::buildForm public function Form constructor. Overrides InviteEmailBaseForm::buildForm
EnrollInviteEmailForm::cancelForm public function Cancel form taking you back to an event.
EnrollInviteEmailForm::create public static function Instantiates a new instance of this class. Overrides InviteEmailBaseForm::create
EnrollInviteEmailForm::getFormId public function Returns a unique string identifying the form. Overrides InviteEmailBaseForm::getFormId
EnrollInviteEmailForm::submitForm public function Form submission handler. Overrides InviteEmailBaseForm::submitForm
EnrollInviteEmailForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
EnrollInviteEmailForm::__construct public function Constructs a new BulkGroupInvitation Form. Overrides InviteEmailBaseForm::__construct
FormBase::$requestStack protected property The request stack. 1
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 3
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.
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.
InviteEmailBaseForm::$entityTypeManager protected property The entity type manager.
InviteEmailBaseForm::$group protected property The current group from route.
InviteEmailBaseForm::$loggerFactory protected property The logger factory. Overrides LoggerChannelTrait::$loggerFactory
InviteEmailBaseForm::$routeMatch protected property The route match. Overrides FormBase::$routeMatch
InviteEmailBaseForm::extractEmailsFrom public function Custom function to extract email addresses from a string.
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. 27
MessengerTrait::messenger public function Gets the messenger. 27
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. 4
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.