You are here

class LoopThroughViewResultController in Business Rules 2.x

Same name and namespace in other branches
  1. 8 src/Controller/LoopThroughViewResultController.php \Drupal\business_rules\Controller\LoopThroughViewResultController

Class LoopThroughViewResultController.

@package Drupal\business_rules\Controller

Hierarchy

Expanded class hierarchy of LoopThroughViewResultController

File

src/Controller/LoopThroughViewResultController.php, line 23

Namespace

Drupal\business_rules\Controller
View source
class LoopThroughViewResultController extends ControllerBase {

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

  /**
   * The type of item to be configured action|condition.
   *
   * @var string
   */
  protected $item;

  /**
   * The Item config name: condition | action.
   *
   * @var string
   */
  protected $itemType;

  /**
   * All saved items from database.
   *
   * @var \Drupal\Core\Entity\EntityInterface[]|static[]
   */
  protected $items;

  /**
   * The item name for the configuration actions|conditions.
   *
   * @var string
   */
  protected $itemsName;

  /**
   * The item label.
   *
   * @var \Drupal\Core\StringTranslation\TranslatableMarkup
   */
  protected $label;

  /**
   * The item label in plural.
   *
   * @var \Drupal\Core\StringTranslation\TranslatableMarkup
   */
  protected $labelPlural;

  /**
   * The items currently saved on the Action.
   *
   * @var array
   */
  protected $savedItems = [];

  /**
   * {@inheritdoc}
   */
  public function __construct(ContainerInterface $container) {
    $this->entityTypeManager = $container
      ->get('entity_type.manager');
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container);
  }

  /**
   * Add item on Action.
   *
   * @param string $action_id
   *   The action id.
   * @param string $item_type
   *   The item type action|condition.
   * @param string $item_id
   *   The item id.
   *
   * @return \Zend\Diactoros\Response\RedirectResponse
   *   The RedirectResponse.
   */
  public function addItem($action_id, $item_type, $item_id) {
    $action = Action::load($action_id);
    $weight = $this
      ->getMaxItemWeight($action) + 1;
    $itemObj = new BusinessRulesItemObject($item_id, $item_type, $weight);
    $items = $action
      ->getSettings('items');
    $item_array = $itemObj
      ->toArray();
    $items[$itemObj
      ->getId()] = $item_array[$itemObj
      ->getId()];
    $action
      ->setSetting('items', $items);
    $action
      ->save();
    $url = new Url('entity.business_rules_action.edit_form', [
      'business_rules_action' => $action_id,
    ], [
      'fragment' => $item_id,
    ]);
    return new RedirectResponse($url
      ->toString());
  }

  /**
   * Get the bigger weight for the action items.
   *
   * @param \Drupal\business_rules\ActionInterface $action
   *   The action to get the bigger item weight.
   *
   * @return int
   *   The bigger weight for the action items.
   */
  public function getMaxItemWeight(ActionInterface $action) {
    $items = $action
      ->getSettings('items');
    $max = -100;
    if (is_array($items)) {
      foreach ($items as $item) {
        if ($max < $item['weight']) {
          $max = $item['weight'];
        }
      }
    }
    return $max;
  }

  /**
   * The items table.
   *
   * @param string $action_id
   *   The condition id.
   * @param string $item_type
   *   The item type action|condition.
   * @param string $method
   *   The method name: ajax|nojs.
   *
   * @return array|\Drupal\Core\Ajax\AjaxResponse
   *   Render array or AjaxResponse.
   */
  public function itemsTable($action_id, $item_type, $method) {
    $this
      ->init($item_type);

    /** @var \Drupal\business_rules\ActionInterface $action */
    $action = Action::load($action_id);
    $table['#title'] = $this
      ->t('Add @label_plural on %action', [
      '%action' => $action
        ->label(),
      '@label_plural' => $this->labelPlural,
    ]);
    $table['#attached']['library'][] = 'system/drupal.system.modules';
    $table['filters'] = [
      '#type' => 'container',
      '#attributes' => [
        'class' => [
          'table-filter',
          'js-show',
        ],
      ],
    ];
    $table['filters']['text'] = [
      '#type' => 'search',
      '#title' => $this
        ->t('Search'),
      '#size' => 30,
      '#placeholder' => $this
        ->t('Search for a @label key', [
        '@label' => $this->label,
      ]),
      '#attributes' => [
        'class' => [
          'table-filter-text',
        ],
        'data-table' => '.searchable-list',
        'autocomplete' => 'off',
        'title' => $this
          ->t('Enter a part of the @label key to filter by.', [
          '@label' => $this->label,
        ]),
      ],
    ];
    $header = [
      'label' => $this->label,
      'id' => $this
        ->t('Machine Name'),
      'type' => $this
        ->t('Type'),
      'description' => $this
        ->t('Description'),
      'operations' => $this
        ->t('Operations'),
      'filter' => [
        'data' => [
          '#markup' => 'filter',
        ],
        'style' => 'display: none',
      ],
    ];
    $rows = [];

    /** @var \Drupal\business_rules\ItemInterface $item */
    foreach ($this->items as $item) {
      if (!in_array($item
        ->id(), array_keys($this->savedItems)) && $item
        ->id() != $action
        ->id()) {
        $listBuilder = $this->entityTypeManager
          ->getListBuilder($item
          ->getEntityTypeId());
        $operations = $listBuilder
          ->buildOperations($item);
        $search_string = $item
          ->label() . ' ' . $item
          ->id() . ' ' . $item
          ->getTypeLabel() . ' ' . $item
          ->getDescription();
        $link = Link::createFromRoute($item
          ->label(), 'business_rules.loop_through_view_result.items.add', [
          'action_id' => $action_id,
          'item_id' => $item
            ->id(),
          'item_type' => $item_type,
        ]);
        $rows[$item
          ->id()] = [
          'label' => [
            'data' => $link,
          ],
          'id' => [
            'data' => [
              '#markup' => $item
                ->id(),
            ],
          ],
          'type' => [
            'data' => [
              '#markup' => $item
                ->getTypeLabel(),
            ],
          ],
          'description' => [
            'data' => [
              '#markup' => $item
                ->getDescription(),
            ],
          ],
          'operations' => [
            'data' => $operations,
          ],
          'filter' => [
            'data' => [
              [
                '#markup' => '<span class="table-filter-text-source">' . $search_string . '</span>',
              ],
            ],
            'style' => [
              'display: none',
            ],
          ],
        ];
      }
    }
    $table['business_rule_items'] = [
      '#type' => 'table',
      '#header' => $header,
      '#rows' => $rows,
      '#attributes' => [
        'class' => [
          'searchable-list',
        ],
      ],
    ];
    if ($method == 'ajax') {
      $table['#attached']['library'][] = 'core/drupal.dialog.ajax';
      $options = [
        'width' => '75%',
      ];
      $title = $this
        ->t('Add @item', [
        '@item' => $this->label,
      ]);
      $response = new AjaxResponse();
      $response
        ->addCommand(new OpenModalDialogCommand($title, $table, $options));
      return $response;
    }
    else {
      return $table;
    }
  }

  /**
   * Init properties.
   *
   * @param string $item_type
   *   The item type: action|condition.
   */
  public function init($item_type) {
    $this->item = $item_type;
    switch ($this->item) {
      case 'condition':
        $this->label = $this
          ->t('Condition');
        $this->labelPlural = $this
          ->t('Conditions');
        $this->items = Condition::loadMultiple();
        $this->itemsName = 'conditions';
        $this->itemType = 'condition';
        break;
      case 'action':
        $this->label = $this
          ->t('Action');
        $this->labelPlural = $this
          ->t('Actions');
        $this->items = Action::loadMultiple();
        $this->itemsName = 'actions';
        $this->itemType = 'action';
        break;
    }
  }

  /**
   * Remove item from condition.
   *
   * @param string $action_id
   *   The action id.
   * @param string $item_type
   *   The item type action|condition.
   * @param string $item_id
   *   The item id.
   * @param string $method
   *   The method name: ajax|nojs.
   *
   * @return \Drupal\Core\Ajax\AjaxResponse|\Zend\Diactoros\Response\RedirectResponse
   *   The AjaxResponse or the RedirectResponse.
   */
  public function removeItem($action_id, $item_type, $item_id, $method) {
    $action = Action::load($action_id);
    $items = $action
      ->getSettings('items');
    unset($items[$item_id]);
    $items = is_null($items) ? [] : $items;
    $action
      ->setSetting('items', $items);
    $action
      ->save();
    if ($method == 'ajax') {
      $response = new AjaxResponse();
      $response
        ->addCommand(new RemoveCommand('#' . $item_id));
      return $response;
    }
    else {
      $url = new Url('entity.business_rules_action.edit_form', [
        'business_rule_action' => $action_id,
      ]);
      $string_url = $url
        ->toString() . '#business_rule-add_buttons';
      return new RedirectResponse($string_url);
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ControllerBase::$configFactory protected property The configuration factory.
ControllerBase::$currentUser protected property The current user service. 1
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$formBuilder protected property The form builder. 2
ControllerBase::$keyValue protected property The key-value storage. 1
ControllerBase::$languageManager protected property The language manager. 1
ControllerBase::$moduleHandler protected property The module handler. 2
ControllerBase::$stateService protected property The state service.
ControllerBase::cache protected function Returns the requested cache bin.
ControllerBase::config protected function Retrieves a configuration object.
ControllerBase::container private function Returns the service container.
ControllerBase::currentUser protected function Returns the current user. 1
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityTypeManager protected function Retrieves the entity type manager.
ControllerBase::formBuilder protected function Returns the form builder service. 2
ControllerBase::keyValue protected function Returns a key/value storage collection. 1
ControllerBase::languageManager protected function Returns the language manager service. 1
ControllerBase::moduleHandler protected function Returns the module handler. 2
ControllerBase::redirect protected function Returns a redirect response object for the specified route.
ControllerBase::state protected function Returns the state storage 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.
LoopThroughViewResultController::$entityTypeManager protected property The EntityTypeManager. Overrides ControllerBase::$entityTypeManager
LoopThroughViewResultController::$item protected property The type of item to be configured action|condition.
LoopThroughViewResultController::$items protected property All saved items from database.
LoopThroughViewResultController::$itemsName protected property The item name for the configuration actions|conditions.
LoopThroughViewResultController::$itemType protected property The Item config name: condition | action.
LoopThroughViewResultController::$label protected property The item label.
LoopThroughViewResultController::$labelPlural protected property The item label in plural.
LoopThroughViewResultController::$savedItems protected property The items currently saved on the Action.
LoopThroughViewResultController::addItem public function Add item on Action.
LoopThroughViewResultController::create public static function Instantiates a new instance of this class. Overrides ControllerBase::create
LoopThroughViewResultController::getMaxItemWeight public function Get the bigger weight for the action items.
LoopThroughViewResultController::init public function Init properties.
LoopThroughViewResultController::itemsTable public function The items table.
LoopThroughViewResultController::removeItem public function Remove item from condition.
LoopThroughViewResultController::__construct public function
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.