DisplayBlockTest.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. <?php
  2. namespace Drupal\Tests\block\Functional\Views;
  3. use Drupal\Component\Serialization\Json;
  4. use Drupal\Component\Utility\Crypt;
  5. use Drupal\Core\Site\Settings;
  6. use Drupal\Core\Url;
  7. use Drupal\Tests\block\Functional\AssertBlockAppearsTrait;
  8. use Drupal\Tests\system\Functional\Cache\AssertPageCacheContextsAndTagsTrait;
  9. use Drupal\Tests\views\Functional\ViewTestBase;
  10. use Drupal\views\Entity\View;
  11. use Drupal\views\Views;
  12. use Drupal\views\Tests\ViewTestData;
  13. use Drupal\Core\Template\Attribute;
  14. /**
  15. * Tests the block display plugin.
  16. *
  17. * @group block
  18. * @see \Drupal\views\Plugin\views\display\Block
  19. */
  20. class DisplayBlockTest extends ViewTestBase {
  21. use AssertPageCacheContextsAndTagsTrait;
  22. use AssertBlockAppearsTrait;
  23. /**
  24. * Modules to install.
  25. *
  26. * @var array
  27. */
  28. public static $modules = ['node', 'block_test_views', 'test_page_test', 'contextual', 'views_ui'];
  29. /**
  30. * Views used by this test.
  31. *
  32. * @var array
  33. */
  34. public static $testViews = ['test_view_block', 'test_view_block2'];
  35. /**
  36. * {@inheritdoc}
  37. */
  38. protected function setUp($import_test_views = TRUE) {
  39. parent::setUp($import_test_views);
  40. ViewTestData::createTestViews(get_class($this), ['block_test_views']);
  41. $this->enableViewsTestModule();
  42. }
  43. /**
  44. * Tests default and custom block categories.
  45. */
  46. public function testBlockCategory() {
  47. $this->drupalLogin($this->drupalCreateUser(['administer views', 'administer blocks']));
  48. // Create a new view in the UI.
  49. $edit = [];
  50. $edit['label'] = $this->randomString();
  51. $edit['id'] = strtolower($this->randomMachineName());
  52. $edit['show[wizard_key]'] = 'standard:views_test_data';
  53. $edit['description'] = $this->randomString();
  54. $edit['block[create]'] = TRUE;
  55. $edit['block[style][row_plugin]'] = 'fields';
  56. $this->drupalPostForm('admin/structure/views/add', $edit, t('Save and edit'));
  57. $pattern = '//tr[.//td[text()=:category] and .//td//a[contains(@href, :href)]]';
  58. // Test that the block was given a default category corresponding to its
  59. // base table.
  60. $arguments = [
  61. ':href' => \Drupal::Url('block.admin_add', [
  62. 'plugin_id' => 'views_block:' . $edit['id'] . '-block_1',
  63. 'theme' => 'classy',
  64. ]),
  65. ':category' => 'Lists (Views)',
  66. ];
  67. $this->drupalGet('admin/structure/block');
  68. $this->clickLink('Place block');
  69. $elements = $this->xpath($pattern, $arguments);
  70. $this->assertTrue(!empty($elements), 'The test block appears in the category for its base table.');
  71. // Duplicate the block before changing the category.
  72. $this->drupalPostForm('admin/structure/views/view/' . $edit['id'] . '/edit/block_1', [], t('Duplicate @display_title', ['@display_title' => 'Block']));
  73. $this->assertUrl('admin/structure/views/view/' . $edit['id'] . '/edit/block_2');
  74. // Change the block category to a random string.
  75. $this->drupalGet('admin/structure/views/view/' . $edit['id'] . '/edit/block_1');
  76. $link = $this->xpath('//a[@id="views-block-1-block-category" and normalize-space(text())=:category]', $arguments);
  77. $this->assertTrue(!empty($link));
  78. $this->clickLink(t('Lists (Views)'));
  79. $category = $this->randomString();
  80. $this->drupalPostForm(NULL, ['block_category' => $category], t('Apply'));
  81. // Duplicate the block after changing the category.
  82. $this->drupalPostForm(NULL, [], t('Duplicate @display_title', ['@display_title' => 'Block']));
  83. $this->assertUrl('admin/structure/views/view/' . $edit['id'] . '/edit/block_3');
  84. $this->drupalPostForm(NULL, [], t('Save'));
  85. // Test that the blocks are listed under the correct categories.
  86. $arguments[':category'] = $category;
  87. $this->drupalGet('admin/structure/block');
  88. $this->clickLink('Place block');
  89. $elements = $this->xpath($pattern, $arguments);
  90. $this->assertTrue(!empty($elements), 'The test block appears in the custom category.');
  91. $arguments = [
  92. ':href' => \Drupal::Url('block.admin_add', [
  93. 'plugin_id' => 'views_block:' . $edit['id'] . '-block_2',
  94. 'theme' => 'classy',
  95. ]),
  96. ':category' => 'Lists (Views)',
  97. ];
  98. $elements = $this->xpath($pattern, $arguments);
  99. $this->assertTrue(!empty($elements), 'The first duplicated test block remains in the original category.');
  100. $arguments = [
  101. ':href' => \Drupal::Url('block.admin_add', [
  102. 'plugin_id' => 'views_block:' . $edit['id'] . '-block_3',
  103. 'theme' => 'classy',
  104. ]),
  105. ':category' => $category,
  106. ];
  107. $elements = $this->xpath($pattern, $arguments);
  108. $this->assertTrue(!empty($elements), 'The second duplicated test block appears in the custom category.');
  109. }
  110. /**
  111. * Tests removing a block display.
  112. */
  113. public function testDeleteBlockDisplay() {
  114. // To test all combinations possible we first place create two instances
  115. // of the block display of the first view.
  116. $block_1 = $this->drupalPlaceBlock('views_block:test_view_block-block_1', ['label' => 'test_view_block-block_1:1']);
  117. $block_2 = $this->drupalPlaceBlock('views_block:test_view_block-block_1', ['label' => 'test_view_block-block_1:2']);
  118. // Then we add one instance of blocks for each of the two displays of the
  119. // second view.
  120. $block_3 = $this->drupalPlaceBlock('views_block:test_view_block2-block_1', ['label' => 'test_view_block2-block_1']);
  121. $block_4 = $this->drupalPlaceBlock('views_block:test_view_block2-block_2', ['label' => 'test_view_block2-block_2']);
  122. $this->drupalGet('test-page');
  123. $this->assertBlockAppears($block_1);
  124. $this->assertBlockAppears($block_2);
  125. $this->assertBlockAppears($block_3);
  126. $this->assertBlockAppears($block_4);
  127. $block_storage = $this->container->get('entity_type.manager')->getStorage('block');
  128. // Remove the block display, so both block entities from the first view
  129. // should both disappear.
  130. $view = Views::getView('test_view_block');
  131. $view->initDisplay();
  132. $view->displayHandlers->remove('block_1');
  133. $view->storage->save();
  134. $this->assertFalse($block_storage->load($block_1->id()), 'The block for this display was removed.');
  135. $this->assertFalse($block_storage->load($block_2->id()), 'The block for this display was removed.');
  136. $this->assertTrue($block_storage->load($block_3->id()), 'A block from another view was unaffected.');
  137. $this->assertTrue($block_storage->load($block_4->id()), 'A block from another view was unaffected.');
  138. $this->drupalGet('test-page');
  139. $this->assertNoBlockAppears($block_1);
  140. $this->assertNoBlockAppears($block_2);
  141. $this->assertBlockAppears($block_3);
  142. $this->assertBlockAppears($block_4);
  143. // Remove the first block display of the second view and ensure the block
  144. // instance of the second block display still exists.
  145. $view = Views::getView('test_view_block2');
  146. $view->initDisplay();
  147. $view->displayHandlers->remove('block_1');
  148. $view->storage->save();
  149. $this->assertFalse($block_storage->load($block_3->id()), 'The block for this display was removed.');
  150. $this->assertTrue($block_storage->load($block_4->id()), 'A block from another display on the same view was unaffected.');
  151. $this->drupalGet('test-page');
  152. $this->assertNoBlockAppears($block_3);
  153. $this->assertBlockAppears($block_4);
  154. }
  155. /**
  156. * Test the block form for a Views block.
  157. */
  158. public function testViewsBlockForm() {
  159. $this->drupalLogin($this->drupalCreateUser(['administer blocks']));
  160. $default_theme = $this->config('system.theme')->get('default');
  161. $this->drupalGet('admin/structure/block/add/views_block:test_view_block-block_1/' . $default_theme);
  162. $elements = $this->xpath('//input[@name="label"]');
  163. $this->assertTrue(empty($elements), 'The label field is not found for Views blocks.');
  164. // Test that that machine name field is hidden from display and has been
  165. // saved as expected from the default value.
  166. $this->assertNoFieldById('edit-machine-name', 'views_block__test_view_block_1', 'The machine name is hidden on the views block form.');
  167. // Save the block.
  168. $edit = ['region' => 'content'];
  169. $this->drupalPostForm(NULL, $edit, t('Save block'));
  170. $storage = $this->container->get('entity_type.manager')->getStorage('block');
  171. $block = $storage->load('views_block__test_view_block_block_1');
  172. // This will only return a result if our new block has been created with the
  173. // expected machine name.
  174. $this->assertTrue(!empty($block), 'The expected block was loaded.');
  175. for ($i = 2; $i <= 3; $i++) {
  176. // Place the same block again and make sure we have a new ID.
  177. $this->drupalPostForm('admin/structure/block/add/views_block:test_view_block-block_1/' . $default_theme, $edit, t('Save block'));
  178. $block = $storage->load('views_block__test_view_block_block_1_' . $i);
  179. // This will only return a result if our new block has been created with the
  180. // expected machine name.
  181. $this->assertTrue(!empty($block), 'The expected block was loaded.');
  182. }
  183. // Tests the override capability of items per page.
  184. $this->drupalGet('admin/structure/block/add/views_block:test_view_block-block_1/' . $default_theme);
  185. $edit = ['region' => 'content'];
  186. $edit['settings[override][items_per_page]'] = 10;
  187. $this->drupalPostForm('admin/structure/block/add/views_block:test_view_block-block_1/' . $default_theme, $edit, t('Save block'));
  188. $block = $storage->load('views_block__test_view_block_block_1_4');
  189. $config = $block->getPlugin()->getConfiguration();
  190. $this->assertEqual(10, $config['items_per_page'], "'Items per page' is properly saved.");
  191. $edit['settings[override][items_per_page]'] = 5;
  192. $this->drupalPostForm('admin/structure/block/manage/views_block__test_view_block_block_1_4', $edit, t('Save block'));
  193. $block = $storage->load('views_block__test_view_block_block_1_4');
  194. $config = $block->getPlugin()->getConfiguration();
  195. $this->assertEqual(5, $config['items_per_page'], "'Items per page' is properly saved.");
  196. // Tests the override of the label capability.
  197. $edit = ['region' => 'content'];
  198. $edit['settings[views_label_checkbox]'] = 1;
  199. $edit['settings[views_label]'] = 'Custom title';
  200. $this->drupalPostForm('admin/structure/block/add/views_block:test_view_block-block_1/' . $default_theme, $edit, t('Save block'));
  201. $block = $storage->load('views_block__test_view_block_block_1_5');
  202. $config = $block->getPlugin()->getConfiguration();
  203. $this->assertEqual('Custom title', $config['views_label'], "'Label' is properly saved.");
  204. }
  205. /**
  206. * Tests the actual rendering of the views block.
  207. */
  208. public function testBlockRendering() {
  209. // Create a block and set a custom title.
  210. $block = $this->drupalPlaceBlock('views_block:test_view_block-block_1', ['label' => 'test_view_block-block_1:1', 'views_label' => 'Custom title']);
  211. $this->drupalGet('');
  212. $result = $this->xpath('//div[contains(@class, "region-sidebar-first")]/div[contains(@class, "block-views")]/h2');
  213. $this->assertEqual($result[0]->getText(), 'Custom title');
  214. // Don't override the title anymore.
  215. $plugin = $block->getPlugin();
  216. $plugin->setConfigurationValue('views_label', '');
  217. $block->save();
  218. $this->drupalGet('');
  219. $result = $this->xpath('//div[contains(@class, "region-sidebar-first")]/div[contains(@class, "block-views")]/h2');
  220. $this->assertEqual($result[0]->getText(), 'test_view_block');
  221. // Hide the title.
  222. $block->getPlugin()->setConfigurationValue('label_display', FALSE);
  223. $block->save();
  224. $this->drupalGet('');
  225. $result = $this->xpath('//div[contains(@class, "region-sidebar-first")]/div[contains(@class, "block-views")]/h2');
  226. $this->assertTrue(empty($result), 'The title is not visible.');
  227. $this->assertCacheTags(array_merge($block->getCacheTags(), ['block_view', 'config:block_list', 'config:system.site', 'config:views.view.test_view_block', 'http_response', 'rendered']));
  228. }
  229. /**
  230. * Tests the various testcases of empty block rendering.
  231. */
  232. public function testBlockEmptyRendering() {
  233. $url = new Url('test_page_test.test_page');
  234. // Remove all views_test_data entries.
  235. \Drupal::database()->truncate('views_test_data')->execute();
  236. /** @var \Drupal\views\ViewEntityInterface $view */
  237. $view = View::load('test_view_block');
  238. $view->invalidateCaches();
  239. $block = $this->drupalPlaceBlock('views_block:test_view_block-block_1', ['label' => 'test_view_block-block_1:1', 'views_label' => 'Custom title']);
  240. $this->drupalGet('');
  241. $this->assertEqual(1, count($this->xpath('//div[contains(@class, "block-views-blocktest-view-block-block-1")]')));
  242. $display = &$view->getDisplay('block_1');
  243. $display['display_options']['block_hide_empty'] = TRUE;
  244. $view->save();
  245. $this->drupalGet($url);
  246. $this->assertEqual(0, count($this->xpath('//div[contains(@class, "block-views-blocktest-view-block-block-1")]')));
  247. // Ensure that the view cacheability metadata is propagated even, for an
  248. // empty block.
  249. $this->assertCacheTags(array_merge($block->getCacheTags(), ['block_view', 'config:block_list', 'config:views.view.test_view_block', 'http_response', 'rendered']));
  250. $this->assertCacheContexts(['url.query_args:_wrapper_format']);
  251. // Add a header displayed on empty result.
  252. $display = &$view->getDisplay('block_1');
  253. $display['display_options']['defaults']['header'] = FALSE;
  254. $display['display_options']['header']['example'] = [
  255. 'field' => 'area_text_custom',
  256. 'id' => 'area_text_custom',
  257. 'table' => 'views',
  258. 'plugin_id' => 'text_custom',
  259. 'content' => 'test header',
  260. 'empty' => TRUE,
  261. ];
  262. $view->save();
  263. $this->drupalGet($url);
  264. $this->assertEqual(1, count($this->xpath('//div[contains(@class, "block-views-blocktest-view-block-block-1")]')));
  265. $this->assertCacheTags(array_merge($block->getCacheTags(), ['block_view', 'config:block_list', 'config:views.view.test_view_block', 'http_response', 'rendered']));
  266. $this->assertCacheContexts(['url.query_args:_wrapper_format']);
  267. // Hide the header on empty results.
  268. $display = &$view->getDisplay('block_1');
  269. $display['display_options']['defaults']['header'] = FALSE;
  270. $display['display_options']['header']['example'] = [
  271. 'field' => 'area_text_custom',
  272. 'id' => 'area_text_custom',
  273. 'table' => 'views',
  274. 'plugin_id' => 'text_custom',
  275. 'content' => 'test header',
  276. 'empty' => FALSE,
  277. ];
  278. $view->save();
  279. $this->drupalGet($url);
  280. $this->assertEqual(0, count($this->xpath('//div[contains(@class, "block-views-blocktest-view-block-block-1")]')));
  281. $this->assertCacheTags(array_merge($block->getCacheTags(), ['block_view', 'config:block_list', 'config:views.view.test_view_block', 'http_response', 'rendered']));
  282. $this->assertCacheContexts(['url.query_args:_wrapper_format']);
  283. // Add an empty text.
  284. $display = &$view->getDisplay('block_1');
  285. $display['display_options']['defaults']['empty'] = FALSE;
  286. $display['display_options']['empty']['example'] = [
  287. 'field' => 'area_text_custom',
  288. 'id' => 'area_text_custom',
  289. 'table' => 'views',
  290. 'plugin_id' => 'text_custom',
  291. 'content' => 'test empty',
  292. ];
  293. $view->save();
  294. $this->drupalGet($url);
  295. $this->assertEqual(1, count($this->xpath('//div[contains(@class, "block-views-blocktest-view-block-block-1")]')));
  296. $this->assertCacheTags(array_merge($block->getCacheTags(), ['block_view', 'config:block_list', 'config:views.view.test_view_block', 'http_response', 'rendered']));
  297. $this->assertCacheContexts(['url.query_args:_wrapper_format']);
  298. }
  299. /**
  300. * Tests the contextual links on a Views block.
  301. */
  302. public function testBlockContextualLinks() {
  303. $this->drupalLogin($this->drupalCreateUser(['administer views', 'access contextual links', 'administer blocks']));
  304. $block = $this->drupalPlaceBlock('views_block:test_view_block-block_1');
  305. $cached_block = $this->drupalPlaceBlock('views_block:test_view_block-block_1');
  306. $this->drupalGet('test-page');
  307. $id = 'block:block=' . $block->id() . ':langcode=en|entity.view.edit_form:view=test_view_block:location=block&name=test_view_block&display_id=block_1&langcode=en';
  308. $id_token = Crypt::hmacBase64($id, Settings::getHashSalt() . $this->container->get('private_key')->get());
  309. $cached_id = 'block:block=' . $cached_block->id() . ':langcode=en|entity.view.edit_form:view=test_view_block:location=block&name=test_view_block&display_id=block_1&langcode=en';
  310. $cached_id_token = Crypt::hmacBase64($cached_id, Settings::getHashSalt() . $this->container->get('private_key')->get());
  311. // @see \Drupal\contextual\Tests\ContextualDynamicContextTest:assertContextualLinkPlaceHolder()
  312. $this->assertRaw('<div' . new Attribute(['data-contextual-id' => $id, 'data-contextual-token' => $id_token]) . '></div>', format_string('Contextual link placeholder with id @id exists.', ['@id' => $id]));
  313. $this->assertRaw('<div' . new Attribute(['data-contextual-id' => $cached_id, 'data-contextual-token' => $cached_id_token]) . '></div>', format_string('Contextual link placeholder with id @id exists.', ['@id' => $cached_id]));
  314. // Get server-rendered contextual links.
  315. // @see \Drupal\contextual\Tests\ContextualDynamicContextTest:renderContextualLinks()
  316. $post = ['ids[0]' => $id, 'ids[1]' => $cached_id, 'tokens[0]' => $id_token, 'tokens[1]' => $cached_id_token];
  317. $url = 'contextual/render?_format=json,destination=test-page';
  318. $this->getSession()->getDriver()->getClient()->request('POST', $url, $post);
  319. $this->assertResponse(200);
  320. $json = Json::decode($this->getSession()->getPage()->getContent());
  321. $this->assertIdentical($json[$id], '<ul class="contextual-links"><li class="block-configure"><a href="' . base_path() . 'admin/structure/block/manage/' . $block->id() . '">Configure block</a></li><li class="entityviewedit-form"><a href="' . base_path() . 'admin/structure/views/view/test_view_block/edit/block_1">Edit view</a></li></ul>');
  322. $this->assertIdentical($json[$cached_id], '<ul class="contextual-links"><li class="block-configure"><a href="' . base_path() . 'admin/structure/block/manage/' . $cached_block->id() . '">Configure block</a></li><li class="entityviewedit-form"><a href="' . base_path() . 'admin/structure/views/view/test_view_block/edit/block_1">Edit view</a></li></ul>');
  323. }
  324. }