ExposedFormTest.php 16.3 KB
Newer Older
merlinofchaos's avatar
merlinofchaos committed
1
2
<?php

3
namespace Drupal\Tests\views\Functional\Plugin;
4

5
use Drupal\Component\Utility\Html;
6
use Drupal\entity_test\Entity\EntityTest;
7
use Drupal\Tests\system\Functional\Cache\AssertPageCacheContextsAndTagsTrait;
8
use Drupal\Tests\views\Functional\ViewTestBase;
9
10
use Drupal\views\ViewExecutable;
use Drupal\views\Views;
11
use Drupal\views\Entity\View;
12

merlinofchaos's avatar
merlinofchaos committed
13
/**
14
15
16
 * Tests exposed forms functionality.
 *
 * @group views
merlinofchaos's avatar
merlinofchaos committed
17
 */
18
class ExposedFormTest extends ViewTestBase {
19

20
21
  use AssertPageCacheContextsAndTagsTrait;

22
23
24
25
26
  /**
   * Views used by this test.
   *
   * @var array
   */
27
  public static $testViews = ['test_exposed_form_buttons', 'test_exposed_block', 'test_exposed_form_sort_items_per_page', 'test_exposed_form_pager'];
28

29
30
31
32
33
  /**
   * Modules to enable.
   *
   * @var array
   */
34
  protected static $modules = ['node', 'views_ui', 'block', 'entity_test'];
35

36
37
38
39
40
  /**
   * {@inheritdoc}
   */
  protected $defaultTheme = 'classy';

41
  protected function setUp($import_test_views = TRUE): void {
42
    parent::setUp($import_test_views);
43

44
45
    $this->enableViewsTestModule();

46
    $this->drupalCreateContentType(['type' => 'article']);
47
48
49

    // Create some random nodes.
    for ($i = 0; $i < 5; $i++) {
50
      $this->drupalCreateNode(['type' => 'article']);
51
52
53
    }
  }

54
55
56
57
  /**
   * Tests the submit button.
   */
  public function testSubmitButton() {
58
    // Test the submit button value defaults to 'Apply'.
59
60
    $this->drupalGet('test_exposed_form_buttons');
    $this->assertResponse(200);
61
    $this->helperButtonHasLabel('edit-submit-test-exposed-form-buttons', t('Apply'));
62
63
64
65
66
67

    // Rename the label of the submit button.
    $view = Views::getView('test_exposed_form_buttons');
    $view->setDisplay();

    $exposed_form = $view->display_handler->getOption('exposed_form');
68
    $exposed_form['options']['submit_button'] = $expected_label = $this->randomMachineName();
69
70
71
72
73
74
75
    $view->display_handler->setOption('exposed_form', $exposed_form);
    $view->save();

    // Make sure the submit button label changed.
    $this->drupalGet('test_exposed_form_buttons');
    $this->helperButtonHasLabel('edit-submit-test-exposed-form-buttons', $expected_label);

76
    // Make sure an empty label uses the default 'Apply' button value too.
77
78
79
80
81
82
83
84
    $view = Views::getView('test_exposed_form_buttons');
    $view->setDisplay();

    $exposed_form = $view->display_handler->getOption('exposed_form');
    $exposed_form['options']['submit_button'] = '';
    $view->display_handler->setOption('exposed_form', $exposed_form);
    $view->save();

85
    // Make sure the submit button label shows 'Apply'.
86
    $this->drupalGet('test_exposed_form_buttons');
87
    $this->helperButtonHasLabel('edit-submit-test-exposed-form-buttons', t('Apply'));
88
89
  }

90
91
92
93
94
95
96
97
  /**
   * Tests the exposed form with a non-standard identifier.
   */
  public function testExposedIdentifier() {
    // Alter the identifier of the filter to a random string.
    $view = Views::getView('test_exposed_form_buttons');
    $view->setDisplay();
    $identifier = 'new_identifier';
98
    $view->displayHandlers->get('default')->overrideOption('filters', [
99
100
101
102
103
104
105
106
107
108
109
110
111
      'type' => [
        'exposed' => TRUE,
        'field' => 'type',
        'id' => 'type',
        'table' => 'node_field_data',
        'plugin_id' => 'in_operator',
        'entity_type' => 'node',
        'entity_field' => 'type',
        'expose' => [
          'identifier' => $identifier,
          'label' => 'Content: Type',
          'operator_id' => 'type_op',
          'reduce' => FALSE,
112
          'description' => 'Exposed overridden description',
113
        ],
114
      ],
115
    ]);
116
    $view->save();
117
    $this->drupalGet('test_exposed_form_buttons', ['query' => [$identifier => 'article']]);
118
119
120
121
122
123
124
    $this->assertFieldById(Html::getId('edit-' . $identifier), 'article', "Article type filter set with new identifier.");

    // Alter the identifier of the filter to a random string containing
    // restricted characters.
    $view = Views::getView('test_exposed_form_buttons');
    $view->setDisplay();
    $identifier = 'bad identifier';
125
    $view->displayHandlers->get('default')->overrideOption('filters', [
126
      'type' => [
127
        'exposed' => TRUE,
128
129
130
131
132
133
134
135
136
137
138
        'field' => 'type',
        'id' => 'type',
        'table' => 'node_field_data',
        'plugin_id' => 'in_operator',
        'entity_type' => 'node',
        'entity_field' => 'type',
        'expose' => [
          'identifier' => $identifier,
          'label' => 'Content: Type',
          'operator_id' => 'type_op',
          'reduce' => FALSE,
139
          'description' => 'Exposed overridden description',
140
        ],
141
      ],
142
    ]);
143
144
145
146
147
148
149
150
151
152
    $this->executeView($view);

    $errors = $view->validate();
    $expected = [
      'default' => ['This identifier has illegal characters.'],
      'page_1' => ['This identifier has illegal characters.'],
    ];
    $this->assertEqual($errors, $expected);
  }

153
  /**
154
   * Tests whether the reset button works on an exposed form.
155
156
   */
  public function testResetButton() {
157
    // Test the button is hidden when there is no exposed input.
158
    $this->drupalGet('test_exposed_form_buttons');
159
160
    $this->assertNoField('edit-reset');

161
    $this->drupalGet('test_exposed_form_buttons', ['query' => ['type' => 'article']]);
162
163
164
165
    // Test that the type has been set.
    $this->assertFieldById('edit-type', 'article', 'Article type filter set.');

    // Test the reset works.
166
    $this->drupalGet('test_exposed_form_buttons', ['query' => ['op' => 'Reset']]);
167
168
169
    $this->assertResponse(200);
    // Test the type has been reset.
    $this->assertFieldById('edit-type', 'All', 'Article type filter has been reset.');
170
171
172

    // Test the button is hidden after reset.
    $this->assertNoField('edit-reset');
173

174
    // Test the reset works with type set.
175
    $this->drupalGet('test_exposed_form_buttons', ['query' => ['type' => 'article', 'op' => 'Reset']]);
176
177
178
    $this->assertResponse(200);
    $this->assertFieldById('edit-type', 'All', 'Article type filter has been reset.');

179
180
181
    // Test the button is hidden after reset.
    $this->assertNoField('edit-reset');

merlinofchaos's avatar
merlinofchaos committed
182
    // Rename the label of the reset button.
183
    $view = Views::getView('test_exposed_form_buttons');
184
    $view->setDisplay();
merlinofchaos's avatar
merlinofchaos committed
185

186
    $exposed_form = $view->display_handler->getOption('exposed_form');
187
    $exposed_form['options']['reset_button_label'] = $expected_label = $this->randomMachineName();
merlinofchaos's avatar
merlinofchaos committed
188
    $exposed_form['options']['reset_button'] = TRUE;
189
    $view->display_handler->setOption('exposed_form', $exposed_form);
merlinofchaos's avatar
merlinofchaos committed
190
191
    $view->save();

192
    // Look whether the reset button label changed.
193
    $this->drupalGet('test_exposed_form_buttons', ['query' => ['type' => 'article']]);
194
    $this->assertResponse(200);
merlinofchaos's avatar
merlinofchaos committed
195
196
197
198

    $this->helperButtonHasLabel('edit-reset', $expected_label);
  }

199
200
201
202
  /**
   * Tests the exposed block functionality.
   */
  public function testExposedBlock() {
203
    $this->drupalCreateContentType(['type' => 'page']);
204
205
206
    $view = Views::getView('test_exposed_block');
    $view->setDisplay('page_1');
    $block = $this->drupalPlaceBlock('views_exposed_filter_block:test_exposed_block-page_1');
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228

    // Set label to display on the exposed filter form block.
    $block->getPlugin()->setConfigurationValue('label_display', TRUE);
    $block->save();

    // Test that the block label is found.
    $this->drupalGet('test_exposed_block');
    $this->assertText($view->getTitle(), 'Block title found.');

    // Set a custom label on the exposed filter form block.
    $block->getPlugin()->setConfigurationValue('views_label', '<strong>Custom</strong> title<script>alert("hacked!");</script>');
    $block->save();

    // Test that the custom block label is found.
    $this->drupalGet('test_exposed_block');
    $this->assertRaw('<strong>Custom</strong> titlealert("hacked!");', 'Custom block title found.');

    // Set label to hidden on the exposed filter form block.
    $block->getPlugin()->setConfigurationValue('label_display', FALSE);
    $block->save();

    // Test that the label is removed.
229
    $this->drupalGet('test_exposed_block');
230
231
    $this->assertNoRaw('<strong>Custom</strong> titlealert("hacked!");', 'Custom title was not displayed.');
    $this->assertNoText($view->getTitle(), 'Block title was not displayed.');
232
233

    // Test there is an exposed form in a block.
234
    $xpath = $this->buildXPathQuery('//div[@id=:id]/form/@id', [':id' => Html::getUniqueId('block-' . $block->id())]);
235
    $result = $this->xpath($xpath);
236
    $this->assertCount(1, $result);
237
238

    // Test there is not an exposed form in the view page content area.
239
    $xpath = $this->buildXPathQuery('//div[@class="view-content"]/form/@id', [':id' => Html::getUniqueId('block-' . $block->id())]);
240
241
242
    $this->assertNoFieldByXpath($xpath, $this->getExpectedExposedFormId($view), 'No exposed form found in views content region.');

    // Test there is only one views exposed form on the page.
243
    $elements = $this->xpath('//form[@id=:id]', [':id' => $this->getExpectedExposedFormId($view)]);
244
    $this->assertCount(1, $elements, 'One exposed form block found.');
245
246
247

    // Test that the correct option is selected after form submission.
    $this->assertCacheContext('url');
248
    $this->assertOptionSelected('Content: Type', 'All');
249
250
251
    foreach (['All', 'article', 'page'] as $argument) {
      $this->drupalGet('test_exposed_block', ['query' => ['type' => $argument]]);
      $this->assertCacheContext('url');
252
      $this->assertOptionSelected('Content: Type', $argument);
253
    }
254
255
  }

256
257
258
259
  /**
   * Test the input required exposed form type.
   */
  public function testInputRequired() {
260
    $view = View::load('test_exposed_form_buttons');
261
262
263
264
265
266
    $display = &$view->getDisplay('default');
    $display['display_options']['exposed_form']['type'] = 'input_required';
    $view->save();

    $this->drupalGet('test_exposed_form_buttons');
    $this->assertResponse(200);
267
    $this->helperButtonHasLabel('edit-submit-test-exposed-form-buttons', t('Apply'));
268
269
270

    // Ensure that no results are displayed.
    $rows = $this->xpath("//div[contains(@class, 'views-row')]");
271
    $this->assertCount(0, $rows, 'No rows are displayed by default when no input is provided.');
272

273
    $this->drupalGet('test_exposed_form_buttons', ['query' => ['type' => 'article']]);
274
275
276

    // Ensure that results are displayed.
    $rows = $this->xpath("//div[contains(@class, 'views-row')]");
277
    $this->assertCount(5, $rows, 'All rows are displayed by default when input is provided.');
278
279
  }

280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
  /**
   * Test the "on demand text" for the input required exposed form type.
   */
  public function testTextInputRequired() {
    $view = Views::getView('test_exposed_form_buttons');
    $display = &$view->storage->getDisplay('default');
    $display['display_options']['exposed_form']['type'] = 'input_required';
    // Set up the "on demand text".
    // @see https://www.drupal.org/node/535868
    $on_demand_text = 'Select any filter and click Apply to see results.';
    $display['display_options']['exposed_form']['options']['text_input_required'] = $on_demand_text;
    $display['display_options']['exposed_form']['options']['text_input_required_format'] = filter_default_format();
    $view->save();

    // Ensure that the "on demand text" is displayed when no exposed filters are
    // applied.
    $this->drupalGet('test_exposed_form_buttons');
    $this->assertText('Select any filter and click Apply to see results.');

    // Ensure that the "on demand text" is not displayed when an exposed filter
    // is applied.
301
    $this->drupalGet('test_exposed_form_buttons', ['query' => ['type' => 'article']]);
302
303
304
    $this->assertNoText($on_demand_text);
  }

305
306
307
308
309
  /**
   * Tests exposed forms with exposed sort and items per page.
   */
  public function testExposedSortAndItemsPerPage() {
    for ($i = 0; $i < 50; $i++) {
310
      $entity = EntityTest::create([]);
311
312
313
314
315
316
      $entity->save();
    }
    $contexts = [
      'languages:language_interface',
      'entity_test_view_grants',
      'theme',
317
      'url.query_args',
318
      'languages:language_content',
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
    ];

    $this->drupalGet('test_exposed_form_sort_items_per_page');
    $this->assertCacheContexts($contexts);
    $this->assertIds(range(1, 10, 1));

    $this->drupalGet('test_exposed_form_sort_items_per_page', ['query' => ['sort_order' => 'DESC']]);
    $this->assertCacheContexts($contexts);
    $this->assertIds(range(50, 41, 1));

    $this->drupalGet('test_exposed_form_sort_items_per_page', ['query' => ['sort_order' => 'DESC', 'items_per_page' => 25]]);
    $this->assertCacheContexts($contexts);
    $this->assertIds(range(50, 26, 1));

    $this->drupalGet('test_exposed_form_sort_items_per_page', ['query' => ['sort_order' => 'DESC', 'items_per_page' => 25, 'offset' => 10]]);
    $this->assertCacheContexts($contexts);
    $this->assertIds(range(40, 16, 1));
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356

    // Change the label to something with special characters.
    $view = Views::getView('test_exposed_form_sort_items_per_page');
    $view->setDisplay();
    $sorts = $view->display_handler->getOption('sorts');
    $sorts['id']['expose']['label'] = $expected_label = "<script>alert('unsafe&dangerous');</script>";
    $view->display_handler->setOption('sorts', $sorts);
    $view->save();

    $this->drupalGet('test_exposed_form_sort_items_per_page');
    $options = $this->xpath('//select[@id=:id]/option', [':id' => 'edit-sort-by']);
    $this->assertCount(1, $options);
    $this->assertSession()->optionExists('edit-sort-by', $expected_label);
    $escape_1 = Html::escape($expected_label);
    $escape_2 = Html::escape($escape_1);
    // Make sure we see the single-escaped string in the raw output.
    $this->assertRaw($escape_1);
    // But no double-escaped string.
    $this->assertNoRaw($escape_2);
    // And not the raw label, either.
    $this->assertNoRaw($expected_label);
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
  }

  /**
   * Checks whether the specified ids are the ones displayed in the view output.
   *
   * @param int[] $ids
   *   The ids to check.
   *
   * @return bool
   *   TRUE if ids match, FALSE otherwise.
   */
  protected function assertIds(array $ids) {
    $elements = $this->cssSelect('div.view-test-exposed-form-sort-items-per-page div.views-row span.field-content');
    $actual_ids = [];
    foreach ($elements as $element) {
372
      $actual_ids[] = (int) $element->getText();
373
374
375
376
377
    }

    return $this->assertIdentical($ids, $actual_ids);
  }

378
379
380
381
382
383
384
385
386
387
  /**
   * Returns a views exposed form ID.
   *
   * @param \Drupal\views\ViewExecutable $view
   *   The view to create an ID for.
   *
   * @return string
   *   The form ID.
   */
  protected function getExpectedExposedFormId(ViewExecutable $view) {
388
    return Html::cleanCssIdentifier('views-exposed-form-' . $view->storage->id() . '-' . $view->current_display);
389
390
  }

391
392
393
394
395
396
397
  /**
   * Tests a view which is rendered after a form with a validation error.
   */
  public function testFormErrorWithExposedForm() {
    $this->drupalGet('views_test_data_error_form_page');
    $this->assertResponse(200);
    $form = $this->cssSelect('form.views-exposed-form');
398
    $this->assertNotEmpty($form, 'The exposed form element was found.');
399
    $this->assertRaw(t('Apply'), 'Ensure the exposed form is rendered before submitting the normal form.');
400
401
    $this->assertRaw('<div class="views-row">', 'Views result shown.');

402
    $this->drupalPostForm(NULL, [], t('Submit'));
403
404
    $this->assertResponse(200);
    $form = $this->cssSelect('form.views-exposed-form');
405
    $this->assertNotEmpty($form, 'The exposed form element was found.');
406
    $this->assertRaw(t('Apply'), 'Ensure the exposed form is rendered after submitting the normal form.');
407
408
409
    $this->assertRaw('<div class="views-row">', 'Views result shown.');
  }

410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
  /**
   * Tests the exposed form with a pager.
   */
  public function testExposedFilterPagination() {
    $this->drupalCreateContentType(['type' => 'post']);
    // Create some random nodes.
    for ($i = 0; $i < 5; $i++) {
      $this->drupalCreateNode(['type' => 'post']);
    }

    $this->drupalGet('test_exposed_form_pager');
    $this->getSession()->getPage()->fillField('type[]', 'post');
    $this->getSession()->getPage()->fillField('created[min]', '-1 month');
    $this->getSession()->getPage()->fillField('created[max]', '+1 month');

    // Ensure the filters can be applied.
    $this->getSession()->getPage()->pressButton('Apply');
    $this->assertFieldByName('type[]', 'post');
    $this->assertFieldByName('created[min]', '-1 month');
    $this->assertFieldByName('created[max]', '+1 month');

    // Ensure the filters are still applied after pressing next.
    $this->clickLink('Next ›');
    $this->assertFieldByName('type[]', 'post');
    $this->assertFieldByName('created[min]', '-1 month');
    $this->assertFieldByName('created[max]', '+1 month');
  }

merlinofchaos's avatar
merlinofchaos committed
438
}