You are here

class MessageForm in Courier 8

Same name and namespace in other branches
  1. 2.x courier_message_composer/src/Form/MessageForm.php \Drupal\courier_message_composer\Form\MessageForm

Create a message.

Hierarchy

Expanded class hierarchy of MessageForm

1 string reference to 'MessageForm'
courier_message_composer.routing.yml in courier_message_composer/courier_message_composer.routing.yml
courier_message_composer/courier_message_composer.routing.yml

File

courier_message_composer/src/Form/MessageForm.php, line 21

Namespace

Drupal\courier_message_composer\Form
View source
class MessageForm extends FormBase {
  use CourierTokenElementTrait;

  /**
   * The RNG event manager.
   *
   * @var \Drupal\rng\EventManagerInterface
   */
  protected $eventManager;

  /**
   * The identity channel manager.
   *
   * @var \Drupal\courier\Service\IdentityChannelManager
   */
  protected $identityChannelManager;

  /**
   * The courier manager.
   *
   * @var \Drupal\courier\Service\CourierManagerInterface
   */
  protected $courierManager;

  /**
   * Constructs a MessageForm object.
   *
   * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
   *   The entity manager.
   * @param \Drupal\courier\Service\IdentityChannelManagerInterface $identity_channel_manager
   *   The identity channel manager.
   * @param \Drupal\courier\Service\CourierManagerInterface $courier_manager
   *   The courier manager.
   */
  public function __construct(EntityManagerInterface $entity_manager, IdentityChannelManagerInterface $identity_channel_manager, CourierManagerInterface $courier_manager) {
    $this->entityManager = $entity_manager;
    $this->identityChannelManager = $identity_channel_manager;
    $this->courierManager = $courier_manager;
  }

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, ContentEntityTypeInterface $courier_channel = NULL) {
    $form['#title'] = $courier_channel
      ->getLabel();
    $t_args = [
      '@channel' => $courier_channel
        ->getLabel(),
    ];

    /** @var \Drupal\courier\ChannelInterface $message */
    $message = $this->entityManager
      ->getStorage($courier_channel
      ->id())
      ->create();
    $form_state
      ->set('message_entity', $message);

    // Identity.
    $form['identity_information'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Recipient'),
      '#description' => $this
        ->t('Select a recipient for the message.'),
      '#open' => TRUE,
    ];
    $form['identity_information']['identity'] = [
      '#type' => 'radios',
      '#options' => NULL,
      '#title' => $this
        ->t('Recipient'),
      '#required' => TRUE,
    ];
    $channels = $this->identityChannelManager
      ->getChannels();
    foreach ($channels[$courier_channel
      ->id()] as $entity_type_id) {
      $permission = 'courier_message_composer compose ' . $courier_channel
        ->id() . ' to ' . $entity_type_id;
      if (!$this
        ->currentUser()
        ->hasPermission($permission)) {
        continue;
      }
      $entity_type = $this->entityManager
        ->getDefinition($entity_type_id);
      $form['identity_information']['identity'][$entity_type_id] = [
        '#prefix' => '<div class="form-item container-inline">',
        '#suffix' => '</div>',
      ];
      $form['identity_information']['identity'][$entity_type_id]['radio'] = [
        '#type' => 'radio',
        '#title' => $entity_type
          ->getLabel(),
        '#return_value' => "{$entity_type_id}:*",
        '#parents' => [
          'identity',
        ],
        '#default_value' => $entity_type_id == 'user' ?: '',
        '#error_no_message' => TRUE,
      ];
      $form['identity_information']['identity'][$entity_type_id]['autocomplete'] = [
        '#type' => 'entity_autocomplete',
        '#title' => $entity_type
          ->getLabel(),
        '#title_display' => 'invisible',
        '#target_type' => $entity_type_id,
        '#tags' => FALSE,
        '#parents' => [
          'entity',
          $entity_type_id,
        ],
      ];
      if ($entity_type_id == 'user' && !$this
        ->currentUser()
        ->isAnonymous()) {
        $user = User::load($this
          ->currentUser()
          ->id());
        $form['identity_information']['identity'][$entity_type_id]['autocomplete']['#default_value'] = $user;
      }
    }

    // Form display.
    $display = entity_get_form_display($courier_channel
      ->id(), $courier_channel
      ->id(), 'default');
    $form_state
      ->set([
      'form_display',
    ], $display);
    $form['message'] = [
      '#tree' => TRUE,
    ];
    $display
      ->buildForm($message, $form['message'], $form_state);

    // Tokens.
    $form['tokens'] = [
      '#type' => 'container',
      '#title' => $this
        ->t('Tokens'),
      '#weight' => 51,
    ];
    $form['tokens']['list'] = $this
      ->courierTokenElement();
    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => t('Send @channel', $t_args),
      '#button_type' => 'primary',
    ];
    return $form;
  }

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

    /** @var \Drupal\courier\ChannelInterface $message */
    $message = $form_state
      ->get('message_entity');
    $form_state
      ->get([
      'form_display',
    ])
      ->validateFormValues($message, $form, $form_state);

    // Identity.
    if ($form_state
      ->getValue('identity')) {
      $identity = NULL;
      list($entity_type, $entity_id) = explode(':', $form_state
        ->getValue('identity'));
      if (!empty($entity_type)) {
        $references = $form_state
          ->getValue('entity');
        if (is_numeric($references[$entity_type])) {
          $entity_id = $references[$entity_type];
          $identity = $this->entityManager
            ->getStorage($entity_type)
            ->load($entity_id);
        }
      }
      if ($identity instanceof EntityInterface) {
        $form_state
          ->setValueForElement($form['identity_information']['identity'], $identity);
        $channel_types = $this->identityChannelManager
          ->getChannelsForIdentity($identity);
        if (!in_array($message
          ->getEntityTypeId(), $channel_types)) {
          $form_state
            ->setError($form['identity_information']['identity'], $this
            ->t('@identity cannot receive @channel.', [
            '@identity' => $identity
              ->label(),
            '@channel' => $message
              ->getEntityType()
              ->getLabel(),
          ]));
        }
      }
      else {
        $form_state
          ->setError($form['identity_information']['identity'], $this
          ->t('Invalid identity.'));
      }
    }
  }

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

    /** @var \Drupal\courier\ChannelInterface $message */
    $message = $form_state
      ->get('message_entity');
    $form_state
      ->get([
      'form_display',
    ])
      ->extractFormValues($message, $form, $form_state);
    $template_collection = TemplateCollection::create()
      ->setTemplate($message);
    $identity = $form_state
      ->getValue('identity');
    $mqi = $this->courierManager
      ->sendMessage($template_collection, $identity);
    if ($mqi instanceof MessageQueueItemInterface) {
      drupal_set_message(t('Message queued for delivery.'));
    }
    else {
      drupal_set_message(t('Failed to send message'), 'error');
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
CourierTokenElementTrait::courierTokenElement public function Render a token element.
CourierTokenElementTrait::templateCollectionTokenElement public function Render a token element for a template collection.
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.
MessageForm::$courierManager protected property The courier manager.
MessageForm::$eventManager protected property The RNG event manager.
MessageForm::$identityChannelManager protected property The identity channel manager.
MessageForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
MessageForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
MessageForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
MessageForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
MessageForm::validateForm public function @inheritDoc Overrides FormBase::validateForm
MessageForm::__construct public function Constructs a MessageForm 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.