You are here

class BlockListingForm in Layout Builder Browser 8

Builds a listing of block entities.

Hierarchy

Expanded class hierarchy of BlockListingForm

1 string reference to 'BlockListingForm'
layout_builder_browser.routing.yml in ./layout_builder_browser.routing.yml
layout_builder_browser.routing.yml

File

src/Form/BlockListingForm.php, line 17

Namespace

Drupal\layout_builder_browser\Form
View source
class BlockListingForm extends FormBase {

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

  /**
   * Block manager.
   *
   * @var \Drupal\Core\Block\BlockManagerInterface
   */
  protected $blockManager;

  /**
   * Constructs an layout_builder_browserForm object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   *   The entityTypeManager.
   * @param \Drupal\Core\Block\BlockManagerInterface $blockManager
   *   The blockManager.
   */
  public function __construct(EntityTypeManagerInterface $entityTypeManager, BlockManagerInterface $blockManager) {
    $this->entityTypeManager = $entityTypeManager;
    $this->blockManager = $blockManager;
  }

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

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

  /**
   * {@inheritdoc}
   */
  public function buildHeader() {
    $header = [
      'title' => [
        'data' => $this
          ->t('Title'),
      ],
      'block_provider' => $this
        ->t('Block provider'),
      'category' => $this
        ->t('Category'),
      'weight' => $this
        ->t('Weight'),
      'operations' => $this
        ->t('Operations'),
    ];
    return $header;
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $categories = $this
      ->loadCategories();
    $form['categories'] = [
      '#type' => 'table',
      '#header' => $this
        ->buildHeader(),
      '#empty' => $this
        ->t('No block categories defined.'),
      '#attributes' => [
        'id' => 'blocks',
      ],
    ];
    foreach ($categories as $category) {
      $category_id = $category["category"]->id;
      $form['categories'][$category_id] = $this
        ->buildBlockCategoryRow($category["category"]);
      $form['categories']['#tabledrag'][] = [
        'action' => 'order',
        'relationship' => 'sibling',
        'group' => 'block-weight',
        'subgroup' => 'block-weight-' . $category_id,
      ];
      $form['categories']['region-' . $category_id . '-message'] = [
        '#attributes' => [
          'class' => [
            'region-message',
            'region-' . $category_id . '-message',
            empty($category['blocks']) ? 'region-empty' : 'region-populated',
          ],
        ],
      ];
      $form['categories']['region-' . $category_id . '-message']['message'] = [
        '#markup' => '<em>' . $this
          ->t('No blocks in this category') . '</em>',
        '#wrapper_attributes' => [
          'colspan' => 5,
        ],
      ];
      foreach ($category['blocks'] as $block) {
        $block['category'] = $category_id;
        $form['categories'][$block['id']] = $this
          ->buildBlockRow($block);
      }
    }
    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Save'),
      '#button_type' => 'primary',
    ];
    $form['#attached']['library'][] = 'layout_builder_browser/admin';
    $form['#attached']['library'][] = 'block/drupal.block';
    $form['#attached']['library'][] = 'block/drupal.block.admin';
    return $form;
  }

  /**
   * Builds one block row.
   *
   * @var array $block
   *   The block.
   *
   * @return array
   *   Row with information about block.
   */
  private function buildBlockRow($block) {
    $row = [];
    $row['title'] = [
      '#type' => 'markup',
      '#markup' => '<div class="block-title">' . $block['label'] . '</div>',
    ];
    $row['block_provider'] = [
      '#type' => 'markup',
      '#markup' => $block["block_provider"],
    ];
    $block_categories = $this->entityTypeManager
      ->getStorage('layout_builder_browser_blockcat')
      ->loadMultiple();
    uasort($block_categories, [
      'Drupal\\Core\\Config\\Entity\\ConfigEntityBase',
      'sort',
    ]);
    $categories_options = [];
    foreach ($block_categories as $block_category) {
      $categories_options[$block_category
        ->id()] = $block_category
        ->label();
    }
    $row['category'] = [
      '#type' => 'select',
      '#options' => $categories_options,
      '#default_value' => $block['category'],
      '#attributes' => [
        'class' => [
          'block-region-select',
          'block-region-' . $block['category'],
        ],
      ],
    ];
    $row['#attributes'] = [
      'title' => $this
        ->t('ID: @name', [
        '@name' => $block['id'],
      ]),
      'class' => [
        'block-wrapper',
        'draggable',
      ],
    ];
    $row['weight'] = [
      '#type' => 'weight',
      '#default_value' => $block['weight'],
      '#delta' => 100,
      '#title' => $this
        ->t('Weight for @block block', [
        '@block' => $block['label'],
      ]),
      '#title_display' => 'invisible',
      '#attributes' => [
        'class' => [
          'block-weight',
          'block-weight-' . $block['category'],
        ],
      ],
    ];
    $row['operations'] = [
      '#type' => 'link',
      '#title' => $this
        ->t('edit'),
      '#url' => Url::fromRoute('entity.layout_builder_browser_block.edit_form', [
        'layout_builder_browser_block' => $block['id'],
      ]),
      '#attributes' => [
        'class' => [
          'use-ajax',
          'button',
          'button--small',
        ],
        'data-dialog-type' => 'modal',
        'data-dialog-options' => Json::encode([
          'width' => 700,
        ]),
      ],
    ];
    return $row;
  }

  /**
   * Builds an array of block categorie for display in the overview.
   */
  private function buildBlockCategoryRow($block_category) {
    return [
      'title' => [
        '#theme_wrappers' => [
          'container' => [
            '#attributes' => [
              'class' => [
                'block-category-title',
                'region-title__action',
              ],
            ],
          ],
        ],
        '#type' => 'link',
        '#prefix' => Html::escape($block_category
          ->label()),
        '#title' => $this
          ->t('Place block <span class="visually-hidden">in %category</span>', [
          '%category' => Html::escape($block_category
            ->label()),
        ]),
        '#url' => Url::fromRoute('entity.layout_builder_browser_block.add_form', [], [
          'query' => [
            'blockcat' => $block_category
              ->id(),
          ],
        ]),
        '#attributes' => [
          'class' => [
            'use-ajax',
            'button',
            'button--small',
          ],
          'data-dialog-type' => 'modal',
          'data-dialog-options' => Json::encode([
            'width' => 700,
          ]),
        ],
        '#wrapper_attributes' => [
          'colspan' => 5,
        ],
      ],
      '#attributes' => [
        'class' => [
          'region-title',
          'region-title-' . $block_category
            ->id(),
        ],
      ],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $blocks = $form_state
      ->getValue('categories');
    $lb_block_storage = $this->entityTypeManager
      ->getStorage('layout_builder_browser_block');
    foreach ($blocks as $id => $block) {
      $lb_block = $lb_block_storage
        ->load($id);
      $lb_block->weight = $block['weight'];
      $lb_block->category = $block['category'];
      $lb_block
        ->save();
    }
    $this
      ->messenger()
      ->addMessage($this
      ->t('The blocks have been updated.'));
  }

  /**
   * Loads block categories and blocks, grouped by block categories.
   *
   * @return \Drupal\Core\Config\Entity\ConfigEntityInterface[][]
   *   An associative array with two keys:
   *   - categories: All available block categories, each followed by all blocks
   *     attached to it.
   *   - hidden_blocks: All blocks that aren't attached to any block categories.
   */
  public function loadCategories() {
    $block_categories = $this->entityTypeManager
      ->getStorage('layout_builder_browser_blockcat')
      ->loadMultiple();
    uasort($block_categories, [
      'Drupal\\Core\\Config\\Entity\\ConfigEntityBase',
      'sort',
    ]);
    $block_categories_group = [];
    foreach ($block_categories as $key => $block_category) {
      $block_categories_group[$key]['category'] = $block_category;
      $block_categories_group[$key]['blocks'] = [];
      $blocks = \Drupal::entityTypeManager()
        ->getStorage('layout_builder_browser_block')
        ->loadByProperties([
        'category' => $key,
      ]);
      uasort($blocks, [
        'Drupal\\Core\\Config\\Entity\\ConfigEntityBase',
        'sort',
      ]);
      foreach ($blocks as $block) {
        $blockdefinition = \Drupal::service('plugin.manager.block')
          ->getDefinition($block->block_id);
        $item = [];
        $item['id'] = $block->id;
        $item['weight'] = $block->weight;
        $item['label'] = $block
          ->label();
        $item['block_provider'] = $blockdefinition['admin_label'] . " - " . $blockdefinition["category"];
        $item['block_id'] = $block->block_id;
        $block_categories_group[$key]['blocks'][] = $item;
      }
    }
    return $block_categories_group;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
BlockListingForm::$blockManager protected property Block manager.
BlockListingForm::$entityTypeManager protected property Entity type manager.
BlockListingForm::buildBlockCategoryRow private function Builds an array of block categorie for display in the overview.
BlockListingForm::buildBlockRow private function Builds one block row.
BlockListingForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
BlockListingForm::buildHeader public function
BlockListingForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
BlockListingForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
BlockListingForm::loadCategories public function Loads block categories and blocks, grouped by block categories.
BlockListingForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
BlockListingForm::__construct public function Constructs an layout_builder_browserForm object.
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.
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.