You are here

class MessageListForm in RNG - Events and Registrations 8

Same name and namespace in other branches
  1. 8.2 src/Form/MessageListForm.php \Drupal\rng\Form\MessageListForm
  2. 3.x src/Form/MessageListForm.php \Drupal\rng\Form\MessageListForm

Creates message list form.

Hierarchy

Expanded class hierarchy of MessageListForm

File

src/Form/MessageListForm.php, line 18

Namespace

Drupal\rng\Form
View source
class MessageListForm extends FormBase {

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

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

  /**
   * Constructs a new message list form.
   *
   * @param \Drupal\Core\Routing\RedirectDestinationInterface $redirect_destination
   *   The redirect destination service.
   * @param \Drupal\rng\EventManagerInterface $event_manager
   *   The RNG event manager.
   */
  public function __construct(RedirectDestinationInterface $redirect_destination, EventManagerInterface $event_manager) {
    $this->redirectDestination = $redirect_destination;
    $this->eventManager = $event_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('redirect.destination'), $container
      ->get('rng.event_manager'));
  }

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

  /**
   * Get a list of rules.
   *
   * @param \Drupal\Core\Entity\EntityInterface $event
   *   An event entity.
   *
   * @return \Drupal\rng\RuleInterface[]
   *   An array of rng_rule entities keyed by rule ID.
   */
  protected function getCommunicationRules(EntityInterface $event) {

    // List of communication related action plugin ids.
    $communication_actions = [
      'rng_courier_message',
    ];
    $rules = [];
    $rules_all = $this->eventManager
      ->getMeta($event)
      ->getRules(NULL, FALSE, NULL);
    foreach ($rules_all as $rid => $rule) {
      foreach ($rule
        ->getActions() as $action) {
        $action_id = $action
          ->getPluginId();
        if (in_array($action_id, $communication_actions)) {
          $rules[$rid] = $rule;
          continue 2;
        }
      }
    }
    return $rules;
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, EntityInterface $rng_event = NULL) {
    $form['#rng_event'] = $rng_event;

    // @todo: move trigger definitions to a discovery service.
    $rng_triggers = [
      'entity:registration:new' => $this
        ->t('Registration creation'),
      'entity:registration:update' => $this
        ->t('Registration updated'),
      'rng:custom:date' => $this
        ->t('Send on a date'),
    ];

    // Actions.
    $form['actions'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Operations'),
      '#attributes' => [
        'class' => [
          'container-inline',
        ],
      ],
      '#open' => TRUE,
    ];
    $form['actions']['operation'] = [
      '#title' => $this
        ->t('With selection'),
      '#type' => 'select',
      '#options' => [
        'enable' => $this
          ->t('Enable messages'),
        'disable' => $this
          ->t('Disable messages'),
        'delete' => $this
          ->t('Delete messages'),
      ],
      '#empty_option' => $this
        ->t(' - Select - '),
      '#button_type' => 'primary',
    ];
    $form['actions']['apply'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Apply'),
      '#button_type' => 'primary',
    ];

    // List items.
    $form['list'] = [
      '#type' => 'courier_template_collection_list',
      '#checkboxes' => TRUE,
      '#items' => [],
    ];
    foreach ($this
      ->getCommunicationRules($form['#rng_event']) as $rid => $rule) {
      $trigger_id = $rule
        ->getTriggerID();
      if ($template_collection = $this
        ->getTemplateCollectionForRule($rule)) {

        // Add description for date conditions.
        $description = NULL;
        if ($component = $this
          ->getDateCondition($rule)) {
          $condition = $component
            ->createInstance();
          $description = $condition
            ->getDateFormatted();
        }
        $form['list']['#items'][$rule
          ->id()] = [
          '#title' => $this
            ->t('@label (@status)', [
            '@label' => isset($rng_triggers[$trigger_id]) ? $rng_triggers[$trigger_id] : $trigger_id,
            '@status' => $rule
              ->isActive() ? $this
              ->t('active') : $this
              ->t('disabled'),
          ]),
          '#description' => $description,
          '#template_collection' => $template_collection,
          '#operations' => $this
            ->getOperations($rule),
        ];
      }
    }
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $message = NULL;
    $operation = $form_state
      ->getValue([
      'operation',
    ]);

    // Checkbox is checked, keyed by rule ID.
    $checkbox = $form_state
      ->getValue([
      'list',
      'checkboxes',
    ]);

    // A list of checked rules.
    $rules = [];
    foreach ($this
      ->getCommunicationRules($form['#rng_event']) as $rule) {

      // Checkbox is checked.
      if ($checkbox[$rule
        ->id()]) {
        $rules[] = $rule;
      }
    }

    /** @var RuleInterface $rule */
    foreach ($rules as $rule) {
      if (in_array($operation, [
        'enable',
        'disable',
      ])) {
        $operation_active = $operation == 'enable';
        if ($rule
          ->isActive() != $operation_active) {
          $rule
            ->setIsActive($operation_active)
            ->save();
        }
        $message = $operation == 'enable' ? $this
          ->t('Messages enabled.') : $this
          ->t('Messages disabled.');
      }
      elseif ($operation == 'delete') {
        $rule
          ->delete();
        $message = $this
          ->t('Messages deleted');
      }
    }
    drupal_set_message($message ? $message : $this
      ->t('No action performed.'));
  }

  /**
   * Gets the template collection from an action on the rule.
   *
   * @param \Drupal\rng\RuleInterface $rule
   *   The rule.
   *
   * @return \Drupal\courier\TemplateCollectionInterface|NULL
   *   A template collection entity, or NULL if no template collection is
   *   associated.
   */
  protected function getTemplateCollectionForRule(RuleInterface $rule) {
    foreach ($rule
      ->getActions() as $action) {
      $conf = $action
        ->getConfiguration();
      $id = $conf['template_collection'];
      if ($id && ($template_collection = TemplateCollection::load($id))) {
        return $template_collection;
      }
    }
    return NULL;
  }

  /**
   * Gets the condition containing a date instance.
   *
   * @param \Drupal\rng\RuleInterface $rule
   *   The rule.
   *
   * @return \Drupal\rng\RuleComponentInterface|NULL
   *   A rule component entity, or NULL if no date condition is associated.
   */
  protected function getDateCondition(RuleInterface $rule) {
    foreach ($rule
      ->getConditions() as $component) {
      $condition = $component
        ->createInstance();
      if ($condition instanceof CurrentTime) {
        return $component;
      }
    }
    return NULL;
  }

  /**
   * Gets operations for a rule.
   *
   * @param \Drupal\rng\RuleInterface $rule
   *   The rule.
   *
   * @return array
   *   An array of links suitable for an 'operations' element.
   */
  protected function getOperations(RuleInterface $rule) {
    $links = [];
    $destination = $this->redirectDestination
      ->getAsArray();
    if ($component = $this
      ->getDateCondition($rule)) {
      if ($component
        ->access('edit')) {
        $links['edit-date'] = [
          'title' => $this
            ->t('Edit date'),
          'url' => $component
            ->urlInfo('edit-form'),
          'query' => $destination,
        ];
      }
    }
    if ($rule
      ->access('delete')) {
      $links['delete'] = [
        'title' => $this
          ->t('Delete'),
        'url' => $rule
          ->urlInfo('delete-form'),
        'query' => $destination,
      ];
    }
    return $links;
  }

}

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.
MessageListForm::$eventManager protected property The RNG event manager.
MessageListForm::$redirectDestination protected property The redirect destination service. Overrides RedirectDestinationTrait::$redirectDestination
MessageListForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
MessageListForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
MessageListForm::getCommunicationRules protected function Get a list of rules.
MessageListForm::getDateCondition protected function Gets the condition containing a date instance.
MessageListForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
MessageListForm::getOperations protected function Gets operations for a rule.
MessageListForm::getTemplateCollectionForRule protected function Gets the template collection from an action on the rule.
MessageListForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
MessageListForm::__construct public function Constructs a new message list form.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
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.