You are here

Select2BoxesTests.php in Select2 Boxes 8

File

tests/src/FunctionalJavascript/Select2BoxesTests.php
View source
<?php

namespace Drupal\Tests\select2boxes\FunctionalJavascript;

use Drupal\taxonomy\Entity\Term;
use Drupal\taxonomy\Entity\Vocabulary;

/**
 * Class for testing Select2Boxes.
 *
 * @group Select2Boxes
 */
class Select2BoxesTests extends Select2BoxesTestsBase {

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();
    $this
      ->drupalLogin($this->user);
  }

  /**
   * Tests whether the widgets plugins exist and are accessible.
   *
   * @todo This test should be a kernel/unit test which runs much faster.
   */
  public function testWidgetsPlugins() {

    // Check if the plugin manager service exists.
    $this
      ->assertTrue(\Drupal::hasService('plugin.manager.field.widget'));

    /** @var \Drupal\Core\Field\WidgetPluginManager $plugin_manager */
    $plugin_manager = \Drupal::service('plugin.manager.field.widget');

    // Check each plugin if it has definition under a plugin manager service.
    foreach (static::$pluginIds as $widget) {
      $this
        ->assertTrue($plugin_manager
        ->hasDefinition($widget));
    }
  }

  /**
   * Check whether all widgets exist in the field widgets settings.
   */
  public function testWidgetsAdminExistence() {
    $page = $this
      ->getSession()
      ->getPage();
    $assert_session = $this
      ->assertSession();

    // Go the the "Manage Form Display" form.
    $this
      ->drupalGet('admin/structure/types/manage/select2boxes_test_content_type/form-display');

    // Check for entity reference field widgets.
    $page
      ->hasSelect('edit-fields-field-tags-type');
    $assert_session
      ->optionExists('edit-fields-field-tags-type', static::$pluginIds[1]);
    $assert_session
      ->optionExists('edit-fields-field-tags-type', static::$pluginIds[2]);

    // Check if the newly created field exists in the list.
    $page
      ->hasSelect('edit-fields-field-test-list-type');

    // Check for list field widgets.
    $assert_session
      ->optionExists('edit-fields-field-test-list-type', static::$pluginIds[0]);

    // Set the Select2Boxes widgets for both fields and submit the form.
    $assert_session
      ->elementExists('xpath', '//select[@name="fields[field_test_list][type]"]')
      ->setValue(static::$pluginIds[0]);
    $assert_session
      ->assertWaitOnAjaxRequest();
    $assert_session
      ->elementExists('xpath', '//select[@name="fields[field_tags][type]"]')
      ->setValue(static::$pluginIds[1]);
    $assert_session
      ->assertWaitOnAjaxRequest();
    $page
      ->pressButton('Save');

    // Check if the submission has been successful.
    $this
      ->assertSession()
      ->pageTextContains('Your settings have been saved.');
  }

  /**
   * Test single widget for entity reference fields.
   */
  public function testSingleWidget() {
    $page = $this
      ->getSession()
      ->getPage();
    $assert_session = $this
      ->assertSession();

    // Go the the "Manage Form Display" form.
    $this
      ->drupalGet('admin/structure/types/manage/select2boxes_test_content_type/form-display');

    // Set single widget for the Tags field.
    $assert_session
      ->elementExists('xpath', '//select[@name="fields[field_tags][type]"]')
      ->setValue(static::$pluginIds[1]);
    $assert_session
      ->assertWaitOnAjaxRequest();
    $page
      ->pressButton('Save');

    // Check if the submission has been successful.
    $this
      ->assertSession()
      ->pageTextContains('Your settings have been saved.');

    // Now let's check the widgets style on a node creation page.
    $this
      ->drupalGet('node/add/select2boxes_test_content_type');

    // Check if all required html attributes are existing for the entity
    // reference field.
    $select = $assert_session
      ->selectExists('edit-field-tags');
    $assert_session
      ->elementAttributeExists('css', '#edit-field-tags', 'data-jquery-once-autocomplete');
    $assert_session
      ->elementAttributeExists('css', '#edit-field-tags', 'data-select2-autocomplete-list-widget');
    $this
      ->assertTrue($select
      ->hasClass('select2-widget'));
  }

  /**
   * Test multiple widget for entity reference fields.
   */
  public function testMultipleWidget() {
    $page = $this
      ->getSession()
      ->getPage();
    $assert_session = $this
      ->assertSession();

    // Go the the "Manage Form Display" form.
    $this
      ->drupalGet('admin/structure/types/manage/select2boxes_test_content_type/form-display');

    // Set multiple widget for the Tags field.
    $assert_session
      ->elementExists('xpath', '//select[@name="fields[field_tags][type]"]')
      ->setValue(static::$pluginIds[2]);
    $assert_session
      ->assertWaitOnAjaxRequest();
    $page
      ->pressButton('Save');

    // Check if the submission has been successful.
    $this
      ->assertSession()
      ->pageTextContains('Your settings have been saved.');

    // Now let's check the node creation page.
    $this
      ->drupalGet('node/add/select2boxes_test_content_type');
    $select = $assert_session
      ->selectExists('edit-field-tags');

    // Check if all required html attributes are exist
    // for the entity reference field.
    $assert_session
      ->elementAttributeExists('css', '#edit-field-tags', 'data-jquery-once-autocomplete');
    $assert_session
      ->elementAttributeExists('css', '#edit-field-tags', 'data-select2-multiple');
    $assert_session
      ->elementAttributeExists('css', '#edit-field-tags', 'data-autocomplete-path');
    $assert_session
      ->elementAttributeExists('css', '#edit-field-tags', 'data-field-name');
    $this
      ->assertTrue($select
      ->hasClass('select2-widget'));
    $this
      ->assertTrue($select
      ->hasClass('select2-boxes-widget'));

    // Generate dummy terms.
    $terms = $this
      ->generateDummyTerms('tags', 10);

    // Generate one node for testing.
    $nodes = $this
      ->generateDummyContent(1);

    /** @var \Drupal\node\Entity\Node $node */
    $node = reset($nodes);
    $node
      ->set('field_tags', $terms[random_int(0, 9)]
      ->id())
      ->save();

    // Go to the node's edit page.
    $this
      ->drupalGet('node/' . $node
      ->id() . '/edit');

    // Check that the select element exists.
    $select = $assert_session
      ->selectExists('edit-field-tags');

    // Check that only the selected tag item has been rendered as a dropdown
    // option.
    $this
      ->assertCount(1, $this
      ->getOptions($select));
  }

  /**
   * Test widget for a list type of fields.
   */
  public function testListWidget() {
    $page = $this
      ->getSession()
      ->getPage();
    $assert_session = $this
      ->assertSession();

    // Go the the "Manage Form Display" form.
    $this
      ->drupalGet('admin/structure/types/manage/select2boxes_test_content_type/form-display');

    // Set list widget for the Test list field.
    $assert_session
      ->elementExists('xpath', '//select[@name="fields[field_test_list][type]"]')
      ->setValue(static::$pluginIds[0]);
    $assert_session
      ->assertWaitOnAjaxRequest();
    $page
      ->pressButton('Save');

    // Check if the submission has been successful.
    $this
      ->assertSession()
      ->pageTextContains('Your settings have been saved.');

    // Now let's check the node creation page.
    $this
      ->drupalGet('node/add/select2boxes_test_content_type');

    // Check that the select element exists.
    $select = $assert_session
      ->selectExists('edit-field-test-list');

    // Check if all required html attributes are exist
    // for the list field.
    $assert_session
      ->elementAttributeExists('css', '#edit-field-test-list', 'data-jquery-once-autocomplete');
    $assert_session
      ->elementAttributeExists('css', '#edit-field-test-list', 'data-select2-autocomplete-list-widget');
    $this
      ->assertTrue($select
      ->hasClass('select2-widget'));
  }

  /**
   * Test preloading functionality for the multiple entity reference widgets.
   */
  public function testPreloading() {
    $page = $this
      ->getSession()
      ->getPage();
    $assert_session = $this
      ->assertSession();

    // Firstly generate fake vocabulary terms.
    $this
      ->generateDummyTerms('tags', 10);

    // Go the the "Manage Form Display" form.
    $this
      ->drupalGet('admin/structure/types/manage/select2boxes_test_content_type/form-display');

    // Set multiple widget for the Tags field.
    $assert_session
      ->elementExists('xpath', '//select[@name="fields[field_tags][type]"]')
      ->setValue(static::$pluginIds[2]);
    $assert_session
      ->assertWaitOnAjaxRequest();
    $page
      ->pressButton('Save');

    // Check for the summary text about preloading option.
    $assert_session
      ->pageTextContains('Preloading disabled');

    // Open the settings form for the Tags field.
    $this
      ->click('input[name="field_tags_settings_edit"]');
    $assert_session
      ->assertWaitOnAjaxRequest();

    // Enable preloading via checking the checkbox field.
    $this
      ->click('input[name="fields[field_tags][settings_edit_form][third_party_settings][select2boxes][enable_preload]"]');
    $assert_session
      ->assertWaitOnAjaxRequest();

    // Set 5 rows to be preloaded.
    $page
      ->fillField('fields[field_tags][settings_edit_form][third_party_settings][select2boxes][preload_count]', '5');

    // Submit the settings form.
    $this
      ->click('input[name="field_tags_plugin_settings_update"]');
    $assert_session
      ->assertWaitOnAjaxRequest();

    // Check for summary text updates,
    // according to the specified number of preload entries.
    $assert_session
      ->pageTextContains('Number of preloaded entries: 5');

    // Submit the entity form display settings.
    $page
      ->pressButton('Save');

    // Check if the submission has been successful.
    $this
      ->assertSession()
      ->pageTextContains('Your settings have been saved.');

    // Go to the node's creation form.
    $this
      ->drupalGet('node/add/select2boxes_test_content_type');

    // Trigger the opening dropdown via click on the search input field.
    $this
      ->click('input[class="select2-search__field"]');
    $assert_session
      ->assertWaitOnAjaxRequest();

    // Find the list of results element on the page.
    $fake_select = $assert_session
      ->elementExists('css', '#select2-edit-field-tags-results');

    // Check if the number of results is equals to the 5 rows
    // (as was specified in the widget settings).
    $this
      ->assertCount(5, $fake_select
      ->findAll('xpath', '//li'));
  }

  /**
   * Test limited search option functionality.
   */
  public function testLimitedSearch() {
    $page = $this
      ->getSession()
      ->getPage();
    $assert_session = $this
      ->assertSession();

    // Go the the "Manage Form Display" form.
    $this
      ->drupalGet('admin/structure/types/manage/select2boxes_test_content_type/form-display');

    // Set list widget for the Test list field.
    $assert_session
      ->elementExists('xpath', '//select[@name="fields[field_test_list][type]"]')
      ->setValue(static::$pluginIds[0]);
    $assert_session
      ->assertWaitOnAjaxRequest();
    $page
      ->pressButton('Save');

    // Check if the submission has been successful.
    $this
      ->assertSession()
      ->pageTextContains('Your settings have been saved.');

    // Enable limited search option.
    $this
      ->drupalGet('admin/config/user-interface/select2boxes');

    // Specify minimum length search to a BIGGER value
    // than we have in our "Allowed values" settings for the field.
    $edit = [
      'limited_search' => '1',
      'minimum_search_length' => '4',
    ];
    $this
      ->submitForm($edit, 'Save configuration');
    $assert_session
      ->pageTextContains('The configuration options have been saved.');

    // Go to the node's creation form.
    $this
      ->drupalGet('node/add/select2boxes_test_content_type');

    // Trigger opening dropdown.
    $this
      ->getSession()
      ->executeScript("jQuery('select[name=\"field_test_list\"]').select2('open');");

    // Check for NON-existing search input field.
    $search_input = $assert_session
      ->elementExists('xpath', '//span[contains(@class, \'select2-search--dropdown\')]');
    $this
      ->assertNotNull($search_input);
    $this
      ->assertTrue($search_input
      ->hasClass('select2-search--hide'));
    $this
      ->drupalGet('admin/config/user-interface/select2boxes');

    // Specify minimum length search to the SAME value
    // than we have in our "Allowed values" settings for the field.
    $edit = [
      'limited_search' => '1',
      'minimum_search_length' => '3',
    ];
    $this
      ->submitForm($edit, 'Save configuration');
    $assert_session
      ->pageTextContains('The configuration options have been saved.');

    // Go to the node's creation form.
    $this
      ->drupalGet('node/add/select2boxes_test_content_type');

    // Trigger opening dropdown.
    $this
      ->getSession()
      ->executeScript("jQuery('select[name=\"field_test_list\"]').select2('open');");

    // Check for EXISTING search input field.
    $search_input = $assert_session
      ->elementExists('xpath', '//span[contains(@class, \'select2-search--dropdown\')]');
    $this
      ->assertFalse($search_input
      ->hasClass('select2-search--hide'));
  }

  /**
   * Test entity auto-creation with limited search enabled.
   */
  public function testEntityAutoCreationWithLimitedSearch() {
    $page = $this
      ->getSession()
      ->getPage();
    $assert_session = $this
      ->assertSession();
    $this
      ->drupalGet('admin/config/user-interface/select2boxes');
    $this
      ->submitForm([
      'limited_search' => '1',
      'minimum_search_length' => '4',
    ], 'Save configuration');
    $assert_session
      ->pageTextContains('The configuration options have been saved.');

    // Go the the "Manage Form Display" form.
    $this
      ->drupalGet('admin/structure/types/manage/select2boxes_test_content_type/form-display');

    // Set single widget for the Tags entity reference field.
    $assert_session
      ->elementExists('xpath', '//select[@name="fields[field_tags][type]"]')
      ->setValue(static::$pluginIds[1]);
    $assert_session
      ->assertWaitOnAjaxRequest();
    $page
      ->pressButton('Save');

    // Go to the node's creation form.
    $this
      ->drupalGet('node/add/select2boxes_test_content_type');

    // Trigger opening dropdown.
    $this
      ->getSession()
      ->executeScript("jQuery('select[name=\"field_tags\"]').select2('open');");

    // Check for EXISTING search input field.
    $search_input = $assert_session
      ->elementExists('xpath', '//span[contains(@class, \'select2-search--dropdown\')]');
    $this
      ->assertFalse($search_input
      ->hasClass('select2-search--hide'));
  }

  /**
   * Test unlimited preloading behavior.
   */
  public function testUnlimitedPreloading() {
    $page = $this
      ->getSession()
      ->getPage();
    $assert_session = $this
      ->assertSession();

    // Firstly generate fake vocabulary terms.
    $this
      ->generateDummyTerms('tags', 10);

    // Go the the "Manage Form Display" form.
    $this
      ->drupalGet('admin/structure/types/manage/select2boxes_test_content_type/form-display');

    // Set multiple widget for the Tags field.
    $assert_session
      ->elementExists('xpath', '//select[@name="fields[field_tags][type]"]')
      ->setValue(static::$pluginIds[2]);
    $assert_session
      ->assertWaitOnAjaxRequest();

    // Check for the summary text about preloading option.
    $assert_session
      ->pageTextContains('Preloading disabled');

    // Open the settings form for the Tags field.
    $this
      ->click('input[name="field_tags_settings_edit"]');
    $assert_session
      ->assertWaitOnAjaxRequest();

    // Enable preloading via checking the checkbox field.
    $this
      ->click('input[name="fields[field_tags][settings_edit_form][third_party_settings][select2boxes][enable_preload]"]');
    $assert_session
      ->assertWaitOnAjaxRequest();

    // Do not specify the preload count value!
    // Submit the settings form.
    $this
      ->click('input[name="field_tags_plugin_settings_update"]');
    $assert_session
      ->assertWaitOnAjaxRequest();

    // Check for summary text updates,
    // according to the NON-specified number of preload entries.
    $assert_session
      ->pageTextContains('Number of preloaded entries: all');

    // Submit the entity form display settings.
    $page
      ->pressButton('Save');

    // Check if the submission has been successful.
    $this
      ->assertSession()
      ->pageTextContains('Your settings have been saved.');

    // Go to the node's creation form.
    $this
      ->drupalGet('node/add/select2boxes_test_content_type');

    // Trigger the opening dropdown via click on the search input field.
    $this
      ->click('input[class="select2-search__field"]');
    $assert_session
      ->assertWaitOnAjaxRequest();

    // Find the list of results element on the page.
    $fake_select = $assert_session
      ->elementExists('css', '#select2-edit-field-tags-results');

    // Check if the number of results is equals to the 10 rows (as was
    // generated).
    $this
      ->assertCount(10, $fake_select
      ->findAll('xpath', '//li'));
  }

  /**
   * Test globally enabled select2 widgets.
   */
  public function testGlobalSelect2Widgets() {
    $assert_session = $this
      ->assertSession();

    // Enable select2 widgets globally.
    $this
      ->drupalGet('admin/config/user-interface/select2boxes');
    $this
      ->submitForm([
      'select2_global' => TRUE,
    ], 'Save configuration');
    $assert_session
      ->pageTextContains('The configuration options have been saved.');

    // Go the the "Manage Form Display" form.
    $this
      ->drupalGet('admin/structure/types/manage/select2boxes_test_content_type/form-display');

    // Get all <select> elements on a page.
    $selects = $assert_session
      ->elementExists('xpath', '//select');

    // Check if all of them are having appropriate class and attribute values.
    foreach ($selects as $select) {

      /** @var \Behat\Mink\Element\NodeElement $select */
      $this
        ->assertTrue($select
        ->hasClass('select2-widget'));
      $this
        ->assertTrue($select
        ->hasAttribute('data-jquery-once-autocomplete'));
      $this
        ->assertTrue($select
        ->hasAttribute('data-select2-autocomplete-list-widget'));
    }
    $this
      ->drupalGet('admin/config/user-interface/select2boxes');
    $this
      ->submitForm([
      'select2_global' => FALSE,
    ], 'Save configuration');
    $assert_session
      ->pageTextContains('The configuration options have been saved.');

    // Go the the "Manage Form Display" form.
    $this
      ->drupalGet('admin/structure/types/manage/select2boxes_test_content_type/form-display');

    // Get all <select> elements on a page.
    $selects = $assert_session
      ->elementExists('xpath', '//select');

    // Check if all of them are NOT having
    // appropriate class and attribute values.
    foreach ($selects as $select) {

      /** @var \Behat\Mink\Element\NodeElement $select */
      $this
        ->assertFalse($select
        ->hasClass('select2-widget'));
      $this
        ->assertFalse($select
        ->hasAttribute('data-jquery-once-autocomplete'));
      $this
        ->assertFalse($select
        ->hasAttribute('data-select2-autocomplete-list-widget'));
    }
  }

  /**
   * Test globally enabled select2 widgets with limited search.
   */
  public function testGlobalSelect2WidgetsWithLimitedSearch() {
    $assert_session = $this
      ->assertSession();
    $this
      ->drupalGet('admin/config/user-interface/select2boxes');
    $this
      ->submitForm([
      'select2_global' => TRUE,
      'limited_search' => TRUE,
      'minimum_search_length' => '3',
    ], 'Save configuration');
    $assert_session
      ->pageTextContains('The configuration options have been saved.');

    // Go the the "Manage Form Display" form.
    $this
      ->drupalGet('admin/structure/types/manage/select2boxes_test_content_type/form-display');

    // Trigger opening dropdown.
    $this
      ->getSession()
      ->executeScript("jQuery('select[name=\"fields[status][type]\"]').select2('open');");

    // Check for NON-existing search input field.
    $search_input = $assert_session
      ->elementExists('xpath', '//span[contains(@class, \'select2-search--dropdown\')]');
    $this
      ->assertTrue($search_input
      ->hasClass('select2-search--hide'));
  }

  /**
   * Test globally enabled select2 widgets with disabling it for admin pages.
   */
  public function testGlobalSelect2WidgetsWithAdminPagesDisabled() {
    $assert_session = $this
      ->assertSession();

    // Enable select2 widgets globally.
    $this
      ->drupalGet('admin/config/user-interface/select2boxes');
    $this
      ->submitForm([
      'select2_global' => TRUE,
    ], 'Save configuration');
    $assert_session
      ->pageTextContains('The configuration options have been saved.');

    // Go the the "Manage Form Display" form.
    $this
      ->drupalGet('admin/structure/types/manage/select2boxes_test_content_type/form-display');

    // Get all <select> elements on a page.
    $selects = $assert_session
      ->elementExists('xpath', '//select');

    // Check if all of them are having appropriate class and attribute values.
    foreach ($selects as $select) {

      /** @var \Behat\Mink\Element\NodeElement $select */
      $this
        ->assertTrue($select
        ->hasClass('select2-widget'));
      $this
        ->assertTrue($select
        ->hasAttribute('data-jquery-once-autocomplete'));
      $this
        ->assertTrue($select
        ->hasAttribute('data-select2-autocomplete-list-widget'));
    }

    // Disable select2 widgets for admin pages.
    $this
      ->drupalGet('admin/config/user-interface/select2boxes');
    $this
      ->submitForm([
      'disable_for_admin_pages' => TRUE,
    ], 'Save configuration');
    $assert_session
      ->pageTextContains('The configuration options have been saved.');

    // Go the the "Manage Form Display" form.
    $this
      ->drupalGet('admin/structure/types/manage/select2boxes_test_content_type/form-display');

    // Get all <select> elements on a page.
    $selects = $assert_session
      ->elementExists('xpath', '//select');

    // Check if all of them are NOT having
    // appropriate class and attribute values.
    foreach ($selects as $select) {

      /** @var \Behat\Mink\Element\NodeElement $select */
      $this
        ->assertFalse($select
        ->hasClass('select2-widget'));
      $this
        ->assertFalse($select
        ->hasAttribute('data-jquery-once-autocomplete'));
      $this
        ->assertFalse($select
        ->hasAttribute('data-select2-autocomplete-list-widget'));
    }
  }

  /**
   * Test entity auto-creation with multiple vocabularies.
   */
  public function testEntityAutoCreationWithMultipleVocabularies() {
    $page = $this
      ->getSession()
      ->getPage();
    $assert_session = $this
      ->assertSession();

    // Create new taxonomy vocabulary for testing.
    $voc = 'test_voc';
    Vocabulary::create([
      'vid' => $voc,
      'name' => $voc,
    ])
      ->save();

    // Check that the new taxonomy vocabulary has been created.
    $this
      ->assertNotNull(Vocabulary::load($voc));

    // Create new entity reference field field.
    $this
      ->drupalGet('admin/structure/types/manage/select2boxes_test_content_type/fields/add-field');
    $page
      ->selectFieldOption('edit-new-storage-type', 'field_ui:entity_reference:taxonomy_term');
    $page
      ->fillField('edit-label', 'Test term');
    $page
      ->pressButton('Save and continue');
    $page
      ->fillField('edit-field-name', 'test_term');
    $page
      ->pressButton('Save and continue');
    $page
      ->selectFieldOption('edit-cardinality', '-1');
    $page
      ->pressButton('Save field settings');
    $page
      ->checkField('settings[handler_settings][auto_create]');
    $page
      ->checkField("settings[handler_settings][target_bundles][{$voc}]");
    $assert_session
      ->assertWaitOnAjaxRequest();
    $page
      ->checkField('settings[handler_settings][target_bundles][tags]');
    $assert_session
      ->assertWaitOnAjaxRequest();
    $page
      ->fillField('settings[handler_settings][auto_create_bundle]', $voc);
    $page
      ->pressButton('Save settings');

    // Go the the "Manage Form Display" form.
    $this
      ->drupalGet('admin/structure/types/manage/select2boxes_test_content_type/form-display');
    $assert_session
      ->elementExists('xpath', '//select[@name="fields[field_test_term][type]"]')
      ->setValue(static::$pluginIds[2]);
    $assert_session
      ->assertWaitOnAjaxRequest();
    $page
      ->pressButton('Save');

    // Go to the node's creation form.
    $this
      ->drupalGet('node/add/select2boxes_test_content_type');
    $page
      ->fillField('title[0][value]', 'TESTTITLE');
    $this
      ->getSession()
      ->executeScript("jQuery('#edit-field-test-term').next().find('input.select2-search__field').val('TESTTERM').trigger('keyup');");
    $assert_session
      ->assertWaitOnAjaxRequest();
    $page
      ->selectFieldOption('field_test_term[]', 'TESTTERM');
    $assert_session
      ->assertWaitOnAjaxRequest();
    $page
      ->pressButton('Save');
    $terms = Term::loadMultiple();
    $this
      ->assertNotEmpty($terms);

    /** @var \Drupal\taxonomy\Entity\Term $term */
    $term = reset($terms);
    $this
      ->assertEquals($voc, $term
      ->bundle());
  }

}

Classes

Namesort descending Description
Select2BoxesTests Class for testing Select2Boxes.