BlockListBuilder.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. <?php
  2. namespace Drupal\block;
  3. use Drupal\Component\Utility\Html;
  4. use Drupal\Component\Serialization\Json;
  5. use Drupal\Core\Config\Entity\ConfigEntityListBuilder;
  6. use Drupal\Core\Entity\EntityInterface;
  7. use Drupal\Core\Entity\EntityStorageInterface;
  8. use Drupal\Core\Entity\EntityTypeInterface;
  9. use Drupal\Core\Form\FormBuilderInterface;
  10. use Drupal\Core\Form\FormInterface;
  11. use Drupal\Core\Form\FormStateInterface;
  12. use Drupal\Core\Messenger\MessengerInterface;
  13. use Drupal\Core\Theme\ThemeManagerInterface;
  14. use Drupal\Core\Url;
  15. use Symfony\Component\DependencyInjection\ContainerInterface;
  16. use Symfony\Component\HttpFoundation\Request;
  17. /**
  18. * Defines a class to build a listing of block entities.
  19. *
  20. * @see \Drupal\block\Entity\Block
  21. */
  22. class BlockListBuilder extends ConfigEntityListBuilder implements FormInterface {
  23. /**
  24. * The theme containing the blocks.
  25. *
  26. * @var string
  27. */
  28. protected $theme;
  29. /**
  30. * The current request.
  31. *
  32. * @var \Symfony\Component\HttpFoundation\Request
  33. */
  34. protected $request;
  35. /**
  36. * The theme manager.
  37. *
  38. * @var \Drupal\Core\Theme\ThemeManagerInterface
  39. */
  40. protected $themeManager;
  41. /**
  42. * The form builder.
  43. *
  44. * @var \Drupal\Core\Form\FormBuilderInterface
  45. */
  46. protected $formBuilder;
  47. /**
  48. * {@inheritdoc}
  49. */
  50. protected $limit = FALSE;
  51. /**
  52. * The messenger.
  53. *
  54. * @var \Drupal\Core\Messenger\MessengerInterface
  55. */
  56. protected $messenger;
  57. /**
  58. * Constructs a new BlockListBuilder object.
  59. *
  60. * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
  61. * The entity type definition.
  62. * @param \Drupal\Core\Entity\EntityStorageInterface $storage
  63. * The entity storage class.
  64. * @param \Drupal\Core\Theme\ThemeManagerInterface $theme_manager
  65. * The theme manager.
  66. * @param \Drupal\Core\Form\FormBuilderInterface $form_builder
  67. * The form builder.
  68. */
  69. public function __construct(EntityTypeInterface $entity_type, EntityStorageInterface $storage, ThemeManagerInterface $theme_manager, FormBuilderInterface $form_builder, MessengerInterface $messenger) {
  70. parent::__construct($entity_type, $storage);
  71. $this->themeManager = $theme_manager;
  72. $this->formBuilder = $form_builder;
  73. $this->messenger = $messenger;
  74. }
  75. /**
  76. * {@inheritdoc}
  77. */
  78. public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
  79. return new static(
  80. $entity_type,
  81. $container->get('entity.manager')->getStorage($entity_type->id()),
  82. $container->get('theme.manager'),
  83. $container->get('form_builder'),
  84. $container->get('messenger')
  85. );
  86. }
  87. /**
  88. * {@inheritdoc}
  89. *
  90. * @param string|null $theme
  91. * (optional) The theme to display the blocks for. If NULL, the current
  92. * theme will be used.
  93. * @param \Symfony\Component\HttpFoundation\Request $request
  94. * The current request.
  95. *
  96. * @return array
  97. * The block list as a renderable array.
  98. */
  99. public function render($theme = NULL, Request $request = NULL) {
  100. $this->request = $request;
  101. $this->theme = $theme;
  102. return $this->formBuilder->getForm($this);
  103. }
  104. /**
  105. * {@inheritdoc}
  106. */
  107. public function getFormId() {
  108. return 'block_admin_display_form';
  109. }
  110. /**
  111. * {@inheritdoc}
  112. */
  113. public function buildForm(array $form, FormStateInterface $form_state) {
  114. $form['#attached']['library'][] = 'core/drupal.tableheader';
  115. $form['#attached']['library'][] = 'block/drupal.block';
  116. $form['#attached']['library'][] = 'block/drupal.block.admin';
  117. $form['#attributes']['class'][] = 'clearfix';
  118. // Build the form tree.
  119. $form['blocks'] = $this->buildBlocksForm();
  120. $form['actions'] = [
  121. '#tree' => FALSE,
  122. '#type' => 'actions',
  123. ];
  124. $form['actions']['submit'] = [
  125. '#type' => 'submit',
  126. '#value' => $this->t('Save blocks'),
  127. '#button_type' => 'primary',
  128. ];
  129. return $form;
  130. }
  131. /**
  132. * Builds the main "Blocks" portion of the form.
  133. *
  134. * @return array
  135. */
  136. protected function buildBlocksForm() {
  137. // Build blocks first for each region.
  138. $blocks = [];
  139. $entities = $this->load();
  140. /** @var \Drupal\block\BlockInterface[] $entities */
  141. foreach ($entities as $entity_id => $entity) {
  142. $definition = $entity->getPlugin()->getPluginDefinition();
  143. $blocks[$entity->getRegion()][$entity_id] = [
  144. 'label' => $entity->label(),
  145. 'entity_id' => $entity_id,
  146. 'weight' => $entity->getWeight(),
  147. 'entity' => $entity,
  148. 'category' => $definition['category'],
  149. 'status' => $entity->status(),
  150. ];
  151. }
  152. $form = [
  153. '#type' => 'table',
  154. '#header' => [
  155. $this->t('Block'),
  156. $this->t('Category'),
  157. $this->t('Region'),
  158. $this->t('Weight'),
  159. $this->t('Operations'),
  160. ],
  161. '#attributes' => [
  162. 'id' => 'blocks',
  163. ],
  164. ];
  165. // Weights range from -delta to +delta, so delta should be at least half
  166. // of the amount of blocks present. This makes sure all blocks in the same
  167. // region get an unique weight.
  168. $weight_delta = round(count($entities) / 2);
  169. $placement = FALSE;
  170. if ($this->request->query->has('block-placement')) {
  171. $placement = $this->request->query->get('block-placement');
  172. $form['#attached']['drupalSettings']['blockPlacement'] = $placement;
  173. }
  174. // Loop over each region and build blocks.
  175. $regions = $this->systemRegionList($this->getThemeName(), REGIONS_VISIBLE);
  176. foreach ($regions as $region => $title) {
  177. $form['#tabledrag'][] = [
  178. 'action' => 'match',
  179. 'relationship' => 'sibling',
  180. 'group' => 'block-region-select',
  181. 'subgroup' => 'block-region-' . $region,
  182. 'hidden' => FALSE,
  183. ];
  184. $form['#tabledrag'][] = [
  185. 'action' => 'order',
  186. 'relationship' => 'sibling',
  187. 'group' => 'block-weight',
  188. 'subgroup' => 'block-weight-' . $region,
  189. ];
  190. $form['region-' . $region] = [
  191. '#attributes' => [
  192. 'class' => ['region-title', 'region-title-' . $region],
  193. 'no_striping' => TRUE,
  194. ],
  195. ];
  196. $form['region-' . $region]['title'] = [
  197. '#theme_wrappers' => [
  198. 'container' => [
  199. '#attributes' => ['class' => 'region-title__action'],
  200. ],
  201. ],
  202. '#prefix' => $title,
  203. '#type' => 'link',
  204. '#title' => $this->t('Place block <span class="visually-hidden">in the %region region</span>', ['%region' => $title]),
  205. '#url' => Url::fromRoute('block.admin_library', ['theme' => $this->getThemeName()], ['query' => ['region' => $region]]),
  206. '#wrapper_attributes' => [
  207. 'colspan' => 5,
  208. ],
  209. '#attributes' => [
  210. 'class' => ['use-ajax', 'button', 'button--small'],
  211. 'data-dialog-type' => 'modal',
  212. 'data-dialog-options' => Json::encode([
  213. 'width' => 700,
  214. ]),
  215. ],
  216. ];
  217. $form['region-' . $region . '-message'] = [
  218. '#attributes' => [
  219. 'class' => [
  220. 'region-message',
  221. 'region-' . $region . '-message',
  222. empty($blocks[$region]) ? 'region-empty' : 'region-populated',
  223. ],
  224. ],
  225. ];
  226. $form['region-' . $region . '-message']['message'] = [
  227. '#markup' => '<em>' . $this->t('No blocks in this region') . '</em>',
  228. '#wrapper_attributes' => [
  229. 'colspan' => 5,
  230. ],
  231. ];
  232. if (isset($blocks[$region])) {
  233. foreach ($blocks[$region] as $info) {
  234. $entity_id = $info['entity_id'];
  235. $form[$entity_id] = [
  236. '#attributes' => [
  237. 'class' => ['draggable'],
  238. ],
  239. ];
  240. $form[$entity_id]['#attributes']['class'][] = $info['status'] ? 'block-enabled' : 'block-disabled';
  241. if ($placement && $placement == Html::getClass($entity_id)) {
  242. $form[$entity_id]['#attributes']['class'][] = 'color-success';
  243. $form[$entity_id]['#attributes']['class'][] = 'js-block-placed';
  244. }
  245. $form[$entity_id]['info'] = [
  246. '#plain_text' => $info['status'] ? $info['label'] : $this->t('@label (disabled)', ['@label' => $info['label']]),
  247. '#wrapper_attributes' => [
  248. 'class' => ['block'],
  249. ],
  250. ];
  251. $form[$entity_id]['type'] = [
  252. '#markup' => $info['category'],
  253. ];
  254. $form[$entity_id]['region-theme']['region'] = [
  255. '#type' => 'select',
  256. '#default_value' => $region,
  257. '#required' => TRUE,
  258. '#title' => $this->t('Region for @block block', ['@block' => $info['label']]),
  259. '#title_display' => 'invisible',
  260. '#options' => $regions,
  261. '#attributes' => [
  262. 'class' => ['block-region-select', 'block-region-' . $region],
  263. ],
  264. '#parents' => ['blocks', $entity_id, 'region'],
  265. ];
  266. $form[$entity_id]['region-theme']['theme'] = [
  267. '#type' => 'hidden',
  268. '#value' => $this->getThemeName(),
  269. '#parents' => ['blocks', $entity_id, 'theme'],
  270. ];
  271. $form[$entity_id]['weight'] = [
  272. '#type' => 'weight',
  273. '#default_value' => $info['weight'],
  274. '#delta' => $weight_delta,
  275. '#title' => $this->t('Weight for @block block', ['@block' => $info['label']]),
  276. '#title_display' => 'invisible',
  277. '#attributes' => [
  278. 'class' => ['block-weight', 'block-weight-' . $region],
  279. ],
  280. ];
  281. $form[$entity_id]['operations'] = $this->buildOperations($info['entity']);
  282. }
  283. }
  284. }
  285. // Do not allow disabling the main system content block when it is present.
  286. if (isset($form['system_main']['region'])) {
  287. $form['system_main']['region']['#required'] = TRUE;
  288. }
  289. return $form;
  290. }
  291. /**
  292. * Gets the name of the theme used for this block listing.
  293. *
  294. * @return string
  295. * The name of the theme.
  296. */
  297. protected function getThemeName() {
  298. // If no theme was specified, use the current theme.
  299. if (!$this->theme) {
  300. $this->theme = $this->themeManager->getActiveTheme()->getName();
  301. }
  302. return $this->theme;
  303. }
  304. /**
  305. * {@inheritdoc}
  306. */
  307. protected function getEntityIds() {
  308. return $this->getStorage()->getQuery()
  309. ->condition('theme', $this->getThemeName())
  310. ->sort($this->entityType->getKey('id'))
  311. ->execute();
  312. }
  313. /**
  314. * {@inheritdoc}
  315. */
  316. public function getDefaultOperations(EntityInterface $entity) {
  317. $operations = parent::getDefaultOperations($entity);
  318. if (isset($operations['edit'])) {
  319. $operations['edit']['title'] = $this->t('Configure');
  320. }
  321. if (isset($operations['delete'])) {
  322. $operations['delete']['title'] = $this->t('Remove');
  323. }
  324. return $operations;
  325. }
  326. /**
  327. * {@inheritdoc}
  328. */
  329. public function validateForm(array &$form, FormStateInterface $form_state) {
  330. // No validation.
  331. }
  332. /**
  333. * {@inheritdoc}
  334. */
  335. public function submitForm(array &$form, FormStateInterface $form_state) {
  336. $entities = $this->storage->loadMultiple(array_keys($form_state->getValue('blocks')));
  337. /** @var \Drupal\block\BlockInterface[] $entities */
  338. foreach ($entities as $entity_id => $entity) {
  339. $entity_values = $form_state->getValue(['blocks', $entity_id]);
  340. $entity->setWeight($entity_values['weight']);
  341. $entity->setRegion($entity_values['region']);
  342. $entity->save();
  343. }
  344. $this->messenger->addStatus($this->t('The block settings have been updated.'));
  345. // Remove any previously set block placement.
  346. $this->request->query->remove('block-placement');
  347. }
  348. /**
  349. * Wraps system_region_list().
  350. */
  351. protected function systemRegionList($theme, $show = REGIONS_ALL) {
  352. return system_region_list($theme, $show);
  353. }
  354. }