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