You are here

abstract class WebformBulkFormBase in Webform 8.5

Same name and namespace in other branches
  1. 6.x src/Form/WebformBulkFormBase.php \Drupal\webform\Form\WebformBulkFormBase

Provides the webform bulk form base.

Hierarchy

Expanded class hierarchy of WebformBulkFormBase

See also

\Drupal\views\Plugin\views\field\BulkForm

File

src/Form/WebformBulkFormBase.php, line 14

Namespace

Drupal\webform\Form
View source
abstract class WebformBulkFormBase extends FormBase {

  /**
   * The tempstore factory.
   *
   * @var \Drupal\Core\TempStore\PrivateTempStoreFactory
   */
  protected $tempStoreFactory;

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

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

  /**
   * The entity type.
   *
   * @var string
   */
  protected $entityTypeId;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    $instance = parent::create($container);
    $instance->tempStoreFactory = $container
      ->get('tempstore.private');
    $instance->currentUser = $container
      ->get('current_user');
    $instance->entityTypeManager = $container
      ->get('entity_type.manager');
    return $instance;
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return $this->entityTypeId . '_bulk_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $table = []) {
    $form['#attributes']['class'][] = 'webform-bulk-form';
    $options = $this
      ->getBulkOptions();
    if (empty($options)) {
      return [
        'items' => $table,
      ];
    }

    // Operations.
    $form['operations'] = [
      '#prefix' => '<div class="container-inline">',
      '#suffix' => '</div>',
    ];
    $form['operations']['action'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Action'),
      '#title_display' => 'invisible',
      '#options' => $this
        ->getBulkOptions(),
      '#empty_option' => $this
        ->t('- Select operation -'),
    ];
    $form['operations']['apply_above'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Apply to selected items'),
    ];

    // Table select.
    $form['items'] = $table;
    $form['items']['#type'] = 'tableselect';
    $form['items']['#options'] = $table['#rows'];
    $form['apply_below'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Apply to selected items'),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $action = $form_state
      ->getValue('action');
    if (empty($action)) {
      $form_state
        ->setErrorByName(NULL, $this
        ->t('No operation selected.'));
    }
    $entity_ids = array_filter($form_state
      ->getValue('items'));
    if (empty($entity_ids)) {
      $form_state
        ->setErrorByName(NULL, $this
        ->t('No items selected.'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $actions = $this
      ->getActions();

    // If the action does exist, skip it and assume that someone has altered
    // the form and added a custom action.
    if (!isset($actions[$form_state
      ->getValue('action')])) {
      return;
    }
    $action = $actions[$form_state
      ->getValue('action')];
    $entity_ids = array_filter($form_state
      ->getValue('items'));
    $entities = $this->entityTypeManager
      ->getStorage($this->entityTypeId)
      ->loadMultiple($entity_ids);
    foreach ($entities as $key => $entity) {

      // Skip execution if the user did not have access.
      if (!$action
        ->getPlugin()
        ->access($entity, $this
        ->currentUser())) {
        $this
          ->messenger()
          ->addError($this
          ->t('No access to execute %action on the @entity_type_label %entity_label.', [
          '%action' => $action
            ->label(),
          '@entity_type_label' => $entity
            ->getEntityType()
            ->getLabel(),
          '%entity_label' => $entity
            ->label(),
        ]));
        unset($entities[$key]);
        continue;
      }
    }
    $count = count($entities);

    // If there were entities selected but the action isn't allowed on any of
    // them, we don't need to do anything further.
    if (!$count) {
      return;
    }
    $action
      ->execute($entities);
    $operation_definition = $action
      ->getPluginDefinition();
    if (!empty($operation_definition['confirm_form_route_name'])) {
      $options = [
        'query' => $this
          ->getDestinationArray(),
      ];
      $form_state
        ->setRedirect($operation_definition['confirm_form_route_name'], [], $options);
    }
    else {

      // Don't display the message unless there are some elements affected and
      // there is no confirmation form.
      $this
        ->messenger()
        ->addStatus($this
        ->formatPlural($count, '%action was applied to @count item.', '%action was applied to @count items.', [
        '%action' => $action
          ->label(),
      ]));
    }
  }

  /**
   * Get the entity type's actions
   *
   * @return \Drupal\system\ActionConfigEntityInterface[]
   *   An associative array of actions.
   */
  protected function getActions() {
    if (!isset($this->actions)) {
      $this->actions = [];
      $action_ids = $this
        ->configFactory()
        ->get('webform.settings')
        ->get('settings.' . $this->entityTypeId . '_bulk_form_actions') ?: [];
      if ($action_ids) {

        /** @var \Drupal\system\ActionConfigEntityInterface[] $actions */
        $actions = $this->entityTypeManager
          ->getStorage('action')
          ->loadMultiple($action_ids);
        $this->actions = array_filter($actions, function ($action) {
          return $action
            ->getType() === $this->entityTypeId;
        });
      }
    }
    return $this->actions;
  }

  /**
   * Returns the available operations for this form.
   *
   * @return array
   *   An associative array of operations, suitable for a select element.
   */
  protected function getBulkOptions() {
    $actions = $this
      ->getActions();
    $options = [];
    foreach ($actions as $id => $action) {
      $options[$id] = $action
        ->label();
    }
    return $options;
  }

}

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.
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.
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.
WebformBulkFormBase::$currentUser protected property The current user.
WebformBulkFormBase::$entityTypeId protected property The entity type. 2
WebformBulkFormBase::$entityTypeManager protected property The entity manager.
WebformBulkFormBase::$tempStoreFactory protected property The tempstore factory.
WebformBulkFormBase::buildForm public function Form constructor. Overrides FormInterface::buildForm 1
WebformBulkFormBase::create public static function Instantiates a new instance of this class. Overrides FormBase::create
WebformBulkFormBase::getActions protected function Get the entity type's actions 2
WebformBulkFormBase::getBulkOptions protected function Returns the available operations for this form.
WebformBulkFormBase::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
WebformBulkFormBase::submitForm public function Form submission handler. Overrides FormInterface::submitForm
WebformBulkFormBase::validateForm public function Form validation handler. Overrides FormBase::validateForm