social_event_invite_flow-1.0.0-beta3/src/Form/ConvertEnrollRequestForm.php

src/Form/ConvertEnrollRequestForm.php
<?php

namespace Drupal\social_event_invite_flow\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\node\NodeInterface;
use Drupal\user\UserInterface;
use Drupal\node\Node;
use Drupal\social_event\Entity\EventEnrollment;
use Drupal\social_event\EventEnrollmentInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\RequestStack;
use Drupal\social_event_invite_flow\Service\EventInviteFlowService;
use Drupal\social_event_invite_flow\EventInviteSettingsInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Mail\MailManagerInterface;
use Drupal\Component\Utility\EmailValidatorInterface;
use Drupal\Core\Utility\Token;
use Drupal\Component\Render\PlainTextOutput;
use Drupal\Core\Render\Markup;
use Drupal\Core\Url;
use Drupal\Core\Routing\RedirectDestinationInterface;


/**
 * Provides a Social event invite flow form.
 */
class ConvertEnrollRequestForm extends FormBase {

  /**
   * The request stack.
   *
   * @var \Symfony\Component\HttpFoundation\RequestStack
   */
  protected $requestStack;

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * The Event Invite Flow Service
   *
   * @var \Drupal\social_event_invite_flow\Service\EventInviteFlowService
   */
  protected $eventInviteFlowService;  

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

  /**
   * The redirect destination helper.
   *
   * @var \Drupal\Core\Routing\RedirectDestinationInterface
   */
  protected $redirectDestination;  

  /**
   * UpdateEnrollRequestController constructor.
   *
   * @param \Symfony\Component\HttpFoundation\RequestStack $requestStack
   *   The request stack.
   * @param \Drupal\Core\Session\AccountProxyInterface $currentUser
   *   The current user.
   */
  public function __construct(
    RequestStack $requestStack, 
    AccountProxyInterface $currentUser, 
    EventInviteFlowService $event_invite_flow_service,
    EntityTypeManagerInterface $entity_type_manager,
    RedirectDestinationInterface $redirect_destination,
  ) {
    $this->requestStack = $requestStack;
    $this->currentUser = $currentUser;
    $this->eventInviteFlowService = $event_invite_flow_service;    
    $this->entityTypeManager = $entity_type_manager;
    $this->redirectDestination = $redirect_destination;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('request_stack'),
      $container->get('current_user'),
      $container->get('social_event_invite_flow.invite_flow_service'),
      $container->get('entity_type.manager'),
      $container->get('redirect.destination')
    );
  }


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

  /**
   * {@inheritdoc}
   */
  private function getCancelUrl() {
    return Url::fromUserInput($this->redirectDestination->get());
  }  

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

    $form['convert_request_message'] = [
      '#type' => 'details',
      '#title' => t('Confirm the request'),
      '#open' => TRUE,
      '#prefix' => '<div class="card"><div class="card__block">',
      '#suffix' => '</div></div>',      
    ];

    $form['subject'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Subject'),
      '#group' => 'convert_request_message',
      '#maxlength' => 255,
      '#required' => TRUE,
    ];  
    
    $form['message'] = [
      '#type' => 'textarea',
      '#title' => $this->t('Message'),
      '#group' => 'convert_request_message', 
      '#required' => TRUE,           
    ];

    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['send'] = [
      '#type' => 'submit',
      '#name' => 'send',
      '#value' => $this->t('Send'),
      '#button_type' => 'primary',
    ];

    $form['actions']['cancel'] = [
      '#type' => 'link',
      '#title' => $this->t('Cancel'),
      '#attributes' => [
        'class' => [
          'button',
          'button--flat',
          'btn',
          'btn-flat',
          'waves-effect',
          'waves-btn',
        ],
      ],
      '#url' => $this->getCancelUrl(),
    ];

    return $form;

  }

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

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


    // Get the node from the request
    $node = $this->getRequest()->get('node');
  
    // Get the event_enrollment from the request.
    $event_enrollment = $this->getRequest()->get('event_enrollment');


    // Define user mail
    $request_user_mail = NULL;

    // Get the subject
    $subject = $form_state->getValue('subject');

    // Get the message
    $message = $form_state->getValue('message');


    // Read the user mail form the field_account
    $user_id = $event_enrollment->getAccount();

    // Load user object
    $user = $this->entityTypeManager->getStorage('user')->load($user_id);   
    
    if ($user instanceof UserInterface) {
      $request_user_mail = $user->getEmail();
    }    

    $message = [
      'subject' => $subject,
      'message' => $message
    ];

    try {

      // Sending Email
      $this->eventInviteFlowService->convertEnrollRequestFormMessage(
        $user,
        $node,
        $request_user_mail,
        $message
      );

      // First, lets delete all messages to keep the messages clean.
      $this->messenger()->deleteAll();

      // First we have to remove the field_request_or_invite_status
      $event_enrollment->field_request_or_invite_status->value = '';
      // Now we need to properly enroll the user.
      $event_enrollment->field_enrollment_status->value = 1;
      // Inform the manger about it
      $this->messenger()->addStatus(t('The event enrollment request has been converted.'));

      // In order for the notifications to be sent correctly we're updating the
      // owner here. The account is still linked to the actual enrollee.
      // The owner is always used as the actor.
      // @see activity_creator_message_insert().
      $event_enrollment->setOwnerId($this->currentUser->id());

      // And finally save (update) this updated $event_enrollment.
      // @todo maybe think of deleting approved/declined records from the db?
      $event_enrollment->save();

      // Get the service
      $event_invite_flow_service = $this->eventInviteFlowService;    

      // Now make sure we set the event settings to shareable link
      $event_invite_setting = $event_invite_flow_service->getEventInviteSettings($node->id());

      if ($event_invite_setting) {
        // Set the invite setting to enable shareable link
        $event_invite_setting->setEnableShareableLink(TRUE);
        $event_invite_setting->save();

        // Get Account from user id.
        $user = $event_invite_flow_service->getAccountFromUserId($event_enrollment->getAccount());

        // Send invite email to user.
        $event_invite_flow_service->sendInviteEmails(
          EventInviteSettingsInterface::InviteModeExistingAccountsDefaultEnrollment,
          $user,
          $node->id(),
          $event_enrollment
        );

      } 


    }
    catch(\Exception $e) {
      \Drupal::logger('social_event_invite_flow')->warning($e->getMessage());
    }
    
    $this->messenger()->addStatus($this->t('The message has been sent.'));

    $form_state->setRedirectUrl($this->getCancelUrl());


  }


}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc