38b7327b4d84d3bda90a20506932a5caeddfd514
[yaffs-website] / web / core / modules / views / tests / src / Functional / Plugin / ExposedFormTest.php
1 <?php
2
3 namespace Drupal\Tests\views\Functional\Plugin;
4
5 use Drupal\Component\Utility\Html;
6 use Drupal\entity_test\Entity\EntityTest;
7 use Drupal\system\Tests\Cache\AssertPageCacheContextsAndTagsTrait;
8 use Drupal\Tests\views\Functional\ViewTestBase;
9 use Drupal\views\ViewExecutable;
10 use Drupal\views\Views;
11 use Drupal\views\Entity\View;
12
13 /**
14  * Tests exposed forms functionality.
15  *
16  * @group views
17  */
18 class ExposedFormTest extends ViewTestBase {
19
20   use AssertPageCacheContextsAndTagsTrait;
21
22   /**
23    * Views used by this test.
24    *
25    * @var array
26    */
27   public static $testViews = ['test_exposed_form_buttons', 'test_exposed_block', 'test_exposed_form_sort_items_per_page'];
28
29   /**
30    * Modules to enable.
31    *
32    * @var array
33    */
34   public static $modules = ['node', 'views_ui', 'block', 'entity_test'];
35
36   protected function setUp($import_test_views = TRUE) {
37     parent::setUp($import_test_views);
38
39     $this->enableViewsTestModule();
40
41     $this->drupalCreateContentType(['type' => 'article']);
42
43     // Create some random nodes.
44     for ($i = 0; $i < 5; $i++) {
45       $this->drupalCreateNode(['type' => 'article']);
46     }
47   }
48
49   /**
50    * Tests the submit button.
51    */
52   public function testSubmitButton() {
53     // Test the submit button value defaults to 'Apply'.
54     $this->drupalGet('test_exposed_form_buttons');
55     $this->assertResponse(200);
56     $this->helperButtonHasLabel('edit-submit-test-exposed-form-buttons', t('Apply'));
57
58     // Rename the label of the submit button.
59     $view = Views::getView('test_exposed_form_buttons');
60     $view->setDisplay();
61
62     $exposed_form = $view->display_handler->getOption('exposed_form');
63     $exposed_form['options']['submit_button'] = $expected_label = $this->randomMachineName();
64     $view->display_handler->setOption('exposed_form', $exposed_form);
65     $view->save();
66
67     // Make sure the submit button label changed.
68     $this->drupalGet('test_exposed_form_buttons');
69     $this->helperButtonHasLabel('edit-submit-test-exposed-form-buttons', $expected_label);
70
71     // Make sure an empty label uses the default 'Apply' button value too.
72     $view = Views::getView('test_exposed_form_buttons');
73     $view->setDisplay();
74
75     $exposed_form = $view->display_handler->getOption('exposed_form');
76     $exposed_form['options']['submit_button'] = '';
77     $view->display_handler->setOption('exposed_form', $exposed_form);
78     $view->save();
79
80     // Make sure the submit button label shows 'Apply'.
81     $this->drupalGet('test_exposed_form_buttons');
82     $this->helperButtonHasLabel('edit-submit-test-exposed-form-buttons', t('Apply'));
83   }
84
85   /**
86    * Tests the exposed form with a non-standard identifier.
87    */
88   public function testExposedIdentifier() {
89     // Alter the identifier of the filter to a random string.
90     $view = Views::getView('test_exposed_form_buttons');
91     $view->setDisplay();
92     $identifier = 'new_identifier';
93     $view->displayHandlers->get('default')->overrideOption('filters', [
94       'type' => [
95         'exposed' => TRUE,
96         'field' => 'type',
97         'id' => 'type',
98         'table' => 'node_field_data',
99         'plugin_id' => 'in_operator',
100         'entity_type' => 'node',
101         'entity_field' => 'type',
102         'expose' => [
103           'identifier' => $identifier,
104           'label' => 'Content: Type',
105           'operator_id' => 'type_op',
106           'reduce' => FALSE,
107           'description' => 'Exposed overridden description'
108         ],
109       ]
110     ]);
111     $view->save();
112     $this->drupalGet('test_exposed_form_buttons', ['query' => [$identifier => 'article']]);
113     $this->assertFieldById(Html::getId('edit-' . $identifier), 'article', "Article type filter set with new identifier.");
114
115     // Alter the identifier of the filter to a random string containing
116     // restricted characters.
117     $view = Views::getView('test_exposed_form_buttons');
118     $view->setDisplay();
119     $identifier = 'bad identifier';
120     $view->displayHandlers->get('default')->overrideOption('filters', [
121       'type' => [
122         'exposed' => TRUE,
123         'field' => 'type',
124         'id' => 'type',
125         'table' => 'node_field_data',
126         'plugin_id' => 'in_operator',
127         'entity_type' => 'node',
128         'entity_field' => 'type',
129         'expose' => [
130           'identifier' => $identifier,
131           'label' => 'Content: Type',
132           'operator_id' => 'type_op',
133           'reduce' => FALSE,
134           'description' => 'Exposed overridden description'
135         ],
136       ]
137     ]);
138     $this->executeView($view);
139
140     $errors = $view->validate();
141     $expected = [
142       'default' => ['This identifier has illegal characters.'],
143       'page_1' => ['This identifier has illegal characters.'],
144     ];
145     $this->assertEqual($errors, $expected);
146   }
147
148   /**
149    * Tests whether the reset button works on an exposed form.
150    */
151   public function testResetButton() {
152     // Test the button is hidden when there is no exposed input.
153     $this->drupalGet('test_exposed_form_buttons');
154     $this->assertNoField('edit-reset');
155
156     $this->drupalGet('test_exposed_form_buttons', ['query' => ['type' => 'article']]);
157     // Test that the type has been set.
158     $this->assertFieldById('edit-type', 'article', 'Article type filter set.');
159
160     // Test the reset works.
161     $this->drupalGet('test_exposed_form_buttons', ['query' => ['op' => 'Reset']]);
162     $this->assertResponse(200);
163     // Test the type has been reset.
164     $this->assertFieldById('edit-type', 'All', 'Article type filter has been reset.');
165
166     // Test the button is hidden after reset.
167     $this->assertNoField('edit-reset');
168
169     // Test the reset works with type set.
170     $this->drupalGet('test_exposed_form_buttons', ['query' => ['type' => 'article', 'op' => 'Reset']]);
171     $this->assertResponse(200);
172     $this->assertFieldById('edit-type', 'All', 'Article type filter has been reset.');
173
174     // Test the button is hidden after reset.
175     $this->assertNoField('edit-reset');
176
177     // Rename the label of the reset button.
178     $view = Views::getView('test_exposed_form_buttons');
179     $view->setDisplay();
180
181     $exposed_form = $view->display_handler->getOption('exposed_form');
182     $exposed_form['options']['reset_button_label'] = $expected_label = $this->randomMachineName();
183     $exposed_form['options']['reset_button'] = TRUE;
184     $view->display_handler->setOption('exposed_form', $exposed_form);
185     $view->save();
186
187     // Look whether the reset button label changed.
188     $this->drupalGet('test_exposed_form_buttons', ['query' => ['type' => 'article']]);
189     $this->assertResponse(200);
190
191     $this->helperButtonHasLabel('edit-reset', $expected_label);
192   }
193
194   /**
195    * Tests overriding the default render option with checkboxes.
196    */
197   public function testExposedFormRenderCheckboxes() {
198     // Make sure we have at least two options for node type.
199     $this->drupalCreateContentType(['type' => 'page']);
200     $this->drupalCreateNode(['type' => 'page']);
201
202     // Use a test theme to convert multi-select elements into checkboxes.
203     \Drupal::service('theme_handler')->install(['views_test_checkboxes_theme']);
204     $this->config('system.theme')
205       ->set('default', 'views_test_checkboxes_theme')
206       ->save();
207
208     // Set the "type" filter to multi-select.
209     $view = Views::getView('test_exposed_form_buttons');
210     $filter = $view->getHandler('page_1', 'filter', 'type');
211     $filter['expose']['multiple'] = TRUE;
212     $view->setHandler('page_1', 'filter', 'type', $filter);
213
214     // Only display 5 items per page so we can test that paging works.
215     $display = &$view->storage->getDisplay('default');
216     $display['display_options']['pager']['options']['items_per_page'] = 5;
217
218     $view->save();
219     $this->drupalGet('test_exposed_form_buttons');
220
221     $actual = $this->xpath('//form//input[@type="checkbox" and @name="type[article]"]');
222     $this->assertEqual(count($actual), 1, 'Article option renders as a checkbox.');
223     $actual = $this->xpath('//form//input[@type="checkbox" and @name="type[page]"]');
224     $this->assertEqual(count($actual), 1, 'Page option renders as a checkbox');
225
226     // Ensure that all results are displayed.
227     $rows = $this->xpath("//div[contains(@class, 'views-row')]");
228     $this->assertEqual(count($rows), 5, '5 rows are displayed by default on the first page when no options are checked.');
229
230     $this->clickLink('Page 2');
231     $rows = $this->xpath("//div[contains(@class, 'views-row')]");
232     $this->assertEqual(count($rows), 1, '1 row is displayed by default on the second page when no options are checked.');
233     $this->assertNoText('An illegal choice has been detected. Please contact the site administrator.');
234   }
235
236   /**
237    * Tests the exposed block functionality.
238    */
239   public function testExposedBlock() {
240     $this->drupalCreateContentType(['type' => 'page']);
241     $view = Views::getView('test_exposed_block');
242     $view->setDisplay('page_1');
243     $block = $this->drupalPlaceBlock('views_exposed_filter_block:test_exposed_block-page_1');
244     $this->drupalGet('test_exposed_block');
245
246     // Test there is an exposed form in a block.
247     $xpath = $this->buildXPathQuery('//div[@id=:id]/form/@id', [':id' => Html::getUniqueId('block-' . $block->id())]);
248     $result = $this->xpath($xpath);
249     $this->assertEquals(1, count($result));
250
251     // Test there is not an exposed form in the view page content area.
252     $xpath = $this->buildXPathQuery('//div[@class="view-content"]/form/@id', [':id' => Html::getUniqueId('block-' . $block->id())]);
253     $this->assertNoFieldByXpath($xpath, $this->getExpectedExposedFormId($view), 'No exposed form found in views content region.');
254
255     // Test there is only one views exposed form on the page.
256     $elements = $this->xpath('//form[@id=:id]', [':id' => $this->getExpectedExposedFormId($view)]);
257     $this->assertEqual(count($elements), 1, 'One exposed form block found.');
258
259     // Test that the correct option is selected after form submission.
260     $this->assertCacheContext('url');
261     $this->assertOptionSelected('edit-type', 'All');
262     foreach (['All', 'article', 'page'] as $argument) {
263       $this->drupalGet('test_exposed_block', ['query' => ['type' => $argument]]);
264       $this->assertCacheContext('url');
265       $this->assertOptionSelected('edit-type', $argument);
266     }
267   }
268
269   /**
270    * Test the input required exposed form type.
271    */
272   public function testInputRequired() {
273     $view = View::load('test_exposed_form_buttons');
274     $display = &$view->getDisplay('default');
275     $display['display_options']['exposed_form']['type'] = 'input_required';
276     $view->save();
277
278     $this->drupalGet('test_exposed_form_buttons');
279     $this->assertResponse(200);
280     $this->helperButtonHasLabel('edit-submit-test-exposed-form-buttons', t('Apply'));
281
282     // Ensure that no results are displayed.
283     $rows = $this->xpath("//div[contains(@class, 'views-row')]");
284     $this->assertEqual(count($rows), 0, 'No rows are displayed by default when no input is provided.');
285
286     $this->drupalGet('test_exposed_form_buttons', ['query' => ['type' => 'article']]);
287
288     // Ensure that results are displayed.
289     $rows = $this->xpath("//div[contains(@class, 'views-row')]");
290     $this->assertEqual(count($rows), 5, 'All rows are displayed by default when input is provided.');
291   }
292
293   /**
294    * Test the "on demand text" for the input required exposed form type.
295    */
296   public function testTextInputRequired() {
297     $view = Views::getView('test_exposed_form_buttons');
298     $display = &$view->storage->getDisplay('default');
299     $display['display_options']['exposed_form']['type'] = 'input_required';
300     // Set up the "on demand text".
301     // @see https://www.drupal.org/node/535868
302     $on_demand_text = 'Select any filter and click Apply to see results.';
303     $display['display_options']['exposed_form']['options']['text_input_required'] = $on_demand_text;
304     $display['display_options']['exposed_form']['options']['text_input_required_format'] = filter_default_format();
305     $view->save();
306
307     // Ensure that the "on demand text" is displayed when no exposed filters are
308     // applied.
309     $this->drupalGet('test_exposed_form_buttons');
310     $this->assertText('Select any filter and click Apply to see results.');
311
312     // Ensure that the "on demand text" is not displayed when an exposed filter
313     // is applied.
314     $this->drupalGet('test_exposed_form_buttons', ['query' => ['type' => 'article']]);
315     $this->assertNoText($on_demand_text);
316   }
317
318   /**
319    * Tests exposed forms with exposed sort and items per page.
320    */
321   public function testExposedSortAndItemsPerPage() {
322     for ($i = 0; $i < 50; $i++) {
323       $entity = EntityTest::create([
324       ]);
325       $entity->save();
326     }
327     $contexts = [
328       'languages:language_interface',
329       'entity_test_view_grants',
330       'theme',
331       'url.query_args',
332       'languages:language_content'
333     ];
334
335     $this->drupalGet('test_exposed_form_sort_items_per_page');
336     $this->assertCacheContexts($contexts);
337     $this->assertIds(range(1, 10, 1));
338
339     $this->drupalGet('test_exposed_form_sort_items_per_page', ['query' => ['sort_order' => 'DESC']]);
340     $this->assertCacheContexts($contexts);
341     $this->assertIds(range(50, 41, 1));
342
343     $this->drupalGet('test_exposed_form_sort_items_per_page', ['query' => ['sort_order' => 'DESC', 'items_per_page' => 25]]);
344     $this->assertCacheContexts($contexts);
345     $this->assertIds(range(50, 26, 1));
346
347     $this->drupalGet('test_exposed_form_sort_items_per_page', ['query' => ['sort_order' => 'DESC', 'items_per_page' => 25, 'offset' => 10]]);
348     $this->assertCacheContexts($contexts);
349     $this->assertIds(range(40, 16, 1));
350   }
351
352   /**
353    * Checks whether the specified ids are the ones displayed in the view output.
354    *
355    * @param int[] $ids
356    *   The ids to check.
357    *
358    * @return bool
359    *   TRUE if ids match, FALSE otherwise.
360    */
361   protected function assertIds(array $ids) {
362     $elements = $this->cssSelect('div.view-test-exposed-form-sort-items-per-page div.views-row span.field-content');
363     $actual_ids = [];
364     foreach ($elements as $element) {
365       $actual_ids[] = (int) $element->getText();
366     }
367
368     return $this->assertIdentical($ids, $actual_ids);
369   }
370
371   /**
372    * Returns a views exposed form ID.
373    *
374    * @param \Drupal\views\ViewExecutable $view
375    *   The view to create an ID for.
376    *
377    * @return string
378    *   The form ID.
379    */
380   protected function getExpectedExposedFormId(ViewExecutable $view) {
381     return Html::cleanCssIdentifier('views-exposed-form-' . $view->storage->id() . '-' . $view->current_display);
382   }
383
384   /**
385    * Tests a view which is rendered after a form with a validation error.
386    */
387   public function testFormErrorWithExposedForm() {
388     $this->drupalGet('views_test_data_error_form_page');
389     $this->assertResponse(200);
390     $form = $this->cssSelect('form.views-exposed-form');
391     $this->assertTrue($form, 'The exposed form element was found.');
392     $this->assertRaw(t('Apply'), 'Ensure the exposed form is rendered before submitting the normal form.');
393     $this->assertRaw('<div class="views-row">', 'Views result shown.');
394
395     $this->drupalPostForm(NULL, [], t('Submit'));
396     $this->assertResponse(200);
397     $form = $this->cssSelect('form.views-exposed-form');
398     $this->assertTrue($form, 'The exposed form element was found.');
399     $this->assertRaw(t('Apply'), 'Ensure the exposed form is rendered after submitting the normal form.');
400     $this->assertRaw('<div class="views-row">', 'Views result shown.');
401   }
402
403 }