eaa5aaa32f31f923e7834419dc8ed2b0eae6e806
[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\Tests\system\Functional\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 the exposed block functionality.
196    */
197   public function testExposedBlock() {
198     $this->drupalCreateContentType(['type' => 'page']);
199     $view = Views::getView('test_exposed_block');
200     $view->setDisplay('page_1');
201     $block = $this->drupalPlaceBlock('views_exposed_filter_block:test_exposed_block-page_1');
202     $this->drupalGet('test_exposed_block');
203
204     // Test there is an exposed form in a block.
205     $xpath = $this->buildXPathQuery('//div[@id=:id]/form/@id', [':id' => Html::getUniqueId('block-' . $block->id())]);
206     $result = $this->xpath($xpath);
207     $this->assertEquals(1, count($result));
208
209     // Test there is not an exposed form in the view page content area.
210     $xpath = $this->buildXPathQuery('//div[@class="view-content"]/form/@id', [':id' => Html::getUniqueId('block-' . $block->id())]);
211     $this->assertNoFieldByXpath($xpath, $this->getExpectedExposedFormId($view), 'No exposed form found in views content region.');
212
213     // Test there is only one views exposed form on the page.
214     $elements = $this->xpath('//form[@id=:id]', [':id' => $this->getExpectedExposedFormId($view)]);
215     $this->assertEqual(count($elements), 1, 'One exposed form block found.');
216
217     // Test that the correct option is selected after form submission.
218     $this->assertCacheContext('url');
219     $this->assertOptionSelected('edit-type', 'All');
220     foreach (['All', 'article', 'page'] as $argument) {
221       $this->drupalGet('test_exposed_block', ['query' => ['type' => $argument]]);
222       $this->assertCacheContext('url');
223       $this->assertOptionSelected('edit-type', $argument);
224     }
225   }
226
227   /**
228    * Test the input required exposed form type.
229    */
230   public function testInputRequired() {
231     $view = View::load('test_exposed_form_buttons');
232     $display = &$view->getDisplay('default');
233     $display['display_options']['exposed_form']['type'] = 'input_required';
234     $view->save();
235
236     $this->drupalGet('test_exposed_form_buttons');
237     $this->assertResponse(200);
238     $this->helperButtonHasLabel('edit-submit-test-exposed-form-buttons', t('Apply'));
239
240     // Ensure that no results are displayed.
241     $rows = $this->xpath("//div[contains(@class, 'views-row')]");
242     $this->assertEqual(count($rows), 0, 'No rows are displayed by default when no input is provided.');
243
244     $this->drupalGet('test_exposed_form_buttons', ['query' => ['type' => 'article']]);
245
246     // Ensure that results are displayed.
247     $rows = $this->xpath("//div[contains(@class, 'views-row')]");
248     $this->assertEqual(count($rows), 5, 'All rows are displayed by default when input is provided.');
249   }
250
251   /**
252    * Test the "on demand text" for the input required exposed form type.
253    */
254   public function testTextInputRequired() {
255     $view = Views::getView('test_exposed_form_buttons');
256     $display = &$view->storage->getDisplay('default');
257     $display['display_options']['exposed_form']['type'] = 'input_required';
258     // Set up the "on demand text".
259     // @see https://www.drupal.org/node/535868
260     $on_demand_text = 'Select any filter and click Apply to see results.';
261     $display['display_options']['exposed_form']['options']['text_input_required'] = $on_demand_text;
262     $display['display_options']['exposed_form']['options']['text_input_required_format'] = filter_default_format();
263     $view->save();
264
265     // Ensure that the "on demand text" is displayed when no exposed filters are
266     // applied.
267     $this->drupalGet('test_exposed_form_buttons');
268     $this->assertText('Select any filter and click Apply to see results.');
269
270     // Ensure that the "on demand text" is not displayed when an exposed filter
271     // is applied.
272     $this->drupalGet('test_exposed_form_buttons', ['query' => ['type' => 'article']]);
273     $this->assertNoText($on_demand_text);
274   }
275
276   /**
277    * Tests exposed forms with exposed sort and items per page.
278    */
279   public function testExposedSortAndItemsPerPage() {
280     for ($i = 0; $i < 50; $i++) {
281       $entity = EntityTest::create([]);
282       $entity->save();
283     }
284     $contexts = [
285       'languages:language_interface',
286       'entity_test_view_grants',
287       'theme',
288       'url.query_args',
289       'languages:language_content'
290     ];
291
292     $this->drupalGet('test_exposed_form_sort_items_per_page');
293     $this->assertCacheContexts($contexts);
294     $this->assertIds(range(1, 10, 1));
295
296     $this->drupalGet('test_exposed_form_sort_items_per_page', ['query' => ['sort_order' => 'DESC']]);
297     $this->assertCacheContexts($contexts);
298     $this->assertIds(range(50, 41, 1));
299
300     $this->drupalGet('test_exposed_form_sort_items_per_page', ['query' => ['sort_order' => 'DESC', 'items_per_page' => 25]]);
301     $this->assertCacheContexts($contexts);
302     $this->assertIds(range(50, 26, 1));
303
304     $this->drupalGet('test_exposed_form_sort_items_per_page', ['query' => ['sort_order' => 'DESC', 'items_per_page' => 25, 'offset' => 10]]);
305     $this->assertCacheContexts($contexts);
306     $this->assertIds(range(40, 16, 1));
307   }
308
309   /**
310    * Checks whether the specified ids are the ones displayed in the view output.
311    *
312    * @param int[] $ids
313    *   The ids to check.
314    *
315    * @return bool
316    *   TRUE if ids match, FALSE otherwise.
317    */
318   protected function assertIds(array $ids) {
319     $elements = $this->cssSelect('div.view-test-exposed-form-sort-items-per-page div.views-row span.field-content');
320     $actual_ids = [];
321     foreach ($elements as $element) {
322       $actual_ids[] = (int) $element->getText();
323     }
324
325     return $this->assertIdentical($ids, $actual_ids);
326   }
327
328   /**
329    * Returns a views exposed form ID.
330    *
331    * @param \Drupal\views\ViewExecutable $view
332    *   The view to create an ID for.
333    *
334    * @return string
335    *   The form ID.
336    */
337   protected function getExpectedExposedFormId(ViewExecutable $view) {
338     return Html::cleanCssIdentifier('views-exposed-form-' . $view->storage->id() . '-' . $view->current_display);
339   }
340
341   /**
342    * Tests a view which is rendered after a form with a validation error.
343    */
344   public function testFormErrorWithExposedForm() {
345     $this->drupalGet('views_test_data_error_form_page');
346     $this->assertResponse(200);
347     $form = $this->cssSelect('form.views-exposed-form');
348     $this->assertTrue($form, 'The exposed form element was found.');
349     $this->assertRaw(t('Apply'), 'Ensure the exposed form is rendered before submitting the normal form.');
350     $this->assertRaw('<div class="views-row">', 'Views result shown.');
351
352     $this->drupalPostForm(NULL, [], t('Submit'));
353     $this->assertResponse(200);
354     $form = $this->cssSelect('form.views-exposed-form');
355     $this->assertTrue($form, 'The exposed form element was found.');
356     $this->assertRaw(t('Apply'), 'Ensure the exposed form is rendered after submitting the normal form.');
357     $this->assertRaw('<div class="views-row">', 'Views result shown.');
358   }
359
360 }