clean install

This commit is contained in:
matze committed 2024-12-10 15:08:16 +01:00
commit e14eb2d8fd
31193 files changed
+3555714

No files matched your search

@@ -0,0 +1,93 @@
<?php
namespace Drupal\Tests\entity_browser\Functional;
use Drupal\Tests\BrowserTestBase;
/**
* Tests the config UI for adding and editing entity browsers.
*
* @group entity_browser
*
* @package Drupal\Tests\entity_browser\FunctionalJavascript
*/
class ConfigAccessTest extends BrowserTestBase {
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = [
'entity_browser',
'block',
'node',
'taxonomy',
'views',
];
/**
* The test administrative user.
*
* @var \Drupal\user\UserInterface
*/
protected $adminUser;
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->drupalPlaceBlock('local_tasks_block');
$this->drupalPlaceBlock('local_actions_block');
$this->adminUser = $this->drupalCreateUser([
'administer entity browsers',
]);
}
/**
* Tests Access to EntityBrowserEditForm.
*/
public function testEntityBrowserEditFormAccess() {
// Test that anonymous user can't access admin pages.
$this->drupalGet('/admin/config/content/entity_browser');
$this->assertSession()->statusCodeEquals(403);
$this->drupalGet('/admin/config/content/entity_browser/add');
$this->assertSession()->statusCodeEquals(403);
// Test that user with "administer entity browsers" permission can access
// admin pages.
$this->drupalLogin($this->adminUser);
$this->drupalGet('/admin/config/content/entity_browser');
$this->assertSession()->statusCodeEquals(200);
$this->assertSession()->responseContains('There are no entity browser entities yet.');
$this->clickLink('Add Entity browser');
$this->assertSession()->fieldExists('label')->setValue('Test entity browser');
$this->assertSession()->fieldExists('name')->setValue('test_entity_browser');
$this->assertSession()->buttonExists('Save')->press();
$this->assertSession()->addressEquals('/admin/config/content/entity_browser/test_entity_browser/widgets');
$this->drupalLogout();
$this->drupalGet('/admin/config/content/entity_browser/test_entity_browser');
$this->assertSession()->statusCodeEquals(404);
$this->drupalLogin($this->adminUser);
$this->drupalGet('/admin/config/content/entity_browser');
$this->clickLink('Delete');
$this->assertSession()->responseContains('This action cannot be undone.');
$this->submitForm([], 'Delete Entity Browser');
$this->assertSession()->responseContains('Entity browser <em class="placeholder">Test entity browser</em> was deleted.');
$this->assertSession()->responseContains('There are no entity browser entities yet.');
$this->drupalLogout();
}
}
@@ -0,0 +1,78 @@
<?php
namespace Drupal\Tests\entity_browser\Functional;
use Drupal\file\Entity\File;
use Drupal\Tests\BrowserTestBase;
use Drupal\Tests\TestFileCreationTrait;
/**
* Tests the entity browser UI.
*
* @group entity_browser
*/
class EntityBrowserUITest extends BrowserTestBase {
use TestFileCreationTrait;
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = [
'entity_browser_test',
'views',
'block',
];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* Tests entity browser UI.
*/
public function testEntityBrowserUI() {
$account = $this->drupalCreateUser([
'administer entity browsers',
'access test_entity_browser_iframe entity browser pages',
]);
$this->drupalLogin($account);
// Go to the entity browser iframe link.
$this->drupalGet('/entity-browser/iframe/test_entity_browser_iframe');
$this->assertSession()->responseContains('Select');
$this->drupalGet('/admin/config/content/entity_browser/test_entity_browser_iframe/widgets');
$edit = [
'table[871dbf77-012e-41cb-b32a-ada353d2de35][form][submit_text]' => 'Different',
];
$this->submitForm($edit, 'Save');
$this->drupalGet('/entity-browser/iframe/test_entity_browser_iframe');
$this->assertSession()->responseContains('Different');
}
/**
* Tests entity browser token support for upload widget.
*/
public function testEntityBrowserToken() {
$this->container->get('module_installer')->install(['token', 'file']);
$account = $this->drupalCreateUser([
'access test_entity_browser_token entity browser pages',
]);
$this->drupalLogin($account);
// Go to the entity browser iframe link.
$this->drupalGet('/entity-browser/iframe/test_entity_browser_token');
$image = current($this->getTestFiles('image'));
$edit = [
'files[upload][]' => $this->container->get('file_system')->realpath($image->uri),
];
$this->submitForm($edit, 'Select files');
$file = File::load(1);
// Test entity browser token that has upload location configured to
// public://[current-user:account-name]/.
$this->assertEquals($file->getFileUri(), 'public://' . $account->getAccountName() . '/' . $file->getFilename(), 'Image has the correct uri.');
}
}
@@ -0,0 +1,86 @@
<?php
namespace Drupal\Tests\entity_browser\Functional;
use Drupal\entity_browser\Element\EntityBrowserElement;
use Drupal\Tests\BrowserTestBase;
/**
* Tests the entity browser form element.
*
* @group entity_browser
*/
class FormElementTest extends BrowserTestBase {
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = ['entity_browser_test', 'node', 'views'];
/**
* Test nodes.
*
* @var \Drupal\node\NodeInterface[]
*/
protected $nodes;
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->container
->get('entity_type.manager')
->getStorage('node_type')
->create([
'type' => 'page',
'name' => 'page',
])->save();
$this->nodes[] = $this->drupalCreateNode();
$this->nodes[] = $this->drupalCreateNode();
}
/**
* Tests the Entity browser form element.
*/
public function testFormElement() {
// See \Drupal\entity_browser_test\Form\FormElementTest.
$this->drupalGet('/test-element');
$this->assertSession()->linkExists('Select entities', 0, 'Trigger link found.');
$ids = [
$this->nodes[0]->getEntityTypeId() . ':' . $this->nodes[0]->id(),
$this->nodes[1]->getEntityTypeId() . ':' . $this->nodes[1]->id(),
];
$ids = implode(' ', $ids);
$this->assertSession()->hiddenFieldExists("fancy_entity_browser[entity_ids]")->setValue($ids);
$this->assertSession()->buttonExists('Submit')->press();
$expected = 'Selected entities: ' . $this->nodes[0]->label() . ', ' . $this->nodes[1]->label();
$this->assertSession()->responseContains($expected);
$default_entity = $this->nodes[0]->getEntityTypeId() . ':' . $this->nodes[0]->id();
$this->drupalGet('/test-element', ['query' => ['default_entity' => $default_entity, 'selection_mode' => EntityBrowserElement::SELECTION_MODE_EDIT]]);
$this->assertSession()->linkExists('Select entities', 0, 'Trigger link found.');
$this->assertSession()->hiddenFieldValueEquals("fancy_entity_browser[entity_ids]", $default_entity);
$hidden_field = $this->assertSession()->hiddenFieldExists("fancy_entity_browser[entity_ids]");
$new_value = 'node:' . $this->nodes[1]->id() . ' node:' . $this->nodes[0]->id();
$hidden_field->setValue($new_value);
$this->submitForm([], 'Submit');
$expected = 'Selected entities: ' . $this->nodes[1]->label() . ', ' . $this->nodes[0]->label();
$this->assertSession()->responseContains($expected);
}
}
@@ -0,0 +1,382 @@
<?php
namespace Drupal\Tests\entity_browser\FunctionalJavascript;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\entity_browser\Element\EntityBrowserElement;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\Tests\ckeditor5\Traits\CKEditor5TestTrait;
use Drupal\user\Entity\Role;
/**
* Tests the Cardinality handling.
*
* @group entity_browser
*/
class CardinalityTest extends EntityBrowserWebDriverTestBase {
use CKEditor5TestTrait;
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = [
'entity_browser_test',
'embed',
'entity_embed',
'entity_browser_entity_embed_test',
'inline_entity_form',
'entity_browser_ief_test',
];
/**
* {@inheritdoc}
*/
public function setUp(): void {
parent::setUp();
/** @var \Drupal\user\RoleInterface $role */
$role = Role::load('authenticated');
$this->grantPermissions($role, [
'access cardinality entity browser pages',
'bypass node access',
'administer node form display',
'access content',
]);
}
/**
* Tests Entity Reference widget.
*/
public function testEntityReferenceWidget() {
// Create an entity_reference field to test the widget.
$field_storage = FieldStorageConfig::create([
'field_name' => 'field_fellowship',
'type' => 'entity_reference',
'entity_type' => 'node',
'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
'settings' => [
'target_type' => 'node',
],
]);
$field_storage->save();
$field = FieldConfig::create([
'field_name' => 'field_fellowship',
'entity_type' => 'node',
'bundle' => 'article',
'label' => 'Referenced articles',
'settings' => [
'handler' => 'default:node',
'handler_settings' => [
'target_bundles' => [
'article' => 'article',
'shark' => 'shark',
'jet' => 'jet',
],
],
],
]);
$field->save();
/** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display */
$form_display = $this->container->get('entity_type.manager')
->getStorage('entity_form_display')
->load('node.article.default');
$form_display->setComponent('field_fellowship', [
'type' => 'entity_browser_entity_reference',
'settings' => [
'entity_browser' => 'cardinality',
'open' => TRUE,
'field_widget_edit' => TRUE,
'field_widget_remove' => TRUE,
'field_widget_replace' => TRUE,
'selection_mode' => EntityBrowserElement::SELECTION_MODE_APPEND,
'field_widget_display' => 'label',
'field_widget_display_settings' => [],
],
])->save();
$gollum = $this->createNode(['type' => 'shark', 'title' => 'Gollum']);
$aragorn = $this->createNode(['type' => 'jet', 'title' => 'Aragorn']);
$gandolf = $this->createNode(['type' => 'article', 'title' => 'Gandolf']);
$legolas = $this->createNode(['type' => 'article', 'title' => 'Legolas']);
$boromir = $this->createNode(['type' => 'article', 'title' => 'Boromir']);
// Test the cardinality handling.
$role = Role::load('authenticated');
$this->grantPermissions($role, [
'access cardinality entity browser pages',
'bypass node access',
'administer node form display',
]);
FieldStorageConfig::load('node.field_fellowship')
->setCardinality(2)
->save();
// Without using field cardinality, the view should contain checkboxes.
// Set view to use field cardinality.
$this->config('views.view.bundle_filter_exposed')
->set('display.default.display_options.fields.entity_browser_select.use_field_cardinality', FALSE)
->save();
$this->drupalGet('/node/add/article');
$this->assertSession()->fieldExists('title[0][value]')->setValue('Le Seigneur des anneaux');
$this->openIframe();
$gollum_checkbox = $this->assertCheckboxExistsByValue('node:' . $gollum->id());
$gollum_checkbox->check();
$aragorn_checkbox = $this->assertCheckboxExistsByValue('node:' . $aragorn->id());
$aragorn_checkbox->check();
$this->assertTrue($gollum_checkbox->isChecked());
$this->assertTrue($aragorn_checkbox->isChecked());
// If using field cardinality and field cardinality is greater than 1 then
// there should be still checkboxes.
$this->config('views.view.bundle_filter_exposed')
->set('display.default.display_options.fields.entity_browser_select.use_field_cardinality', TRUE)
->save();
$this->drupalGet('/node/add/article');
$this->openIframe();
$gollum_checkbox = $this->assertCheckboxExistsByValue('node:' . $gollum->id());
$aragorn_checkbox = $this->assertCheckboxExistsByValue('node:' . $aragorn->id());
$gandolf_checkbox = $this->assertCheckboxExistsByValue('node:' . $gandolf->id());
$this->assertCheckboxExistsByValue('node:' . $legolas->id());
$this->assertCheckboxExistsByValue('node:' . $boromir->id());
// If we attempt to select 3 nodes, Entity Browser should prevent it and
// return an error message.
$gollum_checkbox->check();
$aragorn_checkbox->check();
$gandolf_checkbox->check();
$this->assertSession()->buttonExists('Select entities')->press();
$this->assertSession()->pageTextContains('You can only select up to 2 items');
// If we change the cardinality to 1, we should have radios.
FieldStorageConfig::load('node.field_fellowship')
->setCardinality(1)
->save();
$this->drupalGet('/node/add/article');
$this->openIframe();
$gollum_radio = $this->assertRadioExistsByValue('node:' . $gollum->id());
$gollum_radio->click();
$this->assertSession()->buttonExists('Select entities')->press();
$this->assertSession()->assertWaitOnAjaxRequest();
$this->getSession()->switchToIFrame();
if (!$this->coreVersion('10.2')) {
$this->assertSession()->assertWaitOnAjaxRequest();
}
// Assert the selected entity.
$this->assertSession()->pageTextContains('Gollum');
// Attempt to select more than one element.
$this->assertSession()->buttonExists('Replace')->press();
$this->waitForAjaxToFinish();
$this->getSession()->switchToIFrame('entity_browser_iframe_cardinality');
$gollum_radio = $this->assertRadioExistsByValue('node:' . $gollum->id());
$gollum_radio->click();
$gandolf_radio = $this->assertRadioExistsByValue('node:' . $gandolf->id());
$gandolf_radio->click();
$this->assertFalse($gollum_radio->isSelected());
$this->assertTrue($gandolf_radio->isSelected());
$this->assertSession()->buttonExists('Select entities')->press();
$this->getSession()->switchToIFrame();
$this->waitForAjaxToFinish();
// Assert the selected entity.
$this->assertSession()->pageTextContains('Gandolf');
$this->assertSession()->pageTextNotContains('Gollum');
$this->assertSession()->buttonExists('Replace')->press();
$this->waitForAjaxToFinish();
$this->getSession()->switchToIFrame('entity_browser_iframe_cardinality');
// Test that cardinality setting persists when using exposed filters form,
// When applying the exposed filters, the radios should persist.
$this->assertSession()->selectExists('Type')->selectOption('jet');
$this->assertSession()->buttonExists('Apply')->press();
$this->assertSession()->assertWaitOnAjaxRequest();
$this->assertRadioExistsByValue('node:' . $aragorn->id());
$this->assertRadioNotExistsByValue('node:' . $legolas->id());
$this->assertSession()->selectExists('Type')->selectOption('shark');
$this->assertSession()->buttonExists('Apply')->press();
$this->assertSession()->assertWaitOnAjaxRequest();
$this->assertRadioExistsByValue('node:' . $gollum->id());
$this->assertRadioNotExistsByValue('node:' . $aragorn->id());
}
/**
* Tests cardinality functionality using Entity Embed button.
*/
public function testEntityEmbed() {
$this->config('entity_browser.browser.bundle_filter')
->set('widgets.b882a89d-9ce4-4dfe-9802-62df93af232a.settings.view', 'bundle_filter_exposed')
->save();
$role = Role::load('authenticated');
$this->grantPermissions($role, [
'access content',
'use text format full_html',
'create test_entity_embed content',
'access bundle_filter entity browser pages',
]);
FieldStorageConfig::load('node.field_nodes')
->setCardinality(1)
->save();
$westley = $this->createNode(['type' => 'shark', 'title' => 'Westley']);
$buttercup = $this->createNode(['type' => 'jet', 'title' => 'Buttercup']);
$humperdinck = $this->createNode(['type' => 'article', 'title' => 'Humperdinck']);
$this->drupalGet('/node/add/test_entity_embed');
$this->waitForEditor();
$this->pressEditorButton('Bundle Filter Test Embed');
$this->assertSession()->waitForElementVisible('xpath', "//iframe[contains(@name, 'entity_browser_iframe_bundle_filter')]", 3000);
$this->getSession()->switchToIFrame('entity_browser_iframe_bundle_filter');
$this->assertSession()->waitForElementVisible('xpath', "//div[contains(@class, 'views-exposed-form')]");
// Without use_field_cardinality set, there should be checkboxes, the default.
$this->assertCheckBoxExistsByValue('node:' . $westley->id());
$this->assertCheckBoxExistsByValue('node:' . $buttercup->id());
$this->assertCheckBoxNotExistsByValue('node:' . $humperdinck->id());
// Set view to use field cardinality.
$this->config('views.view.bundle_filter_exposed')
->set('display.default.display_options.fields.entity_browser_select.use_field_cardinality', TRUE)
->save();
$this->drupalGet('/node/add/test_entity_embed');
$this->waitForEditor();
$this->pressEditorButton('Bundle Filter Test Embed');
$this->assertSession()->waitForElementVisible('xpath', "//iframe[contains(@name, 'entity_browser_iframe_bundle_filter')]", 3000);
$this->getSession()->switchToIFrame('entity_browser_iframe_bundle_filter');
$this->assertSession()->waitForElementVisible('xpath', "//div[contains(@class, 'views-exposed-form')]");
// With use_field_cardinality set to true, there should be radios, since
// cardinality on entity embed is always 1.
$this->assertRadioExistsByValue('node:' . $westley->id());
$this->assertRadioExistsByValue('node:' . $buttercup->id());
$this->assertRadioNotExistsByValue('node:' . $humperdinck->id());
// Test that cardinality setting persists when using exposed filters form.
// When applying the exposed filters, the radios should persist.
$this->assertSession()->selectExists('Type')->selectOption('jet');
$this->assertSession()->buttonExists('Apply')->press();
$this->assertSession()->assertWaitOnAjaxRequest();
$this->assertRadioNotExistsByValue('node:' . $westley->id());
$this->assertRadioExistsByValue('node:' . $buttercup->id());
$this->assertRadioNotExistsByValue('node:' . $humperdinck->id());
$this->assertSession()->selectExists('Type')->selectOption('shark');
$this->assertSession()->buttonExists('Apply')->press();
$this->assertSession()->assertWaitOnAjaxRequest();
$this->assertRadioExistsByValue('node:' . $westley->id());
$this->assertRadioNotExistsByValue('node:' . $buttercup->id());
$this->assertRadioNotExistsByValue('node:' . $humperdinck->id());
}
/**
* Tests cardinality functionality using Inline Entity Form.
*/
public function testInlineEntityForm() {
/** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display */
$form_display = $this->container->get('entity_type.manager')
->getStorage('entity_form_display')
->load('node.ief_content.default');
$field_nodes = $form_display->getComponent('field_nodes');
$field_nodes['third_party_settings']['entity_browser_entity_form']['entity_browser_id'] = 'cardinality';
$form_display->setComponent('field_nodes', $field_nodes);
$form_display->save();
// Set auto open to TRUE on the entity browser.
$entity_browser = $this->container->get('entity_type.manager')
->getStorage('entity_browser')
->load('cardinality');
$display_configuration = $entity_browser->get('display_configuration');
$display_configuration['auto_open'] = TRUE;
$entity_browser->set('display_configuration', $display_configuration);
$entity_browser->save();
$vizzini = $this->createNode(['type' => 'shark', 'title' => 'Vizzini']);
$inigo = $this->createNode(['type' => 'jet', 'title' => 'Inigo']);
$miracle_max = $this->createNode(['type' => 'article', 'title' => 'Miracle Max']);
$this->drupalGet('node/add/ief_content');
$page = $this->getSession()->getPage();
$page->pressButton('Add existing node');
$this->assertSession()->assertWaitOnAjaxRequest();
$this->getSession()->switchToIFrame('entity_browser_iframe_cardinality');
// Without use_field_cardinality set, there should be checkboxes, the default.
$this->assertCheckBoxExistsByValue('node:' . $vizzini->id());
$this->assertCheckBoxExistsByValue('node:' . $inigo->id());
$this->assertCheckBoxNotExistsByValue('node:' . $miracle_max->id());
$view = $this->config('views.view.bundle_filter_exposed');
$field = $view->get('display.default.display_options.fields.entity_browser_select', TRUE);
$field['use_field_cardinality'] = TRUE;
$view->set('display.default.display_options.fields.entity_browser_select', $field);
$view->save();
FieldStorageConfig::load('node.field_nodes')
->setCardinality(1)
->save();
$this->drupalGet('node/add/ief_content');
$page = $this->getSession()->getPage();
$page->pressButton('Add existing node');
$this->assertSession()->assertWaitOnAjaxRequest();
$this->getSession()->switchToIFrame('entity_browser_iframe_cardinality');
// With use_field_cardinality set to true, and cardinality set to 1,
// there should be radios.
$this->assertRadioExistsByValue('node:' . $vizzini->id());
$this->assertRadioExistsByValue('node:' . $inigo->id());
$this->assertRadioNotExistsByValue('node:' . $miracle_max->id());
// Test that cardinality setting persists when using exposed filters form.
// When applying the exposed filters, the radios should persist.
$this->assertSession()->selectExists('Type')->selectOption('jet');
$this->assertSession()->buttonExists('Apply')->press();
$this->assertSession()->assertWaitOnAjaxRequest();
$this->assertRadioNotExistsByValue('node:' . $vizzini->id());
$this->assertRadioExistsByValue('node:' . $inigo->id());
$this->assertRadioNotExistsByValue('node:' . $miracle_max->id());
$this->assertSession()->selectExists('Type')->selectOption('shark');
$this->assertSession()->buttonExists('Apply')->press();
$this->assertSession()->assertWaitOnAjaxRequest();
$this->assertRadioExistsByValue('node:' . $vizzini->id());
$this->assertRadioNotExistsByValue('node:' . $inigo->id());
$this->assertRadioNotExistsByValue('node:' . $miracle_max->id());
}
/**
* Helper function for repetitive task.
*
* @throws \Behat\Mink\Exception\ElementNotFoundException
*/
protected function openIframe() {
$open_iframe_link = $this->assertSession()
->elementExists('css', 'a[data-drupal-selector="edit-field-fellowship-entity-browser-entity-browser-link"]');
$open_iframe_link->click();
$this->getSession()->switchToIFrame('entity_browser_iframe_cardinality');
}
}
@@ -0,0 +1,349 @@
<?php
namespace Drupal\Tests\entity_browser\FunctionalJavascript;
use Drupal\entity_browser\Entity\EntityBrowser;
use Drupal\FunctionalJavascriptTests\WebDriverTestBase;
/**
* Tests the config UI for adding and editing entity browsers.
*
* @group entity_browser
*
* @package Drupal\Tests\entity_browser\FunctionalJavascript
*/
class ConfigurationTest extends WebDriverTestBase {
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = [
'entity_browser',
'entity_browser_entity_form',
'entity_browser_test_configuration',
'block',
'node',
'taxonomy',
'views',
'token',
];
/**
* The test administrative user.
*
* @var \Drupal\user\UserInterface
*/
protected $adminUser;
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->drupalPlaceBlock('local_tasks_block');
$this->drupalPlaceBlock('local_actions_block');
$this->drupalCreateContentType(['type' => 'foo', 'name' => 'Foo']);
$this->adminUser = $this->drupalCreateUser([
'administer entity browsers',
]);
}
/**
* Tests EntityBrowserEditForm.
*/
public function testEntityBrowserEditForm() {
$this->drupalLogin($this->adminUser);
$this->drupalGet('/admin/config/content/entity_browser');
$this->assertSession()->responseNotContains('Access denied. You must log in to view this page.');
$this->assertSession()->responseContains('There are no entity browser entities yet.');
$this->clickLink('Add Entity browser');
$this->assertSession()->fieldExists('label')->setValue('Test entity browser');
$this->getSession()->executeScript("jQuery('.visually-hidden, .hidden').removeClass('visually-hidden hidden');");
$this->assertSession()->fieldExists('name')->setValue('test_entity_browser');
$this->assertSession()->selectExists('display')->selectOption('modal');
// Make sure fields in details elements are visible.
$this->getSession()->executeScript("jQuery('details').attr('open', 'open');");
$this->assertSession()->fieldExists('display_configuration[width]')->setValue('700');
$this->assertSession()->fieldExists('display_configuration[height]')->setValue('300');
$this->assertSession()->fieldExists('display_configuration[link_text]')->setValue('Select some entities');
$this->assertSession()->selectExists('widget_selector')->selectOption('tabs');
$this->assertSession()->selectExists('selection_display')->selectOption('no_display');
$this->submitForm([], 'Save');
$this->assertSession()->pageTextContains('The entity browser Test entity browser has been added. Now you may configure the widgets you would like to use.');
$this->assertSession()->addressEquals('/admin/config/content/entity_browser/test_entity_browser/widgets');
$this->assertSession()->selectExists('widget');
$this->clickLink('General Settings');
$this->assertSession()->addressEquals('/admin/config/content/entity_browser/test_entity_browser/edit');
$entity_browser = EntityBrowser::load('test_entity_browser');
$this->assertEquals('modal', $entity_browser->display);
$this->assertEquals('tabs', $entity_browser->widget_selector);
$this->assertEquals('no_display', $entity_browser->selection_display);
$display_configuration = $entity_browser->getDisplay()->getConfiguration();
$this->assertEquals('700', $display_configuration['width']);
$this->assertEquals('300', $display_configuration['height']);
$this->assertEquals('Select some entities', $display_configuration['link_text']);
$this->assertSession()->fieldValueEquals('display_configuration[width]', '700');
$this->assertSession()->fieldValueEquals('display_configuration[height]', '300');
$this->assertSession()->fieldValueEquals('display_configuration[link_text]', 'Select some entities');
$this->assertSession()->selectExists('display')->selectOption('iframe');
$this->assertSession()->assertWaitOnAjaxRequest();
$this->assertSession()->fieldExists('display_configuration[auto_open]')->check();
$this->assertSession()->fieldExists('display_configuration[width]')->setValue('100');
$this->assertSession()->fieldExists('display_configuration[height]')->setValue('100');
$this->assertSession()->fieldExists('display_configuration[link_text]')->setValue('All animals are created equal');
$this->submitForm([], 'Save');
$this->assertSession()->addressEquals('/admin/config/content/entity_browser/test_entity_browser/edit');
$this->assertSession()->pageTextContains('The entity browser Test entity browser has been updated.');
$entity_browser = EntityBrowser::load('test_entity_browser');
$this->assertEquals('iframe', $entity_browser->display);
$this->assertEquals('tabs', $entity_browser->widget_selector);
$this->assertEquals('no_display', $entity_browser->selection_display);
$display_configuration = $entity_browser->getDisplay()->getConfiguration();
$this->assertEquals('100', $display_configuration['width']);
$this->assertEquals('100', $display_configuration['height']);
$this->assertEquals('All animals are created equal', $display_configuration['link_text']);
$this->assertEquals(TRUE, $display_configuration['auto_open']);
$this->assertSession()->fieldExists('display_configuration[width]');
$this->assertSession()->fieldValueEquals('display_configuration[width]', '100');
$this->assertSession()->fieldValueEquals('display_configuration[height]', '100');
$this->assertSession()->fieldValueEquals('display_configuration[link_text]', 'All animals are created equal');
$this->assertSession()->checkboxChecked('display_configuration[auto_open]');
$this->assertSession()->selectExists('display')->selectOption('standalone');
$this->assertSession()->assertWaitOnAjaxRequest();
$this->assertSession()->fieldExists('display_configuration[path]')->setValue('/all-animals');
$this->submitForm([], 'Save');
$this->assertSession()->addressEquals('/admin/config/content/entity_browser/test_entity_browser/edit');
$this->assertSession()->pageTextContains('The entity browser Test entity browser has been updated.');
$this->clickLink('General Settings');
$this->assertSession()->addressEquals('/admin/config/content/entity_browser/test_entity_browser/edit');
$this->getSession()->executeScript("jQuery('details').attr('open', 'open');");
$entity_browser = EntityBrowser::load('test_entity_browser');
$this->assertEquals('standalone', $entity_browser->display);
$display_configuration = $entity_browser->getDisplay()->getConfiguration();
$this->assertEquals('/all-animals', $display_configuration['path']);
$this->assertSession()->fieldValueEquals('display_configuration[path]', '/all-animals');
// Test validation of leading forward slash.
$this->assertSession()->fieldExists('display_configuration[path]')->setValue('no-forward-slash');
$this->submitForm([], 'Save');
$this->assertSession()->responseContains('The Path field must begin with a forward slash.');
$this->assertSession()->fieldExists('display_configuration[path]')->setValue('/all-animals');
$this->submitForm([], 'Save');
$this->assertSession()->pageTextContains('The entity browser Test entity browser has been updated.');
$this->getSession()->executeScript("jQuery('details').attr('open', 'open');");
// Test ajax update of display settings.
$this->assertSession()->selectExists('display')->selectOption('iframe');
$this->assertSession()->assertWaitOnAjaxRequest();
$this->assertSession()->fieldExists('display_configuration[width]');
$this->assertSession()->responseContains('Width of the iFrame');
$this->assertSession()->selectExists('display')->selectOption('standalone');
$this->assertSession()->assertWaitOnAjaxRequest();
$this->assertSession()->fieldExists('display_configuration[path]');
$this->assertSession()->responseContains('The path at which the browser will be accessible.');
$this->assertSession()->selectExists('display')->selectOption('modal');
$this->assertSession()->assertWaitOnAjaxRequest();
$this->assertSession()->fieldExists('display_configuration[width]');
$this->assertSession()->responseContains('Width of the modal');
// Test ajax update of Selection display plugin settings.
$this->assertSession()->selectExists('selection_display')->selectOption('multi_step_display');
$this->assertSession()->assertWaitOnAjaxRequest();
$this->assertSession()->fieldExists('selection_display_configuration[select_text]');
$this->assertSession()->fieldExists('selection_display_configuration[selection_hidden]');
$this->assertSession()->selectExists('selection_display_configuration[entity_type]');
$this->assertSession()->selectExists('selection_display_configuration[display]')->selectOption('rendered_entity');
$this->assertSession()->assertWaitOnAjaxRequest();
$this->assertSession()->fieldExists('selection_display_configuration[display_settings][view_mode]');
$this->assertSession()->responseContains('Select view mode to be used when rendering entities.');
// Test ajax update of Multi step selection display "Entity display plugin".
$this->assertSession()->selectExists('selection_display_configuration[display]')->selectOption('label');
$this->assertSession()->assertWaitOnAjaxRequest();
$this->assertSession()->fieldNotExists('selection_display_configuration[display_settings][view_mode]');
$this->assertSession()->selectExists('selection_display_configuration[display]')->selectOption('rendered_entity');
$this->assertSession()->assertWaitOnAjaxRequest();
$this->assertSession()->fieldExists('selection_display_configuration[display_settings][view_mode]');
$this->assertSession()->responseContains('Select view mode to be used when rendering entities.');
// Test ajax update of Multi step selection display "Entity type".
$entity_type = $this->assertSession()->selectExists('selection_display_configuration[entity_type]')->selectOption('taxonomy_term');
$this->assertSession()->assertWaitOnAjaxRequest();
$this->assertSession()->optionExists('selection_display_configuration[display_settings][view_mode]', 'default');
$this->assertSession()->assertWaitOnAjaxRequest();
$this->assertSession()->optionExists('selection_display_configuration[display_settings][view_mode]', 'full');
// Test view selection display.
$this->assertSession()->selectExists('selection_display')->selectOption('view');
$this->assertSession()->assertWaitOnAjaxRequest();
$this->assertSession()->optionExists('selection_display_configuration[view]', 'content.default');
$this->assertSession()->responseContains('View display to use for displaying currently selected items.');
$this->assertSession()->selectExists('selection_display')->selectOption('no_display');
$this->assertSession()->assertWaitOnAjaxRequest();
$this->assertSession()->elementContains('css', 'details[data-drupal-selector="edit-selection-display-configuration"]', 'This plugin has no configuration options');
}
/**
* Tests WidgetsConfig form.
*/
public function testWidgetsConfig() {
$this->drupalLogin($this->adminUser);
$this->drupalGet('/admin/config/content/entity_browser');
$this->clickLink('Add Entity browser');
$this->assertSession()->fieldExists('label')->setValue('Test entity browser');
$this->getSession()->executeScript("jQuery('.visually-hidden, .hidden').removeClass('visually-hidden hidden');");
$this->assertSession()->fieldExists('name')->setValue('test_entity_browser');
// Use defaults and save to go to WidgetsConfig form.
$this->submitForm([], 'Save');
$this->assertSession()->addressEquals('/admin/config/content/entity_browser/test_entity_browser/widgets');
$this->assertSession()->pageTextContains('The entity browser Test entity browser has been added. Now you may configure the widgets you would like to use.');
$widgetSelect = $this->assertSession()->selectExists('widget');
$this->assertSession()->responseContains('The available plugins are:');
$this->assertSession()->responseContains("<strong>Upload:</strong> Adds an upload field browser's widget.");
$this->assertSession()->responseContains("<strong>View:</strong> Uses a view to provide entity listing in a browser's widget.");
$this->assertSession()->responseContains("<strong>Entity form:</strong> Provides entity form widget.");
// Test adding and removing entity form widget.
$widgetSelect->selectOption('entity_form');
$selector = $this->assertSession()
->waitforElementVisible('css', 'tr.draggable')
->getAttribute('data-drupal-selector');
$uuid = str_replace('edit-table-', '', $selector);
$this->assertSession()->fieldExists("table[$uuid][label]");
$this->assertSession()->fieldExists("table[$uuid][form][submit_text]");
$this->assertSession()->selectExists("table[$uuid][form][entity_type]")->selectOption('node');
$this->assertSession()->assertWaitOnAjaxRequest();
$this->assertSession()->selectExists("table[$uuid][form][bundle][select]")->selectOption('foo');
$this->assertSession()->selectExists("table[$uuid][form][form_mode][form_select]");
$this->submitForm([], 'Save');
$this->assertSession()->addressEquals('/admin/config/content/entity_browser/test_entity_browser/widgets');
$this->assertSession()->pageTextContains('The entity browser Test entity browser has been updated.');
$entity_browser = EntityBrowser::load('test_entity_browser');
$widget = $entity_browser->getWidget($uuid);
$widgetSettings = $widget->getConfiguration()['settings'];
$this->assertEquals([
'submit_text' => 'Save entity',
'entity_type' => 'node',
'bundle' => 'foo',
'form_mode' => 'default',
], $widgetSettings, 'Entity browser widget configuration was correctly saved.');
$this->assertSession()->buttonExists("edit-table-$uuid-remove")->press();
$this->assertSession()->assertWaitOnAjaxRequest();
$this->assertSession()->elementNotExists('css', 'tr[data-drupal-selector="edit-table-' . $uuid . '"]');
// There should be no widgets now.
$this->assertSession()->elementNotExists('css', 'tr.draggable');
// Test adding and removing view widget.
$widgetSelect->selectOption('view');
$selector = $this->assertSession()
->waitforElementVisible('css', 'tr.draggable')
->getAttribute('data-drupal-selector');
$uuid = str_replace('edit-table-', '', $selector);
$this->assertSession()->fieldExists("table[$uuid][label]");
$this->assertSession()->fieldExists("table[$uuid][form][submit_text]");
$this->assertSession()->fieldExists("table[$uuid][form][auto_select]")->check();
$this->assertSession()->selectExists("table[$uuid][form][view]")->selectOption('nodes_entity_browser.entity_browser_1');
$this->submitForm([], 'Save');
$this->assertSession()->addressEquals('/admin/config/content/entity_browser/test_entity_browser/widgets');
$this->assertSession()->pageTextContains('The entity browser Test entity browser has been updated.');
$entity_browser = EntityBrowser::load('test_entity_browser');
$widget = $entity_browser->getWidget($uuid);
$widgetSettings = $widget->getConfiguration()['settings'];
$this->assertEquals([
'view' => 'nodes_entity_browser',
'view_display' => 'entity_browser_1',
'submit_text' => 'Select entities',
'auto_select' => TRUE,
], $widgetSettings, 'Entity browser widget configuration was correctly saved.');
$this->assertSession()->buttonExists("edit-table-$uuid-remove")->press();
$this->assertSession()->assertWaitOnAjaxRequest();
$this->assertSession()->elementNotExists('css', 'tr[data-drupal-selector="edit-table-' . $uuid . '"]');
// There should be no widgets now.
$this->assertSession()->elementNotExists('css', 'tr.draggable');
// Test adding and removing upload widget.
$widgetSelect->selectOption('upload');
$selector = $this->assertSession()
->waitforElementVisible('css', 'tr.draggable')
->getAttribute('data-drupal-selector');
$uuid = str_replace('edit-table-', '', $selector);
$this->assertSession()->fieldExists("table[$uuid][label]");
$this->assertSession()->fieldExists("table[$uuid][form][submit_text]");
$this->assertSession()->fieldExists("table[$uuid][form][upload_location]");
$this->assertSession()->fieldExists("table[$uuid][form][multiple]");
$this->assertSession()->fieldExists("table[$uuid][form][upload_location]");
$this->assertSession()->elementExists('css', 'a.token-dialog.use-ajax');
$this->submitForm([], 'Save');
$this->assertSession()->addressEquals('/admin/config/content/entity_browser/test_entity_browser/widgets');
$this->assertSession()->pageTextContains('The entity browser Test entity browser has been updated.');
$entity_browser = EntityBrowser::load('test_entity_browser');
$widget = $entity_browser->getWidget($uuid);
$widgetSettings = $widget->getConfiguration()['settings'];
$this->assertEquals([
'upload_location' => 'public://',
'multiple' => TRUE,
'submit_text' => 'Select files',
'extensions' => 'jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp',
], $widgetSettings, 'Entity browser widget configuration was correctly saved.');
$this->assertSession()->buttonExists("edit-table-$uuid-remove")->press();
$this->assertSession()->assertWaitOnAjaxRequest();
$this->assertSession()->elementNotExists('css', 'tr[data-drupal-selector="edit-table-' . $uuid . '"]');
// There should be no widgets now.
$this->assertSession()->elementNotExists('css', 'tr.draggable');
// Go back to listing page.
$this->drupalGet('/admin/config/content/entity_browser');
$this->assertSession()->responseContains('admin/config/content/entity_browser/test_entity_browser/edit');
// Test that removing widget without saving doesn't remove it permanently.
$entity_browser = EntityBrowser::load('test_entity_browser');
$widget = $entity_browser->getWidget($uuid);
$this->assertNotEmpty($widget);
}
}
@@ -0,0 +1,634 @@
<?php
namespace Drupal\Tests\entity_browser\FunctionalJavascript;
/**
* Tests the entity_browser.
*
* @group entity_browser
*/
class EntityBrowserTest extends EntityBrowserWebDriverTestBase {
/**
* Tests single widget selector.
*/
public function testSingleWidgetSelector() {
// Sets the single widget selector.
/** @var \Drupal\entity_browser\EntityBrowserInterface $browser */
$browser = $this->container->get('entity_type.manager')
->getStorage('entity_browser')
->load('test_entity_browser_file');
$this->assertEquals($browser->getWidgetSelector()->getPluginId(), 'single', 'Widget selector is set to single.');
// Create a file.
$image = $this->createFile('llama');
$this->drupalGet('node/add/article');
$this->assertSession()->linkExists('Select entities');
$this->getSession()->getPage()->clickLink('Select entities');
$this->getSession()->switchToIFrame('entity_browser_iframe_test_entity_browser_file');
$this->getSession()->getPage()->checkField('entity_browser_select[file:' . $image->id() . ']');
$this->getSession()->getPage()->pressButton('Select entities');
// Switch back to the main page.
$this->getSession()->switchToIFrame();
$this->waitForAjaxToFinish();
// Test the Edit functionality.
$this->assertSession()->pageTextContains('llama.jpg');
$this->assertSession()->buttonExists('Edit');
// @TODO Test the edit button.
// Test the Delete functionality.
$this->assertSession()->buttonExists('Remove');
$this->getSession()->getPage()->pressButton('Remove');
$this->waitForAjaxToFinish();
$this->assertSession()->pageTextNotContains('llama.jpg');
$this->assertSession()->linkExists('Select entities');
}
/**
* Tests the field widget with a single-cardinality field.
*/
public function testSingleCardinalityField() {
$this->container->get('entity_type.manager')
->getStorage('field_storage_config')
->load('node.field_reference')
->setCardinality(1)
->save();
// Create a file.
$image = $this->createFile('llama');
$this->drupalGet('node/add/article');
$this->assertSession()->linkExists('Select entities');
$this->assertSession()->pageTextContains('You can select one file.');
$this->getSession()->getPage()->clickLink('Select entities');
$this->getSession()->switchToIFrame('entity_browser_iframe_test_entity_browser_file');
$this->getSession()->getPage()->checkField('entity_browser_select[file:' . $image->id() . ']');
$this->getSession()->getPage()->pressButton('Select entities');
// Switch back to the main page.
$this->getSession()->switchToIFrame();
$this->waitForAjaxToFinish();
// A selection has been made, so the message is no longer necessary.
$this->assertSession()->pageTextNotContains('You can select one file.');
}
/**
* Tests the field widget with a multi-cardinality field.
*/
public function testMultiCardinalityField() {
$assert_session = $this->assertSession();
$session = $this->getSession();
$page = $session->getPage();
$this->container->get('entity_type.manager')
->getStorage('field_storage_config')
->load('node.field_reference')
->setCardinality(3)
->save();
// Create a few files to choose.
$images = [];
array_push($images, $this->createFile('llama'));
array_push($images, $this->createFile('sloth'));
array_push($images, $this->createFile('puppy'));
$this->drupalGet('node/add/article');
$assert_session->linkExists('Select entities');
$assert_session->pageTextContains('You can select up to 3 files (3 left).');
$page->clickLink('Select entities');
$session->switchToIFrame('entity_browser_iframe_test_entity_browser_file');
$page->checkField('entity_browser_select[file:' . $images[0]->id() . ']');
$page->checkField('entity_browser_select[file:' . $images[1]->id() . ']');
$page->pressButton('Select entities');
// Switch back to the main page.
$session->switchToIFrame();
$this->waitForAjaxToFinish();
// Selections have been made, so the message should be different.
$assert_session->pageTextContains('You can select up to 3 files (1 left).');
}
/**
* Tests tabs widget selector.
*/
public function testTabsWidgetSelector() {
// Sets the tabs widget selector.
/** @var \Drupal\entity_browser\EntityBrowserInterface $browser */
$browser = $this->container->get('entity_type.manager')
->getStorage('entity_browser')
->load('test_entity_browser_file')
->setWidgetSelector('tabs');
$browser->save();
$this->assertEquals($browser->getWidgetSelector()->getPluginId(), 'tabs', 'Widget selector is set to tabs.');
// Create a file.
$image = $this->createFile('llama');
// Create a second file.
$image2 = $this->createFile('llama2');
$this->drupalGet('node/add/article');
$this->assertSession()->linkExists('Select entities');
$this->getSession()->getPage()->clickLink('Select entities');
$this->getSession()->switchToIFrame('entity_browser_iframe_test_entity_browser_file');
$this->assertSession()->linkExists('dummy');
$this->assertSession()->linkExists('view');
$this->assertSession()->linkExists('upload');
$this->assertEquals('is-active active', $this->getSession()->getPage()->findLink('view')->getAttribute('class'));
$this->getSession()->getPage()->checkField('entity_browser_select[file:' . $image->id() . ']');
$this->getSession()->getPage()->pressButton('Select entities');
$this->getSession()->switchToIFrame();
$this->waitForAjaxToFinish();
$this->assertSession()->pageTextContains('llama.jpg');
$this->getSession()->getPage()->clickLink('Select entities');
$this->getSession()->switchToIFrame('entity_browser_iframe_test_entity_browser_file');
$this->getSession()->getPage()->clickLink('upload');
// This is producing an error. Still investigating
// InvalidStateError: DOM Exception 11: An attempt was made to use an object
// that is not, or is no longer, usable.
// $uri = $this->container
// ->get('file_system')
// ->realpath($image2->getFileUri());
// $edit = [
// 'files[upload][]' => $uri,
// ];
// $this->submitForm($edit, 'Select files');.
\Drupal::state()->set('eb_test_dummy_widget_access', FALSE);
$this->drupalGet('entity-browser/iframe/test_entity_browser_file');
$this->assertSession()->linkNotExists('dummy');
$this->assertSession()->linkExists('view');
$this->assertSession()->linkExists('upload');
// Commenting out header checks for now:
// Behat\Mink\Exception\UnsupportedDriverActionException: Response headers are not available
// from Drupal\FunctionalJavascriptTests\DrupalSelenium2Driver
// $this->assertHeader('X-Drupal-Cache-Contexts', 'eb_dummy');
// Move dummy widget to the first place and make sure it does not appear.
$browser = $this->container->get('entity_type.manager')
->getStorage('entity_browser')
->load('test_entity_browser_file');
$browser->getWidget('cbc59500-04ab-4395-b063-c561f0e3bf80')->setWeight(-15);
$browser->save();
$this->drupalGet('entity-browser/iframe/test_entity_browser_file');
$this->assertSession()->linkNotExists('dummy');
$this->assertSession()->linkExists('view');
$this->assertSession()->linkExists('upload');
$this->assertSession()->pageTextNotContains('This is dummy widget.');
}
/**
* Tests dropdown widget selector.
*/
public function testDropdownWidgetSelector() {
// Sets the dropdown widget selector.
/** @var \Drupal\entity_browser\EntityBrowserInterface $browser */
$browser = $this->container->get('entity_type.manager')
->getStorage('entity_browser')
->load('test_entity_browser_file')
->setWidgetSelector('drop_down');
$browser->save();
$this->assertEquals($browser->getWidgetSelector()->getPluginId(), 'drop_down', 'Widget selector is set to dropdown.');
// Create a file.
$image = $this->createFile('llama');
$this->drupalGet('node/add/article');
$this->assertSession()->linkExists('Select entities');
$this->getSession()->getPage()->clickLink('Select entities');
$this->getSession()->switchToIFrame('entity_browser_iframe_test_entity_browser_file');
$this->assertSession()->selectExists('widget');
// Dummy.
$this->assertSession()->optionExists('widget', 'cbc59500-04ab-4395-b063-c561f0e3bf80');
// Upload.
$this->assertSession()->optionExists('widget', '2dc1ab07-2f8f-42c9-aab7-7eef7f8b7d87');
// View.
$this->assertSession()->optionExists('widget', '774798f1-5ec5-4b63-84bd-124cd51ec07d');
// Selects the view widget.
$this->getSession()->getPage()->selectFieldOption('widget', '774798f1-5ec5-4b63-84bd-124cd51ec07d');
$this->getSession()->getPage()->checkField('entity_browser_select[file:' . $image->id() . ']');
$this->getSession()->getPage()->pressButton('Select entities');
$this->getSession()->switchToIFrame();
$this->waitForAjaxToFinish();
$this->assertSession()->pageTextContains('llama.jpg');
$this->getSession()->getPage()->clickLink('Select entities');
$this->getSession()->switchToIFrame('entity_browser_iframe_test_entity_browser_file');
// Causes a fatal.
// Selects the upload widget.
// $this->getSession()
// ->getPage()
// ->selectFieldOption('widget', '2dc1ab07-2f8f-42c9-aab7-7eef7f8b7d87');.
\Drupal::state()->set('eb_test_dummy_widget_access', FALSE);
$this->drupalGet('entity-browser/iframe/test_entity_browser_file');
// Dummy.
$this->assertSession()->optionNotExists('widget', 'cbc59500-04ab-4395-b063-c561f0e3bf80');
// Upload.
$this->assertSession()->optionExists('widget', '2dc1ab07-2f8f-42c9-aab7-7eef7f8b7d87');
// View.
$this->assertSession()->optionExists('widget', '774798f1-5ec5-4b63-84bd-124cd51ec07d');
// Move dummy widget to the first place and make sure it does not appear.
$browser = $this->container->get('entity_type.manager')
->getStorage('entity_browser')
->load('test_entity_browser_file');
$browser->getWidget('cbc59500-04ab-4395-b063-c561f0e3bf80')->setWeight(-15);
$browser->save();
$this->drupalGet('entity-browser/iframe/test_entity_browser_file');
// Dummy.
$this->assertSession()->optionNotExists('widget', 'cbc59500-04ab-4395-b063-c561f0e3bf80');
// Upload.
$this->assertSession()->optionExists('widget', '2dc1ab07-2f8f-42c9-aab7-7eef7f8b7d87');
// View.
$this->assertSession()->optionExists('widget', '774798f1-5ec5-4b63-84bd-124cd51ec07d');
$this->assertSession()->pageTextNotContains('This is dummy widget.');
}
/**
* Tests views selection display.
*/
public function testViewsSelectionDisplayWidget() {
// Sets the dropdown widget selector.
/** @var \Drupal\entity_browser\EntityBrowserInterface $browser */
$browser = $this->container->get('entity_type.manager')
->getStorage('entity_browser')
->load('test_entity_browser_file')
->setSelectionDisplay('view');
$browser->save();
$this->assertEquals($browser->getSelectionDisplay()->getPluginId(), 'view', 'Selection display is set to view.');
}
/**
* Tests NoDisplay selection display plugin.
*/
public function testNoDisplaySelectionDisplay() {
/** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display */
$form_display = $this->container->get('entity_type.manager')
->getStorage('entity_form_display')
->load('node.article.default');
$form_display->setComponent('field_reference', [
'type' => 'entity_browser_entity_reference',
'settings' => [
'entity_browser' => 'multiple_submit_example',
'field_widget_display' => 'label',
'open' => TRUE,
],
])->save();
$account = $this->drupalCreateUser([
'access multiple_submit_example entity browser pages',
'create article content',
'access content',
]);
$this->drupalLogin($account);
$this->drupalGet('node/add/article');
// Open the entity browser widget form.
$this->getSession()->getPage()->clickLink('Select entities');
$this->getSession()->switchToIFrame('entity_browser_iframe_multiple_submit_example');
// Click the second submit button to make sure the widget does not close.
$this->getSession()->getPage()->pressButton('Second submit button');
// Check that the entity browser widget is still open.
$this->getSession()->getPage()->hasButton('Second submit button');
// Click the primary submit button to close the widget.
$this->getSession()->getPage()->pressButton('Select entities');
// Check that the entity browser widget is closed.
$this->assertSession()->buttonNotExists('Second submit button');
}
/**
* Tests the EntityBrowserWidgetContext default argument plugin.
*/
public function testEntityBrowserWidgetContext() {
$this->createNode(['type' => 'shark', 'title' => 'Luke']);
$this->createNode(['type' => 'jet', 'title' => 'Leia']);
$this->createNode(['type' => 'article', 'title' => 'Darth']);
/** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display */
$form_display = $this->container->get('entity_type.manager')
->getStorage('entity_form_display')
->load('node.article.default');
$form_display->setComponent('field_reference', [
'type' => 'entity_browser_entity_reference',
'settings' => [
'entity_browser' => 'widget_context_default_value',
'field_widget_display' => 'label',
'open' => TRUE,
],
])->save();
/** @var \Drupal\Core\Field\FieldConfigInterface $field_config */
$field_config = $this->container->get('entity_type.manager')
->getStorage('field_config')
->load('node.article.field_reference');
$handler_settings = $field_config->getSetting('handler_settings');
$handler_settings['target_bundles'] = [
'shark' => 'shark',
'jet' => 'jet',
];
$field_config->setSetting('handler_settings', $handler_settings);
$field_config->save();
// Set auto open to false on the entity browser.
$entity_browser = $this->container->get('entity_type.manager')
->getStorage('entity_browser')
->load('widget_context_default_value');
$display_configuration = $entity_browser->get('display_configuration');
$display_configuration['auto_open'] = FALSE;
$entity_browser->set('display_configuration', $display_configuration);
$entity_browser->save();
$account = $this->drupalCreateUser([
'access widget_context_default_value entity browser pages',
'create article content',
'access content',
]);
$this->drupalLogin($account);
$this->drupalGet('node/add/article');
// Open the entity browser widget form.
$this->getSession()->getPage()->clickLink('Select entities');
$this->getSession()->switchToIFrame('entity_browser_iframe_widget_context_default_value');
// Check that only nodes of an allowed type are listed.
$this->assertSession()->pageTextContains('Luke');
$this->assertSession()->pageTextContains('Leia');
$this->assertSession()->pageTextNotContains('Darth');
/** @var \Drupal\Core\Field\FieldConfigInterface $field_config */
$field_config = $this->container->get('entity_type.manager')
->getStorage('field_config')
->load('node.article.field_reference');
$handler_settings = $field_config->getSetting('handler_settings');
$handler_settings['target_bundles'] = [
'article' => 'article',
];
$field_config->setSetting('handler_settings', $handler_settings);
$field_config->save();
$this->drupalGet('node/add/article');
// Open the entity browser widget form.
$this->getSession()->getPage()->clickLink('Select entities');
$this->getSession()->switchToIFrame('entity_browser_iframe_widget_context_default_value');
// Check that only nodes of an allowed type are listed.
$this->assertSession()->pageTextNotContains('Luke');
$this->assertSession()->pageTextNotContains('Leia');
$this->assertSession()->pageTextContains('Darth');
}
/**
* Tests the ContextualBundle filter plugin.
*/
public function testContextualBundle() {
$this->createNode(['type' => 'shark', 'title' => 'Luke']);
$this->createNode(['type' => 'jet', 'title' => 'Leia']);
$this->createNode(['type' => 'article', 'title' => 'Darth']);
/** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display */
$form_display = $this->container->get('entity_type.manager')
->getStorage('entity_form_display')
->load('node.article.default');
$form_display->setComponent('field_reference', [
'type' => 'entity_browser_entity_reference',
'settings' => [
'entity_browser' => 'bundle_filter',
'field_widget_display' => 'label',
'open' => TRUE,
],
])->save();
/** @var \Drupal\Core\Field\FieldConfigInterface $field_config */
$field_config = $this->container->get('entity_type.manager')
->getStorage('field_config')
->load('node.article.field_reference');
$handler_settings = $field_config->getSetting('handler_settings');
$handler_settings['target_bundles'] = [
'shark' => 'shark',
'jet' => 'jet',
];
$field_config->setSetting('handler_settings', $handler_settings);
$field_config->save();
// Set auto open to false on the entity browser.
$entity_browser = $this->container->get('entity_type.manager')
->getStorage('entity_browser')
->load('bundle_filter');
$display_configuration = $entity_browser->get('display_configuration');
$display_configuration['auto_open'] = FALSE;
$entity_browser->set('display_configuration', $display_configuration);
$entity_browser->save();
$account = $this->drupalCreateUser([
'access bundle_filter entity browser pages',
'create article content',
'access content',
]);
$this->drupalLogin($account);
$this->drupalGet('node/add/article');
// Open the entity browser widget form.
$this->getSession()->getPage()->clickLink('Select entities');
$this->getSession()->switchToIFrame('entity_browser_iframe_bundle_filter');
// Check that only nodes of an allowed type are listed.
$this->assertSession()->pageTextContains('Luke');
$this->assertSession()->pageTextContains('Leia');
$this->assertSession()->pageTextNotContains('Darth');
/** @var \Drupal\Core\Field\FieldConfigInterface $field_config */
$field_config = $this->container->get('entity_type.manager')
->getStorage('field_config')
->load('node.article.field_reference');
$handler_settings = $field_config->getSetting('handler_settings');
$handler_settings['target_bundles'] = [
'article' => 'article',
];
$field_config->setSetting('handler_settings', $handler_settings);
$field_config->save();
$this->drupalGet('node/add/article');
// Open the entity browser widget form.
$this->getSession()->getPage()->clickLink('Select entities');
$this->getSession()->switchToIFrame('entity_browser_iframe_bundle_filter');
// Check that only nodes of an allowed type are listed.
$this->assertSession()->pageTextNotContains('Luke');
$this->assertSession()->pageTextNotContains('Leia');
$this->assertSession()->pageTextContains('Darth');
}
/**
* Tests the ContextualBundle filter plugin with exposed option.
*/
public function testContextualBundleExposed() {
$this->config('entity_browser.browser.bundle_filter')
->set('widgets.b882a89d-9ce4-4dfe-9802-62df93af232a.settings.view', 'bundle_filter_exposed')
->save();
$this->createNode(['type' => 'shark', 'title' => 'Luke']);
$this->createNode(['type' => 'jet', 'title' => 'Leia']);
$this->createNode(['type' => 'article', 'title' => 'Darth']);
/** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display */
$form_display = $this->container->get('entity_type.manager')
->getStorage('entity_form_display')
->load('node.article.default');
$form_display->setComponent('field_reference', [
'type' => 'entity_browser_entity_reference',
'settings' => [
'entity_browser' => 'bundle_filter',
'field_widget_display' => 'label',
'open' => TRUE,
],
])->save();
/** @var \Drupal\Core\Field\FieldConfigInterface $field_config */
$field_config = $this->container->get('entity_type.manager')
->getStorage('field_config')
->load('node.article.field_reference');
$handler_settings = $field_config->getSetting('handler_settings');
$handler_settings['target_bundles'] = [
'shark' => 'shark',
'jet' => 'jet',
];
$field_config->setSetting('handler_settings', $handler_settings);
$field_config->save();
// Set auto open to false on the entity browser.
$entity_browser = $this->container->get('entity_type.manager')
->getStorage('entity_browser')
->load('bundle_filter');
$display_configuration = $entity_browser->get('display_configuration');
$display_configuration['auto_open'] = FALSE;
$entity_browser->set('display_configuration', $display_configuration);
$entity_browser->save();
$account = $this->drupalCreateUser([
'access bundle_filter entity browser pages',
'create article content',
'access content',
]);
$this->drupalLogin($account);
$this->drupalGet('node/add/article');
// Open the entity browser widget form.
$this->getSession()->getPage()->clickLink('Select entities');
$this->getSession()->switchToIFrame('entity_browser_iframe_bundle_filter');
// Check that only nodes of an allowed type are listed.
$this->assertSession()->pageTextContains('Luke');
$this->assertSession()->pageTextContains('Leia');
$this->assertSession()->pageTextNotContains('Darth');
// Test exposed form type filter.
$this->assertSession()->selectExists('Type')->selectOption('jet');
$this->assertSession()->buttonExists('Apply')->press();
$this->assertSession()->assertWaitOnAjaxRequest();
// Check that only nodes of the type selected in the exposed filter display.
$this->assertSession()->pageTextNotContains('Luke');
$this->assertSession()->pageTextContains('Leia');
$this->assertSession()->pageTextNotContains('Darth');
$this->assertSession()->selectExists('Type')->selectOption('shark');
$this->assertSession()->buttonExists('Apply')->press();
$this->assertSession()->assertWaitOnAjaxRequest();
// Check that only nodes of the type selected in the exposed filter display.
$this->assertSession()->pageTextContains('Luke');
$this->assertSession()->pageTextNotContains('Leia');
$this->assertSession()->pageTextNotContains('Darth');
$this->assertSession()->selectExists('Type')->selectOption('All');
$this->assertSession()->buttonExists('Apply')->press();
$this->assertSession()->assertWaitOnAjaxRequest();
// Check that only nodes of the type selected in the exposed filter display.
$this->assertSession()->pageTextContains('Luke');
$this->assertSession()->pageTextContains('Leia');
$this->assertSession()->pageTextNotContains('Darth');
/** @var \Drupal\Core\Field\FieldConfigInterface $field_config */
$field_config = $this->container->get('entity_type.manager')
->getStorage('field_config')
->load('node.article.field_reference');
$handler_settings = $field_config->getSetting('handler_settings');
$handler_settings['target_bundles'] = [
'article' => 'article',
];
$field_config->setSetting('handler_settings', $handler_settings);
$field_config->save();
$this->drupalGet('node/add/article');
// Open the entity browser widget form.
$this->getSession()->getPage()->clickLink('Select entities');
$this->getSession()->switchToIFrame('entity_browser_iframe_bundle_filter');
// Check that only nodes of an allowed type are listed.
$this->assertSession()->pageTextNotContains('Luke');
$this->assertSession()->pageTextNotContains('Leia');
$this->assertSession()->pageTextContains('Darth');
// If there is just one target_bundle, the contextual filter
// should not be visible.
$this->assertSession()->fieldNotExists('Type');
}
}
@@ -0,0 +1,192 @@
<?php
namespace Drupal\Tests\entity_browser\FunctionalJavascript;
use Drupal\file\Entity\File;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\entity_browser\Element\EntityBrowserElement;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
/**
* Entity Browser views widget tests.
*
* @group entity_browser
* @see \Drupal\entity_browser\Plugin\EntityBrowser\Widget\View
*/
class EntityBrowserViewsWidgetTest extends EntityBrowserWebDriverTestBase {
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = [
'node',
'views',
'entity_browser_test',
];
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$user = $this->drupalCreateUser([
'access test_entity_browser_file entity browser pages',
'access test_double_underscore entity browser pages',
'bypass node access',
]);
$this->drupalLogin($user);
}
/**
* Tests Entity Browser views widget.
*/
public function testViewsWidget() {
// Create a file so that our test View isn't empty.
\Drupal::service('file_system')->copy(\Drupal::root() . '/core/misc/druplicon.png', 'public://example.jpg');
/** @var \Drupal\file\FileInterface $file */
$file = File::create([
'uri' => 'public://example.jpg',
]);
$file->save();
// Visit a test entity browser page that defaults to using a View widget.
$this->drupalGet('/entity-browser/iframe/test_entity_browser_file');
$field = 'entity_browser_select[file:' . $file->id() . ']';
// Test exposed filters.
$this->assertSession()->pageTextContains('example.jpg');
$this->assertSession()->fieldExists($field);
$this->getSession()->getPage()->fillField('filename', 'llama');
$this->getSession()->getPage()->pressButton('Apply');
$this->waitForAjaxToFinish();
$this->assertSession()->fieldNotExists($field);
$this->assertSession()->pageTextNotContains('example.jpg');
$this->getSession()->getPage()->fillField('filename', 'example');
$this->getSession()->getPage()->pressButton('Apply');
$this->waitForAjaxToFinish();
$this->assertSession()->pageTextContains('example.jpg');
$this->assertSession()->fieldExists($field)->check();
$this->assertSession()->buttonExists('Select entities')->press();
$this->assertSession()->responseNotContains('HTTP/1.0 200 OK');
$this->assertSession()->responseNotContains('Cache-Control: no-cache, private');
// Test that the response contains the selected entity.
$script = "return drupalSettings.entity_browser.iframe.entities[0];";
$result = $this->getSession()
->getDriver()
->getWebDriverSession()
->execute([
'script' => $script,
'args' => [],
]);
$this->assertEquals($file->id(), $result[0]);
$this->assertEquals('file', $result[2]);
// Create another file to test bulk select form.
\Drupal::service('file_system')->copy(\Drupal::root() . '/core/misc/druplicon.png', 'public://example_1.jpg');
/** @var \Drupal\file\FileInterface $file */
$new_file = File::create([
'uri' => 'public://example_1.jpg',
]);
$new_file->save();
// Visit entity browser test page again.
$this->drupalGet('/entity-browser/iframe/test_entity_browser_file');
$new_field = 'entity_browser_select[file:' . $new_file->id() . ']';
// Assert both checkbox fields are there.
$check_old = $this->assertSession()->fieldExists($field);
$check_new = $this->assertSession()->fieldExists($new_field);
// Compare value attributes of checkboxes and assert they not equal.
$this->assertNotEquals($check_old->getAttribute('value'), $check_new->getAttribute('value'));
$uuid = \Drupal::service('uuid')->generate();
\Drupal::service('entity_browser.selection_storage')->setWithExpire(
$uuid,
['validators' => ['cardinality' => ['cardinality' => 1]]],
21600
);
$this->drupalGet('/entity-browser/iframe/test_entity_browser_file', ['query' => ['uuid' => $uuid]]);
$this->getSession()->getPage()->fillField('entity_browser_select[file:1]', TRUE);
$this->getSession()->getPage()->fillField('entity_browser_select[file:2]', TRUE);
$this->getSession()->getPage()->pressButton('Select entities');
$this->assertSession()->pageTextContains('You can only select one item.');
$this->assertSession()->checkboxNotChecked('entity_browser_select[file:1]');
$this->assertSession()->checkboxNotChecked('entity_browser_select[file:2]');
// Test entity_browser.view.js adding AJAX to exposed forms.
$field_storage = FieldStorageConfig::create([
'field_name' => 'field_alderaan',
'type' => 'entity_reference',
'entity_type' => 'node',
'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
'settings' => [
'target_type' => 'node',
],
]);
$field_storage->save();
$field = FieldConfig::create([
'field_name' => 'field_alderaan',
'entity_type' => 'node',
'bundle' => 'article',
'label' => 'Referenced articles',
'settings' => [],
]);
$field->save();
/** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display */
$form_display = $this->container->get('entity_type.manager')
->getStorage('entity_form_display')
->load('node.article.default');
$form_display->setComponent('field_alderaan', [
'type' => 'entity_browser_entity_reference',
'settings' => [
'entity_browser' => 'test_double_underscore',
'open' => TRUE,
'field_widget_edit' => TRUE,
'field_widget_remove' => TRUE,
'field_widget_replace' => FALSE,
'selection_mode' => EntityBrowserElement::SELECTION_MODE_APPEND,
'field_widget_display' => 'label',
'field_widget_display_settings' => [],
],
])->save();
$nodes = [
'Happy families are all alike',
'Call me Ishmael',
];
foreach ($nodes as $title) {
$this->createNode([
'title' => $title,
'type' => 'article',
]);
}
$this->drupalGet('/node/add/article');
$this->assertSession()->waitForElementVisible('css', '#entity-browser-test-double-underscore-form');
$this->getSession()->switchToIFrame('entity_browser_iframe_test_double_underscore');
foreach ($nodes as $title) {
$this->assertSession()->pageTextContains($title);
}
$this->assertSession()->fieldExists('title')->setValue('Ishmael');
$this->assertSession()->buttonExists('Apply')->press();
$this->waitForAjaxToFinish();
$this->assertSession()->pageTextContains('Call me Ishmael');
$this->assertSession()->pageTextNotContains('Happy families are all alike');
$this->assertSession()->fieldExists('title')->setValue('families');
$this->assertSession()->buttonExists('Apply')->press();
$this->waitForAjaxToFinish();
$this->assertSession()->pageTextNotContains('Call me Ishmael');
$this->assertSession()->pageTextContains('Happy families are all alike');
}
}
@@ -0,0 +1,317 @@
<?php
namespace Drupal\Tests\entity_browser\FunctionalJavascript;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\file\Entity\File;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\FunctionalJavascriptTests\WebDriverTestBase;
use Behat\Mink\Element\NodeElement;
use Drupal\language\Entity\ConfigurableLanguage;
/**
* Base class for Entity browser Javascript functional tests.
*
* @package Drupal\Tests\entity_browser\FunctionalJavascript
*/
abstract class EntityBrowserWebDriverTestBase extends WebDriverTestBase {
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = [
'entity_browser_test',
'contextual',
'views',
'block',
'node',
'file',
'image',
'field_ui',
'views_ui',
'system',
'language',
];
/**
* Permissions for user that will be logged-in for test.
*
* @var array
*/
protected static $userPermissions = [
'access test_entity_browser_file entity browser pages',
'create article content',
'access content',
];
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
FieldStorageConfig::create([
'field_name' => 'field_reference',
'type' => 'entity_reference',
'entity_type' => 'node',
'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
'settings' => [
'target_type' => 'file',
],
])->save();
FieldConfig::create([
'field_name' => 'field_reference',
'entity_type' => 'node',
'bundle' => 'article',
'label' => 'Reference',
'settings' => [],
])->save();
/** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display */
$form_display = $this->container->get('entity_type.manager')
->getStorage('entity_form_display')
->load('node.article.default');
$form_display->setComponent('field_reference', [
'type' => 'entity_browser_entity_reference',
'settings' => [
'entity_browser' => 'test_entity_browser_file',
'field_widget_display' => 'label',
'open' => TRUE,
],
])->save();
ConfigurableLanguage::createFromLangcode('fr')->save();
$account = $this->drupalCreateUser(static::$userPermissions);
$this->drupalLogin($account);
}
/**
* Return an entity browser if it exists or creates a new one.
*
* @param string $browser_name
* The entity browser name.
* @param string $display_id
* The display plugin id.
* @param string $widget_selector_id
* The widget selector id.
* @param string $selection_display_id
* The selection display id.
* @param array $display_configuration
* The display plugin configuration.
* @param array $widget_selector_configuration
* The widget selector configuration.
* @param array $selection_display_configuration
* The selection display configuration.
* @param array $widget_configurations
* Widget configurations. Have be provided with widget UUIDs.
*
* @return \Drupal\entity_browser\EntityBrowserInterface
* Returns an Entity Browser.
*/
protected function getEntityBrowser($browser_name, $display_id, $widget_selector_id, $selection_display_id, array $display_configuration = [], array $widget_selector_configuration = [], array $selection_display_configuration = [], array $widget_configurations = []) {
/** @var \Drupal\Core\Entity\EntityStorageInterface $storage */
$storage = $this->container->get('entity_type.manager')
->getStorage('entity_browser');
/** @var \Drupal\entity_browser\EntityBrowserInterface $browser */
$browser = $storage->load($browser_name) ?: $storage->create(['name' => $browser_name]);
$browser->setDisplay($display_id);
if ($display_configuration) {
$browser->getDisplay()->setConfiguration($display_configuration);
}
$browser->setWidgetSelector($widget_selector_id);
if ($widget_selector_configuration) {
$browser->getSelectionDisplay()
->setConfiguration($widget_selector_configuration);
}
$browser->setSelectionDisplay($selection_display_id);
if ($selection_display_configuration) {
$browser->getSelectionDisplay()
->setConfiguration($selection_display_configuration);
}
// Apply custom widget configurations.
if ($widget_configurations) {
foreach ($widget_configurations as $widget_uuid => $widget_config) {
$view_widget = $browser->getWidget($widget_uuid);
$view_widget->setConfiguration(NestedArray::mergeDeep($view_widget->getConfiguration(), $widget_config));
}
}
$browser->save();
// Clear caches after new browser is saved to remove old cached states.
drupal_flush_all_caches();
return $browser;
}
/**
* Creates an image.
*
* @param string $name
* The name of the image.
* @param string $extension
* File extension.
*
* @return \Drupal\file\FileInterface
* Returns an image.
*/
protected function createFile($name, $extension = 'jpg') {
file_put_contents('public://' . $name . '.' . $extension, $this->randomMachineName());
$image = File::create([
'filename' => $name . '.' . $extension,
'uri' => 'public://' . $name . '.' . $extension,
]);
$image->setPermanent();
$image->save();
return $image;
}
/**
* Waits for jQuery to become ready and animations to complete.
*/
protected function waitForAjaxToFinish() {
$this->assertSession()->assertWaitOnAjaxRequest();
}
/**
* Drag element in document with defined offset position.
*
* @param \Behat\Mink\Element\NodeElement $element
* Element that will be dragged.
* @param int $offsetX
* Vertical offset for element drag in pixels.
* @param int $offsetY
* Horizontal offset for element drag in pixels.
*/
protected function dragDropElement(NodeElement $element, $offsetX, $offsetY) {
$elemXpath = $element->getXpath();
$jsCode = "var fireMouseEvent = function (type, element, x, y) {
var event = document.createEvent('MouseEvents');
event.initMouseEvent(type, true, (type !== 'mousemove'), window, 0, 0, 0, x, y, false, false, false, false, 0, element);
element.dispatchEvent(event); };";
// XPath provided by getXpath uses single quote (') to encapsulate strings,
// that's why xpath has to be quited with double quites in javascript code.
$jsCode .= "(function() {
var dragElement = document.evaluate(\"{$elemXpath}\", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
var pos = dragElement.getBoundingClientRect();
var centerX = Math.floor((pos.left + pos.right) / 2);
var centerY = Math.floor((pos.top + pos.bottom) / 2);
fireMouseEvent('mousedown', dragElement, centerX, centerY);
var xOffset = {$offsetX};
var yOffset = {$offsetY};
var moves = 3;
for (i = 0 ; i < moves ; i++ ) {
centerX += xOffset / moves;
centerY += yOffset / moves;
fireMouseEvent('mousemove', dragElement, Math.round(centerX), Math.round(centerY));
}
fireMouseEvent('mouseup', dragElement, centerX, centerY);
})();";
$this->getSession()->executeScript($jsCode);
}
/**
* Checks that a specific radio input element exists on the current page.
*
* @param string $value
* The string value of the radio element.
*
* @return \Behat\Mink\Element\NodeElement
* The radio input form element.
*
* @throws \Behat\Mink\Exception\ElementNotFoundException
*/
protected function assertRadioExistsByValue($value) {
$value = (string) $value;
return $this->assertSession()
->elementExists('xpath', "//input[contains(@type, 'radio') and contains(@value, '" . $value . "')]");
}
/**
* Checks that a specific radio input element does not exist on the current page.
*
* @param string $value
* The string value of the radio element.
*
* @return \Behat\Mink\Element\NodeElement
* The radio input form element.
*
* @throws \Behat\Mink\Exception\ElementNotFoundException
*/
protected function assertRadioNotExistsByValue($value) {
$value = (string) $value;
return $this->assertSession()
->elementNotExists('xpath', "//input[contains(@type, 'radio') and contains(@value, '" . $value . "')]");
}
/**
* Checks that a specific checkbox input element exists on the current page.
*
* @param string $value
* The string value of the radio element.
*
* @return \Behat\Mink\Element\NodeElement
* The radio input form element.
*
* @throws \Behat\Mink\Exception\ElementNotFoundException
*/
protected function assertCheckboxExistsByValue($value) {
$value = (string) $value;
return $this->assertSession()
->elementExists('xpath', "//input[contains(@type, 'checkbox') and contains(@value, '" . $value . "')]");
}
/**
* Checks that a specific checkbox input element does not exist on the current page.
*
* @param string $value
* The string value of the radio element.
*
* @return \Behat\Mink\Element\NodeElement
* The radio input form element.
*
* @throws \Behat\Mink\Exception\ElementNotFoundException
*/
protected function assertCheckboxNotExistsByValue($value) {
$value = (string) $value;
return $this->assertSession()
->elementNotExists('xpath', "//input[contains(@type, 'checkbox') and contains(@value, '" . $value . "')]");
}
/**
* Checks the core version.
*
* @param string $version
* The core version, for example 10.2.
*
* @return bool
* Whether the core version is higher than the requested one.
*/
protected function coreVersion(string $version): bool {
return version_compare(\Drupal::VERSION, $version, '>=');
}
}
@@ -0,0 +1,233 @@
<?php
namespace Drupal\Tests\entity_browser\FunctionalJavascript;
use Drupal\FunctionalJavascriptTests\WebDriverTestBase;
/**
* Tests entity browser within entity embed using CKEditor4.
*
* @group entity_browser
*
* @package Drupal\Tests\entity_browser\FunctionalJavascript
*/
class EntityEmbedCKEditor4Test extends WebDriverTestBase {
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = [
'entity_browser',
'entity_browser_test',
'embed',
'entity_embed',
'entity_browser_entity_embed_test',
];
/**
* The test administrative user.
*
* @var \Drupal\user\UserInterface
*/
protected $adminUser;
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->adminUser = $this->drupalCreateUser([
'access content',
'use text format ckeditor4',
'create test_entity_embed content',
'access widget_context_default_value entity browser pages',
'access bundle_filter entity browser pages',
]);
}
/**
* Tests the EntityBrowserWidgetContext default argument plugin.
*/
public function testEntityBrowserWidgetContext() {
$this->drupalLogin($this->adminUser);
$this->createNode(['type' => 'shark', 'title' => 'Luke']);
$this->createNode(['type' => 'jet', 'title' => 'Leia']);
$this->createNode(['type' => 'article', 'title' => 'Darth']);
$this->drupalGet('/node/add/test_entity_embed');
$this->assertSession()->waitForElement('css', 'a.cke_button__jet_shark_embed')->click();
$this->assertSession()->waitForId('views-exposed-form-widget-context-default-value-entity-browser-1');
$this->getSession()->switchToIFrame('entity_browser_iframe_widget_context_default_value');
// Check that only nodes of an allowed type are listed.
$this->assertSession()->responseContains('Luke');
$this->assertSession()->responseContains('Leia');
$this->assertSession()->responseNotContains('Darth');
// Change the allowed bundles on the entity embed.
$embed_button = $this->container->get('entity_type.manager')
->getStorage('embed_button')
->load('jet_shark_embed');
$type_settings = $embed_button->getTypeSettings();
$type_settings['bundles'] = [
'article' => 'article',
];
$embed_button->set('type_settings', $type_settings);
$embed_button->save();
// Test the new bundle settings are affecting what is visible in the view.
$this->drupalGet('/node/add/test_entity_embed');
$this->assertSession()->waitForElement('css', 'a.cke_button__jet_shark_embed')->click();
$this->assertSession()->waitForId('views-exposed-form-widget-context-default-value-entity-browser-1');
$this->getSession()->switchToIFrame('entity_browser_iframe_widget_context_default_value');
// Check that only nodes of an allowed type are listed.
$this->assertSession()->responseNotContains('Luke');
$this->assertSession()->responseNotContains('Leia');
$this->assertSession()->responseContains('Darth');
}
/**
* Tests the ContextualBundle filter plugin.
*/
public function testContextualBundle() {
$this->drupalLogin($this->adminUser);
$this->createNode(['type' => 'shark', 'title' => 'Luke']);
$this->createNode(['type' => 'jet', 'title' => 'Leia']);
$this->createNode(['type' => 'article', 'title' => 'Darth']);
$this->drupalGet('/node/add/test_entity_embed');
$this->assertSession()->waitForElement('css', 'a.cke_button__bundle_filter_test')->click();
$this->assertSession()->waitForId('views-exposed-form-bundle-filter-entity-browser-1');
$this->getSession()->switchToIFrame('entity_browser_iframe_bundle_filter');
// Check that only nodes of an allowed type are listed.
$this->assertSession()->responseContains('Luke');
$this->assertSession()->responseContains('Leia');
$this->assertSession()->responseNotContains('Darth');
// Change the allowed bundles on the entity embed.
$embed_button = $this->container->get('entity_type.manager')
->getStorage('embed_button')
->load('bundle_filter_test');
$type_settings = $embed_button->getTypeSettings();
$type_settings['bundles'] = [
'article' => 'article',
];
$embed_button->set('type_settings', $type_settings);
$embed_button->save();
// Test the new bundle settings are affecting what is visible in the view.
$this->drupalGet('/node/add/test_entity_embed');
$this->assertSession()->waitForElement('css', 'a.cke_button__bundle_filter_test')->click();
$this->assertSession()->waitForId('views-exposed-form-bundle-filter-entity-browser-1');
$this->getSession()->switchToIFrame('entity_browser_iframe_bundle_filter');
// Check that only nodes of an allowed type are listed.
$this->assertSession()->responseNotContains('Luke');
$this->assertSession()->responseNotContains('Leia');
$this->assertSession()->responseContains('Darth');
}
/**
* Tests the ContextualBundle filter plugin with exposed option.
*/
public function testContextualBundleExposed() {
$this->config('entity_browser.browser.bundle_filter')
->set('widgets.b882a89d-9ce4-4dfe-9802-62df93af232a.settings.view', 'bundle_filter_exposed')
->save();
$this->drupalLogin($this->adminUser);
$this->createNode(['type' => 'shark', 'title' => 'Luke']);
$this->createNode(['type' => 'jet', 'title' => 'Leia']);
$this->createNode(['type' => 'article', 'title' => 'Darth']);
$this->drupalGet('/node/add/test_entity_embed');
$this->assertSession()->waitForElement('css', 'a.cke_button__bundle_filter_test')->click();
$this->assertSession()->waitForId('views-exposed-form-bundle-filter-entity-browser-1');
$this->getSession()->switchToIFrame('entity_browser_iframe_bundle_filter');
// Check that only nodes of an allowed type are listed.
$this->assertSession()->responseContains('Luke');
$this->assertSession()->responseContains('Leia');
$this->assertSession()->responseNotContains('Darth');
// Test exposed form type filter.
$this->assertSession()->selectExists('Type')->selectOption('jet');
$this->assertSession()->buttonExists('Apply')->press();
$this->assertSession()->assertWaitOnAjaxRequest();
// Check that only nodes of the type selected in the exposed filter display.
$this->assertSession()->pageTextNotContains('Luke');
$this->assertSession()->pageTextContains('Leia');
$this->assertSession()->pageTextNotContains('Darth');
$this->assertSession()->selectExists('Type')->selectOption('shark');
$this->assertSession()->buttonExists('Apply')->press();
$this->assertSession()->assertWaitOnAjaxRequest();
// Check that only nodes of the type selected in the exposed filter display.
$this->assertSession()->pageTextContains('Luke');
$this->assertSession()->pageTextNotContains('Leia');
$this->assertSession()->pageTextNotContains('Darth');
$this->assertSession()->selectExists('Type')->selectOption('All');
$this->assertSession()->buttonExists('Apply')->press();
$this->assertSession()->assertWaitOnAjaxRequest();
// Check that only nodes of the type selected in the exposed filter display.
$this->assertSession()->pageTextContains('Luke');
$this->assertSession()->pageTextContains('Leia');
$this->assertSession()->pageTextNotContains('Darth');
// Change the allowed bundles on the entity embed.
$embed_button = $this->container->get('entity_type.manager')
->getStorage('embed_button')
->load('bundle_filter_test');
$type_settings = $embed_button->getTypeSettings();
$type_settings['bundles'] = [
'article' => 'article',
];
$embed_button->set('type_settings', $type_settings);
$embed_button->save();
// Test the new bundle settings are affecting what is visible in the view.
$this->drupalGet('/node/add/test_entity_embed');
$this->assertSession()->waitForElement('css', 'a.cke_button__bundle_filter_test')->click();
$this->assertSession()->waitForId('views-exposed-form-bundle-filter-entity-browser-1');
$this->getSession()->switchToIFrame('entity_browser_iframe_bundle_filter');
// Check that only nodes of an allowed type are listed.
$this->assertSession()->responseNotContains('Luke');
$this->assertSession()->responseNotContains('Leia');
$this->assertSession()->responseContains('Darth');
// If there is just one target_bundle, the contextual filter
// should not be visible.
$this->assertSession()->fieldNotExists('Type');
}
}
@@ -0,0 +1,242 @@
<?php
namespace Drupal\Tests\entity_browser\FunctionalJavascript;
use Drupal\FunctionalJavascriptTests\WebDriverTestBase;
use Drupal\Tests\ckeditor5\Traits\CKEditor5TestTrait;
/**
* Tests entity browser within entity embed.
*
* @group entity_browser
*
* @package Drupal\Tests\entity_browser\FunctionalJavascript
*/
class EntityEmbedTest extends WebDriverTestBase {
use CKEditor5TestTrait;
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = [
'entity_browser',
'entity_browser_test',
'embed',
'entity_embed',
'entity_browser_entity_embed_test',
];
/**
* The test administrative user.
*
* @var \Drupal\user\UserInterface
*/
protected $adminUser;
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->adminUser = $this->drupalCreateUser([
'access content',
'use text format full_html',
'create test_entity_embed content',
'access widget_context_default_value entity browser pages',
'access bundle_filter entity browser pages',
]);
}
/**
* Tests the EntityBrowserWidgetContext default argument plugin.
*/
public function testEntityBrowserWidgetContext() {
$this->drupalLogin($this->adminUser);
$this->createNode(['type' => 'shark', 'title' => 'Luke']);
$this->createNode(['type' => 'jet', 'title' => 'Leia']);
$this->createNode(['type' => 'article', 'title' => 'Darth']);
$this->drupalGet('/node/add/test_entity_embed');
$this->waitForEditor();
$this->pressEditorButton('Jet Shark Embed');
$this->assertSession()->waitForId('views-exposed-form-widget-context-default-value-entity-browser-1');
$this->getSession()->switchToIFrame('entity_browser_iframe_widget_context_default_value');
// Check that only nodes of an allowed type are listed.
$this->assertSession()->responseContains('Luke');
$this->assertSession()->responseContains('Leia');
$this->assertSession()->responseNotContains('Darth');
// Change the allowed bundles on the entity embed.
$embed_button = $this->container->get('entity_type.manager')
->getStorage('embed_button')
->load('jet_shark_embed');
$type_settings = $embed_button->getTypeSettings();
$type_settings['bundles'] = [
'article' => 'article',
];
$embed_button->set('type_settings', $type_settings);
$embed_button->save();
// Test the new bundle settings are affecting what is visible in the view.
$this->drupalGet('/node/add/test_entity_embed');
$this->waitForEditor();
$this->pressEditorButton('Jet Shark Embed');
$this->assertSession()->waitForId('views-exposed-form-widget-context-default-value-entity-browser-1');
$this->getSession()->switchToIFrame('entity_browser_iframe_widget_context_default_value');
// Check that only nodes of an allowed type are listed.
$this->assertSession()->responseNotContains('Luke');
$this->assertSession()->responseNotContains('Leia');
$this->assertSession()->responseContains('Darth');
}
/**
* Tests the ContextualBundle filter plugin.
*/
public function testContextualBundle() {
$this->drupalLogin($this->adminUser);
$this->createNode(['type' => 'shark', 'title' => 'Luke']);
$this->createNode(['type' => 'jet', 'title' => 'Leia']);
$this->createNode(['type' => 'article', 'title' => 'Darth']);
$this->drupalGet('/node/add/test_entity_embed');
$this->waitForEditor();
$this->pressEditorButton('Bundle Filter Test Embed');
$this->assertSession()->waitForId('views-exposed-form-bundle-filter-entity-browser-1');
$this->getSession()->switchToIFrame('entity_browser_iframe_bundle_filter');
// Check that only nodes of an allowed type are listed.
$this->assertSession()->responseContains('Luke');
$this->assertSession()->responseContains('Leia');
$this->assertSession()->responseNotContains('Darth');
// Change the allowed bundles on the entity embed.
$embed_button = $this->container->get('entity_type.manager')
->getStorage('embed_button')
->load('bundle_filter_test');
$type_settings = $embed_button->getTypeSettings();
$type_settings['bundles'] = [
'article' => 'article',
];
$embed_button->set('type_settings', $type_settings);
$embed_button->save();
// Test the new bundle settings are affecting what is visible in the view.
$this->drupalGet('/node/add/test_entity_embed');
$this->waitForEditor();
$this->pressEditorButton('Bundle Filter Test Embed');
$this->assertSession()->waitForId('views-exposed-form-bundle-filter-entity-browser-1');
$this->getSession()->switchToIFrame('entity_browser_iframe_bundle_filter');
// Check that only nodes of an allowed type are listed.
$this->assertSession()->responseNotContains('Luke');
$this->assertSession()->responseNotContains('Leia');
$this->assertSession()->responseContains('Darth');
}
/**
* Tests the ContextualBundle filter plugin with exposed option.
*/
public function testContextualBundleExposed() {
$this->config('entity_browser.browser.bundle_filter')
->set('widgets.b882a89d-9ce4-4dfe-9802-62df93af232a.settings.view', 'bundle_filter_exposed')
->save();
$this->drupalLogin($this->adminUser);
$this->createNode(['type' => 'shark', 'title' => 'Luke']);
$this->createNode(['type' => 'jet', 'title' => 'Leia']);
$this->createNode(['type' => 'article', 'title' => 'Darth']);
$this->drupalGet('/node/add/test_entity_embed');
$this->waitForEditor();
$this->pressEditorButton('Bundle Filter Test Embed');
$this->assertSession()->waitForId('views-exposed-form-bundle-filter-entity-browser-1');
$this->getSession()->switchToIFrame('entity_browser_iframe_bundle_filter');
// Check that only nodes of an allowed type are listed.
$this->assertSession()->responseContains('Luke');
$this->assertSession()->responseContains('Leia');
$this->assertSession()->responseNotContains('Darth');
// Test exposed form type filter.
$this->assertSession()->selectExists('Type')->selectOption('jet');
$this->assertSession()->buttonExists('Apply')->press();
$this->assertSession()->assertWaitOnAjaxRequest();
// Check that only nodes of the type selected in the exposed filter display.
$this->assertSession()->pageTextNotContains('Luke');
$this->assertSession()->pageTextContains('Leia');
$this->assertSession()->pageTextNotContains('Darth');
$this->assertSession()->selectExists('Type')->selectOption('shark');
$this->assertSession()->buttonExists('Apply')->press();
$this->assertSession()->assertWaitOnAjaxRequest();
// Check that only nodes of the type selected in the exposed filter display.
$this->assertSession()->pageTextContains('Luke');
$this->assertSession()->pageTextNotContains('Leia');
$this->assertSession()->pageTextNotContains('Darth');
$this->assertSession()->selectExists('Type')->selectOption('All');
$this->assertSession()->buttonExists('Apply')->press();
$this->assertSession()->assertWaitOnAjaxRequest();
// Check that only nodes of the type selected in the exposed filter display.
$this->assertSession()->pageTextContains('Luke');
$this->assertSession()->pageTextContains('Leia');
$this->assertSession()->pageTextNotContains('Darth');
// Change the allowed bundles on the entity embed.
$embed_button = $this->container->get('entity_type.manager')
->getStorage('embed_button')
->load('bundle_filter_test');
$type_settings = $embed_button->getTypeSettings();
$type_settings['bundles'] = [
'article' => 'article',
];
$embed_button->set('type_settings', $type_settings);
$embed_button->save();
// Test the new bundle settings are affecting what is visible in the view.
$this->drupalGet('/node/add/test_entity_embed');
$this->waitForEditor();
$this->pressEditorButton('Bundle Filter Test Embed');
$this->assertSession()->waitForId('views-exposed-form-bundle-filter-entity-browser-1');
$this->getSession()->switchToIFrame('entity_browser_iframe_bundle_filter');
// Check that only nodes of an allowed type are listed.
$this->assertSession()->responseNotContains('Luke');
$this->assertSession()->responseNotContains('Leia');
$this->assertSession()->responseContains('Darth');
// If there is just one target_bundle, the contextual filter
// should not be visible.
$this->assertSession()->fieldNotExists('Type');
}
}
@@ -0,0 +1,103 @@
<?php
namespace Drupal\Tests\entity_browser\FunctionalJavascript;
use Drupal\entityqueue\Entity\EntitySubqueue;
use Drupal\FunctionalJavascriptTests\WebDriverTestBase;
/**
* Tests entity browser used to manipulate EntitySubqueue.
*
* @group entity_browser
*
* @package Drupal\Tests\entity_browser\FunctionalJavascript
*/
class EntityQueueTest extends WebDriverTestBase {
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = [
'entity_browser',
'entity_browser_test',
'entityqueue',
'entity_browser_test_entityqueue',
];
/**
* The test administrative user.
*
* @var \Drupal\user\UserInterface
*/
protected $adminUser;
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->adminUser = $this->drupalCreateUser([
'access content',
'access widget_context_default_value entity browser pages',
'manipulate all entityqueues',
]);
}
/**
* Tests entityqueue buttons.
*/
public function testEntityQueueButtons() {
$this->drupalLogin($this->adminUser);
$article1 = $this->createNode(['type' => 'article', 'title' => 'Article 1']);
$article2 = $this->createNode(['type' => 'article', 'title' => 'Article 2']);
$article3 = $this->createNode(['type' => 'article', 'title' => 'Article 3']);
$subqueue = EntitySubqueue::load('nodes');
$subqueue->items->setValue([$article1, $article2, $article3]);
$subqueue->save();
$this->drupalGet('/admin/structure/entityqueue/nodes/nodes');
$correct_order = [
1 => 'Article 1',
2 => 'Article 2',
3 => 'Article 3',
];
foreach ($correct_order as $key => $value) {
$this->assertSession()
->elementContains('xpath', "(//div[contains(@class, 'item-container')])[" . $key . "]", $value);
}
$this->assertSession()->buttonExists('Reverse')->press();
$this->assertSession()->assertWaitOnAjaxRequest();
$correct_order = [
1 => 'Article 3',
2 => 'Article 2',
3 => 'Article 1',
];
foreach ($correct_order as $key => $value) {
$this->assertSession()
->elementContains('xpath', "(//div[contains(@class, 'item-container')])[" . $key . "]", $value);
}
$this->assertSession()->buttonExists('Clear')->press();
$this->assertSession()->assertWaitOnAjaxRequest();
$this->assertSession()
->elementNotExists('xpath', "//div[contains(@class, 'item-container')]");
}
}
@@ -0,0 +1,613 @@
<?php
namespace Drupal\Tests\entity_browser\FunctionalJavascript;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\entity_browser\Element\EntityBrowserElement;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\FunctionalJavascriptTests\SortableTestTrait;
use Drupal\node\Entity\Node;
use Drupal\user\Entity\Role;
/**
* Tests the Entity Reference Widget.
*
* @group entity_browser
*/
class EntityReferenceWidgetTest extends EntityBrowserWebDriverTestBase {
use SortableTestTrait;
/**
* {@inheritdoc}
*/
public function setUp(): void {
parent::setUp();
/** @var \Drupal\user\RoleInterface $role */
$role = Role::load('authenticated');
$this->grantPermissions($role, [
'access test_entity_browser_iframe_node_view entity browser pages',
'bypass node access',
'administer node form display',
'access contextual links',
]);
}
/**
* Tests Entity Reference widget.
*/
public function testEntityReferenceWidget() {
// Create an entity_reference field to test the widget.
$field_storage = FieldStorageConfig::create([
'field_name' => 'field_entity_reference1',
'type' => 'entity_reference',
'entity_type' => 'node',
'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
'settings' => [
'target_type' => 'node',
],
]);
$field_storage->save();
$field = FieldConfig::create([
'field_name' => 'field_entity_reference1',
'entity_type' => 'node',
'bundle' => 'article',
'label' => 'Referenced articles',
'settings' => [],
]);
$field->save();
/** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display */
$form_display = $this->container->get('entity_type.manager')
->getStorage('entity_form_display')
->load('node.article.default');
$form_display->setComponent('field_entity_reference1', [
'type' => 'entity_browser_entity_reference',
'settings' => [
'entity_browser' => 'test_entity_browser_iframe_node_view',
'open' => TRUE,
'field_widget_edit' => TRUE,
'field_widget_remove' => TRUE,
'field_widget_replace' => FALSE,
'selection_mode' => EntityBrowserElement::SELECTION_MODE_APPEND,
'field_widget_display' => 'rendered_entity',
'field_widget_display_settings' => [
'view_mode' => 'teaser',
],
],
])->save();
// Create a dummy node that will be used as target.
$target_node = Node::create([
'title' => 'Walrus',
'type' => 'article',
]);
$target_node->save();
$target_node_translation = $target_node->addTranslation('fr', $target_node->toArray());
$target_node_translation->setTitle('le Morse');
$target_node_translation->save();
$this->drupalGet('/node/add/article');
$this->assertSession()->fieldExists('title[0][value]')->setValue('Referencing node 1');
$this->getSession()->switchToIFrame('entity_browser_iframe_test_entity_browser_iframe_node_view');
$this->assertSession()->fieldExists('entity_browser_select[node:1]')->check();
$this->assertSession()->buttonExists('Select entities')->press();
$this->waitForAjaxToFinish();
$this->getSession()->switchToIFrame();
$this->assertTrue($this->assertSession()->waitForText('Walrus'));
$this->assertSession()->buttonExists('Save')->press();
$this->assertSession()->pageTextContains('Article Referencing node 1 has been created.');
$nid = \Drupal::entityQuery('node')->accessCheck(TRUE)->condition('title', 'Referencing node 1')->execute();
$nid = reset($nid);
// Assert correct translation appears.
// @see Drupal\entity_browser\Plugin\EntityBrowser\FieldWidgetDisplay\EntityLabel
$this->drupalGet('fr/node/' . $nid . '/edit');
$this->assertSession()->pageTextContains('le Morse');
$this->drupalGet('node/' . $nid . '/edit');
$this->assertSession()->pageTextContains('Walrus');
// Make sure both "Edit" and "Remove" buttons are visible.
$this->assertSession()->buttonExists('edit-field-entity-reference1-current-items-0-remove-button');
$this->assertSession()->buttonExists('edit-field-entity-reference1-current-items-0-edit-button')->press();
// Make sure the contextual links are not present.
$this->assertSession()->elementNotExists('css', '.contextual-links');
// Test edit dialog by changing title of referenced entity.
$edit_dialog = $this->assertSession()->waitForElement('xpath', '//div[contains(@id, "node-' . $target_node->id() . '-edit-dialog")]');
$title_field = $edit_dialog->findField('title[0][value]');
$title = $title_field->getValue();
$this->assertEquals('Walrus', $title);
$title_field->setValue('Alpaca');
$this->assertSession()
->elementExists('css', '.ui-dialog-buttonset.form-actions .form-submit')
->press();
$this->waitForAjaxToFinish();
// Check that new title is displayed.
$this->assertSession()->pageTextNotContains('Walrus');
$this->assertSession()->pageTextContains('Alpaca');
// Test whether changing these definitions on the browser config effectively
// change the visibility of the buttons.
$form_display->setComponent('field_entity_reference1', [
'type' => 'entity_browser_entity_reference',
'settings' => [
'entity_browser' => 'test_entity_browser_iframe_node_view',
'open' => TRUE,
'field_widget_edit' => FALSE,
'field_widget_remove' => FALSE,
'field_widget_replace' => FALSE,
'selection_mode' => EntityBrowserElement::SELECTION_MODE_APPEND,
'field_widget_display' => 'label',
'field_widget_display_settings' => [],
],
])->save();
$this->drupalGet('node/' . $nid . '/edit');
$this->assertSession()->buttonNotExists('edit-field-entity-reference1-current-items-0-remove-button');
$this->assertSession()->buttonNotExists('edit-field-entity-reference1-current-items-0-edit-button');
// Set them to visible again.
$form_display->setComponent('field_entity_reference1', [
'type' => 'entity_browser_entity_reference',
'settings' => [
'entity_browser' => 'test_entity_browser_iframe_node_view',
'open' => TRUE,
'field_widget_edit' => TRUE,
'field_widget_remove' => TRUE,
'field_widget_replace' => FALSE,
'selection_mode' => EntityBrowserElement::SELECTION_MODE_APPEND,
'field_widget_display' => 'label',
'field_widget_display_settings' => [],
],
])->save();
$this->drupalGet('node/' . $nid . '/edit');
$remove_button = $this->assertSession()->buttonExists('edit-field-entity-reference1-current-items-0-remove-button');
$this->assertEquals('Remove', $remove_button->getValue());
$this->assertTrue($remove_button->hasClass('remove-button'));
$edit_button = $this->assertSession()->buttonExists('edit-field-entity-reference1-current-items-0-edit-button');
$this->assertEquals('Edit', $edit_button->getValue());
$this->assertTrue($edit_button->hasClass('edit-button'));
// Make sure the "Replace" button is not there.
$this->assertSession()->buttonNotExists('edit-field-entity-reference1-current-items-0-replace-button');
// Test the "Remove" button on the widget works.
$this->assertSession()->buttonExists('Remove')->press();
$this->waitForAjaxToFinish();
$this->assertSession()->pageTextNotContains('Alpaca');
// Test the "Replace" button functionality.
$form_display->setComponent('field_entity_reference1', [
'type' => 'entity_browser_entity_reference',
'settings' => [
'entity_browser' => 'test_entity_browser_iframe_node_view',
'open' => TRUE,
'field_widget_edit' => TRUE,
'field_widget_remove' => TRUE,
'field_widget_replace' => TRUE,
'selection_mode' => EntityBrowserElement::SELECTION_MODE_APPEND,
'field_widget_display' => 'label',
'field_widget_display_settings' => [],
],
])->save();
// In order to ensure the replace button opens the browser, it needs to be
// closed.
/** @var \Drupal\entity_browser\EntityBrowserInterface $browser */
$browser = $this->container->get('entity_type.manager')
->getStorage('entity_browser')
->load('test_entity_browser_iframe_node_view');
$browser->getDisplay()
->setConfiguration([
'width' => 650,
'height' => 500,
'link_text' => 'Select entities',
'auto_open' => FALSE,
]);
$browser->save();
// We'll need a third node to be able to make a new selection.
$target_node2 = Node::create([
'title' => 'Target example node 2',
'type' => 'article',
]);
$target_node2->save();
$this->drupalGet('node/' . $nid . '/edit');
// If there is only one entity in the current selection the button should
// show up.
$replace_button = $this->assertSession()->buttonExists('edit-field-entity-reference1-current-items-0-replace-button');
$this->assertEquals('Replace', $replace_button->getValue());
$this->assertTrue($replace_button->hasClass('replace-button'));
// Clicking on the button should empty the selection and automatically
// open the browser again.
$replace_button->click();
$this->waitForAjaxToFinish();
$this->getSession()->switchToIFrame('entity_browser_iframe_test_entity_browser_iframe_node_view');
$this->assertSession()->fieldExists('entity_browser_select[node:3]')->check();
$this->assertSession()->buttonExists('Select entities')->press();
$this->waitForAjaxToFinish();
$this->getSession()->switchToIFrame();
if (!$this->coreVersion('10.2')) {
$this->assertSession()->assertWaitOnAjaxRequest();
}
// Even in the AJAX-built markup for the newly selected element, the replace
// button should be there.
$this->assertSession()->elementExists('css', 'input[data-drupal-selector="edit-field-entity-reference1-current-items-0-replace-button"]');
// Adding a new node to the selection, however, should make it disappear.
$open_iframe_link = $this->assertSession()->elementExists('css', 'a[data-drupal-selector="edit-field-entity-reference1-entity-browser-entity-browser-link"]');
$open_iframe_link->click();
$this->getSession()->switchToIFrame('entity_browser_iframe_test_entity_browser_iframe_node_view');
$this->assertSession()->fieldExists('entity_browser_select[node:1]')->check();
$this->assertSession()->buttonExists('Select entities')->press();
$this->waitForAjaxToFinish();
$this->getSession()->switchToIFrame();
if (!$this->coreVersion('10.2')) {
$this->assertSession()->assertWaitOnAjaxRequest();
}
$this->assertSession()->elementNotExists('css', 'input[data-drupal-selector="edit-field-entity-reference1-current-items-0-replace-button"]');
$this->assertSession()->buttonExists('Save')->press();
$this->assertSession()->pageTextContains('Article Referencing node 1 has been updated.');
// Test the replace button again with different field cardinalities.
FieldStorageConfig::load('node.field_entity_reference1')->setCardinality(1)->save();
$this->drupalGet('/node/add/article');
$this->assertSession()->fieldExists('title[0][value]')->setValue('Referencing node 2');
$open_iframe_link = $this->assertSession()->elementExists('css', 'a[data-drupal-selector="edit-field-entity-reference1-entity-browser-entity-browser-link"]');
$open_iframe_link->click();
$this->getSession()->switchToIFrame('entity_browser_iframe_test_entity_browser_iframe_node_view');
$this->assertSession()->fieldExists('entity_browser_select[node:1]')->check();
$this->assertSession()->buttonExists('Select entities')->press();
$this->waitForAjaxToFinish();
$this->getSession()->switchToIFrame();
if (!$this->coreVersion('10.2')) {
$this->assertSession()->assertWaitOnAjaxRequest();
}
$this->assertSession()->elementContains('css', '#edit-field-entity-reference1-wrapper', 'Alpaca');
// All three buttons should be visible.
$this->assertSession()->elementExists('css', 'input[data-drupal-selector="edit-field-entity-reference1-current-items-0-remove-button"]');
$this->assertSession()->elementExists('css', 'input[data-drupal-selector="edit-field-entity-reference1-current-items-0-edit-button"]');
$replace_button = $this->assertSession()->elementExists('css', 'input[data-drupal-selector="edit-field-entity-reference1-current-items-0-replace-button"]');
// Clicking on the button should empty the selection and automatically
// open the browser again.
$replace_button->click();
$this->waitForAjaxToFinish();
$this->getSession()->switchToIFrame('entity_browser_iframe_test_entity_browser_iframe_node_view');
$this->assertSession()->fieldExists('entity_browser_select[node:2]')->check();
$this->assertSession()->buttonExists('Select entities')->press();
$this->waitForAjaxToFinish();
$this->getSession()->switchToIFrame();
$this->assertSession()->elementContains('css', '#edit-field-entity-reference1-wrapper', 'Referencing node 1');
// Do the same as above but now with cardinality 2.
FieldStorageConfig::load('node.field_entity_reference1')
->setCardinality(2)
->save();
$this->drupalGet('/node/add/article');
$this->assertSession()->fieldExists('title[0][value]')->setValue('Referencing node 3');
$open_iframe_link = $this->assertSession()->elementExists('css', 'a[data-drupal-selector="edit-field-entity-reference1-entity-browser-entity-browser-link"]');
$open_iframe_link->click();
$this->getSession()->switchToIFrame('entity_browser_iframe_test_entity_browser_iframe_node_view');
$this->assertSession()->fieldExists('entity_browser_select[node:1]')->check();
$this->assertSession()->buttonExists('Select entities')->press();
$this->waitForAjaxToFinish();
$this->getSession()->switchToIFrame();
if (!$this->coreVersion('10.2')) {
$this->assertSession()->assertWaitOnAjaxRequest();
}
$this->assertSession()->elementContains('css', '#edit-field-entity-reference1-wrapper', 'Alpaca');
// All three buttons should be visible.
$this->assertSession()->elementExists('css', 'input[data-drupal-selector="edit-field-entity-reference1-current-items-0-remove-button"]');
$this->assertSession()->elementExists('css', 'input[data-drupal-selector="edit-field-entity-reference1-current-items-0-edit-button"]');
$replace_button = $this->assertSession()->elementExists('css', 'input[data-drupal-selector="edit-field-entity-reference1-current-items-0-replace-button"]');
// Clicking on the button should empty the selection and automatically
// open the browser again.
$replace_button->click();
$this->waitForAjaxToFinish();
$this->getSession()->switchToIFrame('entity_browser_iframe_test_entity_browser_iframe_node_view');
$this->assertSession()->fieldExists('entity_browser_select[node:2]')->check();
$this->assertSession()->buttonExists('Select entities')->press();
$this->waitForAjaxToFinish();
$this->getSession()->switchToIFrame();
if (!$this->coreVersion('10.2')) {
$this->assertSession()->assertWaitOnAjaxRequest();
}
$this->assertSession()->elementContains('css', '#edit-field-entity-reference1-wrapper', 'Referencing node 1');
// Verify that if the user cannot edit the entity, the "Edit" button does
// not show up, even if configured to.
/** @var \Drupal\user\RoleInterface $role */
$role = Role::load('authenticated');
$role->revokePermission('bypass node access')->trustData()->save();
$this->drupalGet('node/add/article');
$open_iframe_link = $this->assertSession()->elementExists('css', 'a[data-drupal-selector="edit-field-entity-reference1-entity-browser-entity-browser-link"]');
$open_iframe_link->click();
$this->getSession()->switchToIFrame('entity_browser_iframe_test_entity_browser_iframe_node_view');
$this->assertSession()->fieldExists('entity_browser_select[node:1]')->check();
$this->assertSession()->buttonExists('Select entities')->press();
$this->waitForAjaxToFinish();
$this->getSession()->switchToIFrame();
if (!$this->coreVersion('10.2')) {
$this->assertSession()->assertWaitOnAjaxRequest();
}
$this->assertSession()->buttonNotExists('edit-field-entity-reference1-current-items-0-edit-button');
}
/**
* Tests that drag and drop functions properly.
*/
public function testDragAndDrop() {
$assert_session = $this->assertSession();
$time = time();
$gatsby = $this->createNode([
'type' => 'shark',
'title' => 'Gatsby',
'created' => $time--,
]);
$daisy = $this->createNode([
'type' => 'jet',
'title' => 'Daisy',
'created' => $time--,
]);
$nick = $this->createNode([
'type' => 'article',
'title' => 'Nick',
'created' => $time--,
]);
$santa = $this->createNode([
'type' => 'shark',
'title' => 'Santa Claus',
'created' => $time--,
]);
$easter_bunny = $this->createNode([
'type' => 'jet',
'title' => 'Easter Bunny',
'created' => $time--,
]);
$pumpkin_king = $this->createNode([
'type' => 'article',
'title' => 'Pumpkin King',
'created' => $time--,
]);
$field1_storage_config = [
'field_name' => 'field_east_egg',
'type' => 'entity_reference',
'entity_type' => 'node',
'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
'settings' => [
'target_type' => 'node',
],
];
$field2_storage_config = [
'field_name' => 'field_east_egg2',
] + $field1_storage_config;
$field_storage = FieldStorageConfig::create($field1_storage_config);
$field_storage->save();
$field_storage2 = FieldStorageConfig::create($field2_storage_config);
$field_storage2->save();
$field1_config = [
'field_name' => 'field_east_egg',
'entity_type' => 'node',
'bundle' => 'article',
'label' => 'East Eggers',
'settings' => [
'handler_settings' => [
'target_bundles' => [
'shark' => 'shark',
'jet' => 'jet',
'article' => 'article',
],
],
],
];
$field2_config = [
'field_name' => 'field_east_egg2',
'label' => 'Easter Eggs',
] + $field1_config;
$field = FieldConfig::create($field1_config);
$field->save();
$field2 = FieldConfig::create($field2_config);
$field2->save();
/** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display */
$form_display = $this->container->get('entity_type.manager')
->getStorage('entity_form_display')
->load('node.article.default');
$form_display->removeComponent('field_reference');
$field_widget_config = [
'type' => 'entity_browser_entity_reference',
'settings' => [
'entity_browser' => 'widget_context_default_value',
'table_settings' => [
'status_column' => TRUE,
'bundle_column' => TRUE,
'label_column' => FALSE,
],
'open' => FALSE,
'field_widget_edit' => TRUE,
'field_widget_remove' => TRUE,
'field_widget_replace' => FALSE,
'selection_mode' => EntityBrowserElement::SELECTION_MODE_APPEND,
'field_widget_display' => 'label',
'field_widget_display_settings' => [],
],
];
$form_display->setComponent('field_east_egg', $field_widget_config)->save();
$form_display->setComponent('field_east_egg2', $field_widget_config)->save();
// Set auto open to false on the entity browser.
$entity_browser = $this->container->get('entity_type.manager')
->getStorage('entity_browser')
->load('widget_context_default_value');
$display_configuration = $entity_browser->get('display_configuration');
$display_configuration['auto_open'] = FALSE;
$entity_browser->set('display_configuration', $display_configuration);
$entity_browser->save();
$account = $this->drupalCreateUser([
'access widget_context_default_value entity browser pages',
'create article content',
'access content',
]);
$this->drupalLogin($account);
$this->drupalGet('node/add/article');
$this->assertSession()->elementExists('xpath', '(//summary)[1]')->click();
// Open the entity browser widget form.
$this->getSession()->getPage()->clickLink('Select entities');
$this->getSession()->switchToIFrame('entity_browser_iframe_widget_context_default_value');
$this->assertSession()->fieldExists('entity_browser_select[node:' . $gatsby->id() . ']')->check();
$this->assertSession()->fieldExists('entity_browser_select[node:' . $daisy->id() . ']')->check();
$this->assertSession()->fieldExists('entity_browser_select[node:' . $nick->id() . ']')->check();
$this->assertSession()->buttonExists('Select entities')->press();
$this->assertSession()->buttonExists('Use selected')->press();
$this->assertSession()->assertWaitOnAjaxRequest();
$this->getSession()->switchToIFrame();
if (!$this->coreVersion('10.2')) {
$this->assertSession()->assertWaitOnAjaxRequest();
}
$correct_order = [
1 => 'Gatsby',
2 => 'Daisy',
3 => 'Nick',
];
foreach ($correct_order as $key => $value) {
$this->assertSession()
->elementContains('xpath', "(//div[contains(@class, 'item-container')])[" . $key . "]", $value);
}
// Close details 1.
$this->assertSession()->elementExists('xpath', '(//summary)[1]')->click();
// Open details 2.
$this->assertSession()->elementExists('xpath', '(//summary)[2]')->click();
// Open the entity browser widget form.
$this->assertSession()->elementExists('xpath', "(//a[contains(text(), 'Select entities')])[2]")->click();
$this->getSession()->switchToIFrame('entity_browser_iframe_widget_context_default_value');
$this->assertSession()->fieldExists('entity_browser_select[node:' . $santa->id() . ']')->check();
$this->assertSession()->fieldExists('entity_browser_select[node:' . $easter_bunny->id() . ']')->check();
$this->assertSession()->fieldExists('entity_browser_select[node:' . $pumpkin_king->id() . ']')->check();
$this->assertSession()->buttonExists('Select entities')->press();
$this->assertSession()->buttonExists('Use selected')->press();
$this->waitForAjaxToFinish();
$this->getSession()->switchToIFrame();
if (!$this->coreVersion('10.2')) {
$this->assertSession()->assertWaitOnAjaxRequest();
}
// Close details 2.
$this->assertSession()->elementExists('xpath', '(//summary)[2]')->click();
// Open details 1.
$this->assertSession()->elementExists('xpath', '(//summary)[1]')->click();
// In the first set of selections, drag the first item into the second
// position.
$list_selector = '[data-drupal-selector="edit-field-east-egg-current"]';
$item_selector = "$list_selector .item-container";
$assert_session->elementsCount('css', $item_selector, 3);
$this->sortableAfter("$item_selector:first-child", "$item_selector:nth-child(2)", $list_selector);
$this->assertSession()->fieldExists('title[0][value]')->setValue('Hello World');
$this->assertSession()->buttonExists('Save')->press();
$this->drupalGet('node/7/edit');
$correct_order = [
1 => 'Daisy',
2 => 'Gatsby',
3 => 'Nick',
4 => 'Santa Claus',
5 => 'Easter Bunny',
6 => 'Pumpkin King',
];
foreach ($correct_order as $key => $value) {
$this->assertSession()
->elementContains('xpath', "(//div[contains(@class, 'item-container')])[" . $key . "]", $value);
}
// In the second set of selections, drag the first item into the second
// position.
$list_selector = '[data-drupal-selector="edit-field-east-egg2-current"]';
$item_selector = "$list_selector .item-container";
$assert_session->elementsCount('css', $item_selector, 3);
$this->sortableAfter("$item_selector:first-child", "$item_selector:nth-child(2)", $list_selector);
$correct_order = [
4 => 'Easter Bunny',
5 => 'Santa Claus',
6 => 'Pumpkin King',
];
foreach ($correct_order as $key => $value) {
$this->assertSession()
->elementContains('xpath', "(//div[contains(@class, 'item-container')])[" . $key . "]", $value);
}
// Test that order is preserved after removing item.
$this->assertSession()
->elementExists('xpath', '(//input[contains(@class, "remove-button")])[5]')
->press();
$this->waitForAjaxToFinish();
$correct_order = [
4 => 'Easter Bunny',
5 => 'Pumpkin King',
];
foreach ($correct_order as $key => $value) {
$this->assertSession()
->elementContains('xpath', "(//div[contains(@class, 'item-container')])[" . $key . "]", $value);
}
}
/**
* {@inheritdoc}
*/
protected function sortableUpdate($item, $from, $to = NULL) {
list ($container) = explode(' ', $item, 2);
$js = <<<END
Drupal.entityBrowserEntityReference.entitiesReordered(document.querySelector("$container"));
END;
$this->getSession()->executeScript($js);
}
}
@@ -0,0 +1,233 @@
<?php
namespace Drupal\Tests\entity_browser\FunctionalJavascript;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\entity_browser\Element\EntityBrowserElement;
use Drupal\entity_browser\Entity\EntityBrowser;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\FunctionalJavascriptTests\WebDriverTestBase;
/**
* Tests the config UI for adding and editing entity browsers.
*
* @group entity_browser
*
* @package Drupal\Tests\entity_browser\FunctionalJavascript
*/
class FieldWidgetConfigTest extends WebDriverTestBase {
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = [
'entity_browser',
'entity_browser_test',
'block',
'node',
'taxonomy',
'views',
'token',
'field_ui',
// Drupal 10 has a regression that widget settings form error messages are
// not visible without having this module enabled.
// @see https://www.drupal.org/project/drupal/issues/3407134
'inline_form_errors',
];
/**
* The test administrative user.
*
* @var \Drupal\user\UserInterface
*/
protected $adminUser;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->drupalPlaceBlock('local_tasks_block');
$this->drupalPlaceBlock('local_actions_block');
$this->adminUser = $this->drupalCreateUser([
'administer entity browsers',
'access administration pages',
'administer node fields',
'administer node display',
'administer nodes',
'administer node form display',
'create article content',
]);
$this->drupalLogin($this->adminUser);
}
/**
* Test ajax for display plugin setting.
*/
public function testAjax() {
// Create an entity_reference field to test the widget.
$field_storage = FieldStorageConfig::create([
'field_name' => 'field_humperdinck',
'type' => 'entity_reference',
'entity_type' => 'node',
'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
'settings' => [
'target_type' => 'node',
],
]);
$field_storage->save();
$field = FieldConfig::create([
'field_name' => 'field_humperdinck',
'entity_type' => 'node',
'bundle' => 'article',
'label' => 'Prince of Florin',
'settings' => [
'handler' => 'default:node',
'handler_settings' => [
'target_bundles' => [
'article' => 'article',
],
],
],
]);
$field->save();
/** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display */
$form_display = $this->container->get('entity_type.manager')
->getStorage('entity_form_display')
->load('node.article.default');
$form_display->setComponent('field_humperdinck', [
'type' => 'entity_browser_entity_reference',
'settings' => [
'entity_browser' => 'test_entity_browser_iframe_node_view',
'open' => TRUE,
'field_widget_edit' => TRUE,
'field_widget_remove' => TRUE,
'field_widget_replace' => FALSE,
'selection_mode' => EntityBrowserElement::SELECTION_MODE_APPEND,
'field_widget_display' => 'label',
'field_widget_display_settings' => [],
],
])->save();
$this->drupalGet('/admin/structure/types/manage/article/form-display');
$this->assertSession()->waitforButton('field_humperdinck_settings_edit')->press();
$this->assertSession()->assertWaitOnAjaxRequest();
$form_prefix = 'fields[field_humperdinck][settings_edit_form][settings]';
$display = $this->assertSession()->fieldExists($form_prefix . '[field_widget_display]');
$this->assertEquals('label', $display->getValue());
$details_selector = 'details[data-drupal-selector="edit-fields-field-humperdinck-settings-edit-form-settings-field-widget-display-settings"]';
// Test that switching display plugin returns appropriate plugin
// settings form.
$options = [
'rendered_entity' => 'Select view mode to be used when rendering entities.',
'label' => 'This plugin has no configuration options.',
];
for ($i = 0; $i < 3; $i++) {
foreach ($options as $option => $target_text) {
$display->setValue($option);
$this->assertSession()->assertWaitOnAjaxRequest();
$this->assertSession()
->elementContains('css', $details_selector, $target_text);
}
}
}
/**
* Tests 'selection_edit' validation on field widget form and warning message on content entity forms.
*/
public function testSelectionModeValidation() {
// Create an entity_reference field to test the widget.
$field_storage = FieldStorageConfig::create([
'field_name' => 'field_dalek',
'type' => 'entity_reference',
'entity_type' => 'node',
'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
'settings' => [
'target_type' => 'node',
],
]);
$field_storage->save();
$field = FieldConfig::create([
'field_name' => 'field_dalek',
'entity_type' => 'node',
'bundle' => 'article',
'label' => 'Seek! Locate! Exterminate!',
'settings' => [],
]);
$field->save();
$this->drupalGet('/admin/structure/types/manage/article/form-display');
// Drag to enabled.
$target = $this->assertSession()
->elementExists('css', '#title');
$this->assertSession()
->elementExists('css', '#field-dalek')
->find('css', '.handle')
->dragTo($target);
$this->assertSession()->assertWaitOnAjaxRequest();
// Set to Entity Browser Widget.
$this->assertSession()->selectExists('fields[field_dalek][type]')->selectOption('entity_browser_entity_reference');
$this->assertSession()->assertWaitOnAjaxRequest();
// Open settings form.
$this->assertSession()->waitforButton('field_dalek_settings_edit')->press();
$this->assertSession()->assertWaitOnAjaxRequest();
$form_prefix = 'fields[field_dalek][settings_edit_form][settings]';
// Select entity browser with "no_selection" selection display.
$this->assertSession()->selectExists($form_prefix . '[entity_browser]')->selectOption('test_entity_browser_iframe_node_view');
$this->assertSession()->selectExists($form_prefix . '[selection_mode]')->selectOption('selection_edit');
$this->assertSession()->buttonExists('field_dalek_plugin_settings_update')->press();
$this->assertSession()->assertWaitOnAjaxRequest();
$this->assertSession()->selectExists($form_prefix . '[entity_browser]')->hasClass('error');
$this->assertSession()->selectExists($form_prefix . '[selection_mode]')->hasClass('error');
$error_message = 'The selection mode Edit selection requires an entity browser with a selection display plugin that supports preselection. Either change the selection mode or update the Test entity browser iframe with view widget for nodes entity browser to use a selection display plugin that supports preselection.';
$this->assertSession()->pageTextContains($error_message);
// Switch to an entity browser that supports preselection.
$this->assertSession()->selectExists($form_prefix . '[entity_browser]')->selectOption('test_entity_browser_iframe_view');
$this->assertSession()->buttonExists('field_dalek_plugin_settings_update')->press();
$this->assertSession()->assertWaitOnAjaxRequest();
$this->assertSession()->responseNotContains($error_message);
$this->assertSession()->buttonExists('Save')->press();
// Update selected entity browser so it will trigger a warning.
$entity_browser = EntityBrowser::load('test_entity_browser_iframe_view');
$entity_browser->setSelectionDisplay('no_display');
$entity_browser->save();
$this->drupalGet('/node/add/article');
// Error message should be shown.
$this->assertSession()->pageTextContains('There is a configuration problem with field "Seek! Locate! Exterminate!". The selection mode Edit selection requires an entity browser with a selection display plugin that supports preselection. Either change the selection mode or update the Test entity browser iframe with view widget entity browser to use a selection display plugin that supports preselection.');
}
}
@@ -0,0 +1,259 @@
<?php
namespace Drupal\Tests\entity_browser\FunctionalJavascript;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\entity_browser\Element\EntityBrowserElement;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\file\Entity\File;
use Drupal\node\Entity\Node;
use Drupal\Tests\TestFileCreationTrait;
/**
* Tests the image field widget.
*
* @group entity_browser
*/
class ImageFieldTest extends EntityBrowserWebDriverTestBase {
use TestFileCreationTrait;
/**
* Created file entity.
*
* @var \Drupal\file\Entity\File
*/
protected $image;
/**
* {@inheritdoc}
*/
public function setUp(): void {
parent::setUp();
FieldStorageConfig::create([
'field_name' => 'field_image',
'type' => 'image',
'entity_type' => 'node',
'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
])->save();
FieldConfig::create([
'field_name' => 'field_image',
'entity_type' => 'node',
'bundle' => 'article',
'label' => 'Images',
'settings' => [
'file_extensions' => 'jpg',
'file_directory' => 'entity-browser-test',
'max_resolution' => '40x40',
'title_field' => TRUE,
],
])->save();
$test_files = $this->getTestFiles('image');
foreach ($test_files as $test_file) {
if ($test_file->filename === 'image-test.jpg') {
break;
}
}
$file_system = $this->container->get('file_system');
$file_system->copy($file_system->realpath($test_file->uri), 'public://example.jpg');
$this->image = File::create([
'uri' => 'public://example.jpg',
]);
$this->image->save();
// Register usage for this file to avoid validation errors when referencing
// this file on node save.
\Drupal::service('file.usage')->add($this->image, 'entity_browser', 'test', '1');
/** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display */
$form_display = $this->container->get('entity_type.manager')
->getStorage('entity_form_display')
->load('node.article.default');
$form_display->setComponent('field_image', [
'type' => 'entity_browser_file',
'settings' => [
'entity_browser' => 'test_entity_browser_iframe_view',
'open' => TRUE,
'field_widget_edit' => FALSE,
'field_widget_remove' => TRUE,
'field_widget_replace' => TRUE,
'selection_mode' => EntityBrowserElement::SELECTION_MODE_APPEND,
'view_mode' => 'default',
'preview_image_style' => 'thumbnail',
],
])->save();
$display_config = [
'width' => '650',
'height' => '500',
'link_text' => 'Select images',
];
/** @var \Drupal\entity_browser\EntityBrowserInterface $browser */
$browser = $this->container->get('entity_type.manager')
->getStorage('entity_browser')
->load('test_entity_browser_iframe_view');
$browser->setDisplay('iframe');
$browser->getDisplay()->setConfiguration($display_config);
$browser->addWidget([
// These settings should get overridden by our field settings.
'settings' => [
'upload_location' => 'public://',
'extensions' => 'png',
],
'weight' => 1,
'label' => 'Upload images',
'id' => 'upload',
]);
$browser->setWidgetSelector('tabs');
$browser->save();
$account = $this->drupalCreateUser([
'access test_entity_browser_iframe_view entity browser pages',
'create article content',
'edit own article content',
'access content',
]);
$this->drupalLogin($account);
}
/**
* Tests basic usage for an image field.
*/
public function testImageFieldUsage() {
$this->drupalGet('node/add/article');
$this->assertSession()->linkExists('Select images');
$this->getSession()->getPage()->clickLink('Select images');
$this->getSession()->switchToIFrame('entity_browser_iframe_test_entity_browser_iframe_view');
$this->getSession()->getPage()->checkField('entity_browser_select[file:' . $this->image->id() . ']');
$this->getSession()->getPage()->pressButton('Select entities');
$button = $this->assertSession()->waitForButton('Use selected');
$this->assertSession()->pageTextContains('example.jpg');
$button->press();
$this->waitForAjaxToFinish();
// Switch back to the main page.
$this->getSession()->switchToIFrame();
// Check if the image thumbnail exists.
$this->assertSession()
->waitForElementVisible('xpath', '//tr[@data-drupal-selector="edit-field-image-current-1"]');
// Test if the image filename is present.
$this->assertSession()->pageTextContains('example.jpg');
// Test specifying Alt and Title texts and saving the node.
$alt_text = 'Test alt text.';
$title_text = 'Test title text.';
$this->getSession()->getPage()->fillField('field_image[current][1][meta][alt]', $alt_text);
$this->getSession()->getPage()->fillField('field_image[current][1][meta][title]', $title_text);
$this->getSession()->getPage()->fillField('title[0][value]', 'Node 1');
$this->getSession()->getPage()->pressButton('Save');
$this->assertSession()->pageTextContains('Article Node 1 has been created.');
$node = Node::load(1);
$saved_alt = $node->get('field_image')[0]->alt;
$this->assertEquals($saved_alt, $alt_text);
$saved_title = $node->get('field_image')[0]->title;
$this->assertEquals($saved_title, $title_text);
// Test the Delete functionality.
$this->drupalGet('node/1/edit');
$this->assertSession()->buttonExists('Remove');
$this->getSession()->getPage()->pressButton('Remove');
$this->waitForAjaxToFinish();
// Image filename should not be present.
$this->assertSession()->pageTextNotContains('example.jpg');
$this->assertSession()->linkExists('Select entities');
// Test the Replace functionality.
$test_files = $this->getTestFiles('image');
foreach ($test_files as $test_file) {
if ($test_file->filename === 'image-test.jpg') {
break;
}
}
$file_system = $this->container->get('file_system');
$file_system->copy($file_system->realpath($test_file->uri), 'public://example2.jpg');
$image2 = File::create(['uri' => 'public://example2.jpg']);
$image2->save();
\Drupal::service('file.usage')->add($image2, 'entity_browser', 'test', '1');
$this->drupalGet('node/1/edit');
$this->assertSession()->buttonExists('Replace');
$this->getSession()->getPage()->pressButton('Replace');
$this->waitForAjaxToFinish();
$this->getSession()->switchToIFrame('entity_browser_iframe_test_entity_browser_iframe_view');
$this->getSession()->getPage()->checkField('entity_browser_select[file:' . $image2->id() . ']');
$this->getSession()->getPage()->pressButton('Select entities');
$this->getSession()->getPage()->pressButton('Use selected');
$this->getSession()->wait(1000);
$this->getSession()->switchToIFrame();
$this->waitForAjaxToFinish();
// Initial image should not be present, the new one should be there instead.
$this->assertSession()->pageTextNotContains('example.jpg');
$this->assertSession()->pageTextContains('example2.jpg');
}
/**
* Tests that settings are passed from the image field to the upload widget.
*/
public function testImageFieldSettings() {
$root = \Drupal::root();
$file_wrong_type = $root . '/core/misc/druplicon.png';
$test_files = $this->getTestFiles('image');
$file_system = $this->container->get('file_system');
foreach ($test_files as $test_file) {
if ($test_file->filename === 'image-test.jpg') {
$file_just_right = $file_system->realpath($test_file->uri);
}
elseif ($test_file->filename === 'image-2.jpg') {
$file_too_big = $file_system->realpath($test_file->uri);
}
}
$this->drupalGet('node/add/article');
$this->assertSession()->linkExists('Select images');
$this->getSession()->getPage()->clickLink('Select images');
$this->getSession()->switchToIFrame('entity_browser_iframe_test_entity_browser_iframe_view');
// Switch to the image tab.
$this->clickLink('Upload images');
// Attempt to upload an invalid image type. The upload widget is configured
// to allow png but the field widget is configured to allow jpg, so we
// expect the field to override the widget.
$this->getSession()->getPage()->attachFileToField('files[upload][]', $file_wrong_type);
if (version_compare(\Drupal::VERSION, '8.7', '>=')) {
$this->assertSession()->responseContains('Only files with the following extensions are allowed: <em class="placeholder">jpg</em>.');
$this->assertSession()->responseContains('The selected file <em class="placeholder">druplicon.png</em> cannot be uploaded.');
}
else {
$this->assertSession()->pageTextContains('Only files with the following extensions are allowed: jpg');
$this->assertSession()->pageTextContains('The specified file druplicon.png could not be uploaded');
}
// Upload an image bigger than the field widget's configured max size.
$this->getSession()->getPage()->attachFileToField('files[upload][]', $file_too_big);
$this->waitForAjaxToFinish();
$this->assertSession()->pageTextContains('The image was resized to fit within the maximum allowed dimensions of 40x40 pixels.');
// Upload an image that passes validation and finish the upload.
$this->getSession()->getPage()->attachFileToField('files[upload][]', $file_just_right);
$this->waitForAjaxToFinish();
$this->getSession()->getPage()->pressButton('Select files');
$button = $this->assertSession()->waitForButton('Use selected');
$this->assertSession()->pageTextContains('image-test.jpg');
$button->press();
$this->waitForAjaxToFinish();
// Check that the file has uploaded to the correct sub-directory.
$this->getSession()->switchToIFrame();
if (!$this->coreVersion('10.2')) {
$this->assertSession()->assertWaitOnAjaxRequest();
}
$entity_id = $this->getSession()->evaluateScript('jQuery("#edit-field-image-wrapper [data-entity-id]").data("entity-id")');
$this->assertStringStartsWith('file:', $entity_id);
/** @var \Drupal\file\Entity\File $file */
$fid = explode(':', $entity_id)[1];
$file = File::load($fid);
$this->assertStringContainsString('entity-browser-test', $file->getFileUri());
}
}
@@ -0,0 +1,426 @@
<?php
namespace Drupal\Tests\entity_browser\FunctionalJavascript;
use Drupal\FunctionalJavascriptTests\SortableTestTrait;
/**
* Test for integration of entity browser and inline entity form.
*
* @group entity_browser
*
* @package Drupal\Tests\entity_browser\FunctionalJavascript
*/
class InlineEntityFormTest extends EntityBrowserWebDriverTestBase {
use SortableTestTrait;
/**
* {@inheritdoc}
*/
protected static $modules = [
'views',
'block',
'node',
'file',
'image',
'field_ui',
'views_ui',
'system',
'node',
'inline_entity_form',
'entity_browser_test',
'entity_browser_ief_test',
];
/**
* {@inheritdoc}
*/
protected static $userPermissions = [
'create media',
'update media',
'access ief_entity_browser_file entity browser pages',
'access ief_entity_browser_file_modal entity browser pages',
'access widget_context_default_value entity browser pages',
'access bundle_filter entity browser pages',
'access content',
'create ief_content content',
'create shark content',
'create jet content',
'edit any ief_content content',
];
/**
* Check that selection state in entity browser Inline Entity Form.
*/
public function testEntityBrowserInsideInlineEntityForm() {
$this->createFile('test_file1');
$this->createFile('test_file2');
$this->createFile('test_file3');
$this->drupalGet('node/add/ief_content');
$page = $this->getSession()->getPage();
$page->fillField('Title', 'Test IEF Title');
$page->pressButton('Add new Test File Media');
$this->assertSession()->assertWaitOnAjaxRequest();
$page->fillField('Name', 'Test Bundle Media');
$page->clickLink('Select entities');
$this->getSession()
->switchToIFrame('entity_browser_iframe_ief_entity_browser_file');
$page->checkField('entity_browser_select[file:1]');
$page->checkField('entity_browser_select[file:2]');
$page->pressButton('Select entities');
$page->pressButton('Use selected');
$this->getSession()->switchToIFrame();
$page->pressButton('Create Test File Media');
$this->assertSession()->assertWaitOnAjaxRequest();
$page->pressButton('Save');
$this->drupalGet('node/1/edit');
$page = $this->getSession()->getPage();
$page->pressButton('Edit');
$this->assertSession()->assertWaitOnAjaxRequest();
// Test reorder of elements.
$list_selector = '[data-drupal-selector="edit-ief-media-field-form-inline-entity-form-entities-0-form-ief-media-type-file-field-current"]';
$item_selector = "$list_selector .item-container";
$this->sortableAfter("$item_selector:first-child", "$item_selector:last-child", $list_selector);
$this->assertSession()->assertWaitOnAjaxRequest();
$page->pressButton('Update Test File Media');
$this->assertSession()->assertWaitOnAjaxRequest();
$page->pressButton('Edit');
$this->assertSession()->assertWaitOnAjaxRequest();
// Check that element on second position is test_file1 (file:1).
$secondElement = $page->find('xpath', '//div[@data-drupal-selector="edit-ief-media-field-form-inline-entity-form-entities-0-form-ief-media-type-file-field-current"]/div[2]');
if (empty($secondElement)) {
throw new \Exception('Element is not found.');
}
$this->assertSame('file:1', $secondElement->getAttribute('data-entity-id'));
// Test remove of element.
$this->click('input[name*="ief_media_type_file_field_remove_1_1"]');
$this->assertSession()->assertWaitOnAjaxRequest();
$page->pressButton('Update Test File Media');
$this->assertSession()->assertWaitOnAjaxRequest();
$page->pressButton('Edit');
$this->assertSession()->assertWaitOnAjaxRequest();
// Check that remote button does not exist for already removed entity.
$this->assertSession()
->elementNotExists('css', '[name*="ief_media_type_file_field_remove_1_1"]');
// Test add inside Entity Browser.
$page->clickLink('Select entities');
$this->getSession()
->switchToIFrame('entity_browser_iframe_ief_entity_browser_file');
$page->checkField('entity_browser_select[file:3]');
$page->pressButton('Select entities');
$page->pressButton('Use selected');
$this->assertSession()->assertWaitOnAjaxRequest();
$this->getSession()->switchToIFrame();
$page->pressButton('Update Test File Media');
$this->assertSession()->assertWaitOnAjaxRequest();
$page->pressButton('Edit');
$this->assertSession()->assertWaitOnAjaxRequest();
// Check that element on second position is test_file3 (file:3).
$secondElement = $page->find('xpath', '//div[@data-drupal-selector="edit-ief-media-field-form-inline-entity-form-entities-0-form-ief-media-type-file-field-current"]/div[2]');
if (empty($secondElement)) {
throw new \Exception('Element is not found.');
}
$this->assertSame('file:3', $secondElement->getAttribute('data-entity-id'));
// Test reorder inside Entity Browser.
$page->clickLink('Select entities');
$this->getSession()
->switchToIFrame('entity_browser_iframe_ief_entity_browser_file');
$list_selector = '[data-drupal-selector="edit-selected"]';
$item_selector = "$list_selector .item-container";
$this->sortableAfter("$item_selector:first-child", "$item_selector:last-child", $list_selector);
$page->pressButton('Use selected');
$this->assertSession()->assertWaitOnAjaxRequest();
$this->getSession()->switchToIFrame();
$page->pressButton('Update Test File Media');
$this->assertSession()->assertWaitOnAjaxRequest();
$page->pressButton('Edit');
$this->assertSession()->assertWaitOnAjaxRequest();
// Check that element on second position is test_file2 (file:2).
$secondElement = $page->find('xpath', '//div[@data-drupal-selector="edit-ief-media-field-form-inline-entity-form-entities-0-form-ief-media-type-file-field-current"]/div[2]');
if (empty($secondElement)) {
throw new \Exception('Element is not found.');
}
$this->assertSame('file:2', $secondElement->getAttribute('data-entity-id'));
// Test remove inside entity browser.
$page->clickLink('Select entities');
$this->getSession()
->switchToIFrame('entity_browser_iframe_ief_entity_browser_file');
$page->pressButton('remove_3_0');
$page->pressButton('Use selected');
$this->assertSession()->assertWaitOnAjaxRequest();
$this->getSession()->switchToIFrame();
$page->pressButton('Update Test File Media');
$this->assertSession()->assertWaitOnAjaxRequest();
$page->pressButton('Edit');
$this->assertSession()->assertWaitOnAjaxRequest();
// Check that element on first position is test_file2 (file:2).
$secondElement = $page->find('xpath', '//div[@data-drupal-selector="edit-ief-media-field-form-inline-entity-form-entities-0-form-ief-media-type-file-field-current"]/div[1]');
if (empty($secondElement)) {
throw new \Exception('Element is not found.');
}
$this->assertSame('file:2', $secondElement->getAttribute('data-entity-id'));
}
/**
* Checks auto_open functionality for modals.
*/
public function testModalAutoOpenInsideInlineEntityForm() {
$this->config('core.entity_form_display.node.ief_content.default')
->set('content.ief_media_field.third_party_settings.entity_browser_entity_form.entity_browser_id', 'ief_entity_browser_file_modal')
->save();
$this->drupalGet('node/add/ief_content');
$page = $this->getSession()->getPage();
$page->fillField('Title', 'Test IEF Title');
$page->pressButton('Add existing Test File Media');
$this->assertSession()->assertWaitOnAjaxRequest();
$this->getSession()
->switchToIFrame('entity_browser_iframe_ief_entity_browser_file_modal');
$this->assertSession()->waitForElementVisible('css', 'ief-entity-browser-file-modal-form');
$this->assertSession()->responseContains('Test entity browser file modal');
}
/**
* Tests the EntityBrowserWidgetContext argument_default views plugin.
*/
public function testContextualFilter() {
$this->createNode(['type' => 'shark', 'title' => 'Luke']);
$this->createNode(['type' => 'jet', 'title' => 'Leia']);
$this->createNode(['type' => 'ief_content', 'title' => 'Darth']);
$this->drupalGet('node/add/ief_content');
$page = $this->getSession()->getPage();
$page->fillField('Title', 'Test IEF Title');
$page->pressButton('Add existing node');
$this->assertSession()->assertWaitOnAjaxRequest();
$this->getSession()->switchToIFrame('entity_browser_iframe_widget_context_default_value');
// Check that only nodes of an allowed type are listed.
$this->assertSession()->pageTextContains('Luke');
$this->assertSession()->pageTextContains('Leia');
$this->assertSession()->pageTextNotContains('Darth');
/** @var \Drupal\Core\Field\FieldConfigInterface $field_config */
$field_config = $this->container->get('entity_type.manager')
->getStorage('field_config')
->load('node.ief_content.field_nodes');
$handler_settings = $field_config->getSetting('handler_settings');
$handler_settings['target_bundles'] = [
'ief_content' => 'ief_content',
];
$field_config->setSetting('handler_settings', $handler_settings);
$field_config->save();
$this->drupalGet('node/add/ief_content');
$page = $this->getSession()->getPage();
$page->fillField('Title', 'Test IEF Title');
$page->pressButton('Add existing node');
$this->assertSession()->assertWaitOnAjaxRequest();
$this->getSession()->switchToIFrame('entity_browser_iframe_widget_context_default_value');
// Check that only nodes of an allowed type are listed.
$this->assertSession()->pageTextNotContains('Luke');
$this->assertSession()->pageTextNotContains('Leia');
$this->assertSession()->pageTextContains('Darth');
}
/**
* Tests the ContextualBundle filter plugin with exposed option.
*/
public function testContextualBundleExposed() {
$this->config('core.entity_form_display.node.ief_content.default')
->set('content.field_nodes.third_party_settings.entity_browser_entity_form.entity_browser_id', 'bundle_filter')
->save();
$this->config('entity_browser.browser.bundle_filter')
->set('widgets.b882a89d-9ce4-4dfe-9802-62df93af232a.settings.view', 'bundle_filter_exposed')
->save();
$this->createNode(['type' => 'shark', 'title' => 'Luke']);
$this->createNode(['type' => 'jet', 'title' => 'Leia']);
$this->createNode(['type' => 'ief_content', 'title' => 'Darth']);
$this->drupalGet('node/add/ief_content');
$page = $this->getSession()->getPage();
$page->fillField('Title', 'Test IEF Title');
$page->pressButton('Add existing node');
$this->assertSession()->assertWaitOnAjaxRequest();
$this->getSession()->switchToIFrame('entity_browser_iframe_bundle_filter');
// Check that only nodes of an allowed type are listed.
$this->assertSession()->pageTextContains('Luke');
$this->assertSession()->pageTextContains('Leia');
$this->assertSession()->pageTextNotContains('Darth');
// Test exposed form type filter.
$this->assertSession()->selectExists('Type')->selectOption('jet');
$this->assertSession()->buttonExists('Apply')->press();
$this->assertSession()->assertWaitOnAjaxRequest();
// Check that only nodes of the type selected in the exposed filter display.
$this->assertSession()->pageTextNotContains('Luke');
$this->assertSession()->pageTextContains('Leia');
$this->assertSession()->pageTextNotContains('Darth');
$this->assertSession()->selectExists('Type')->selectOption('shark');
$this->assertSession()->buttonExists('Apply')->press();
$this->assertSession()->assertWaitOnAjaxRequest();
// Check that only nodes of the type selected in the exposed filter display.
$this->assertSession()->pageTextContains('Luke');
$this->assertSession()->pageTextNotContains('Leia');
$this->assertSession()->pageTextNotContains('Darth');
$this->assertSession()->selectExists('Type')->selectOption('All');
$this->assertSession()->buttonExists('Apply')->press();
$this->assertSession()->assertWaitOnAjaxRequest();
// Check that only nodes of the type selected in the exposed filter display.
$this->assertSession()->pageTextContains('Luke');
$this->assertSession()->pageTextContains('Leia');
$this->assertSession()->pageTextNotContains('Darth');
/** @var \Drupal\Core\Field\FieldConfigInterface $field_config */
$field_config = $this->container->get('entity_type.manager')
->getStorage('field_config')
->load('node.ief_content.field_nodes');
$handler_settings = $field_config->getSetting('handler_settings');
$handler_settings['target_bundles'] = [
'ief_content' => 'ief_content',
];
$field_config->setSetting('handler_settings', $handler_settings);
$field_config->save();
$this->drupalGet('node/add/ief_content');
$page = $this->getSession()->getPage();
$page->fillField('Title', 'Test IEF Title');
$page->pressButton('Add existing node');
$this->assertSession()->assertWaitOnAjaxRequest();
$this->getSession()->switchToIFrame('entity_browser_iframe_bundle_filter');
// Check that only nodes of an allowed type are listed.
$this->assertSession()->pageTextNotContains('Luke');
$this->assertSession()->pageTextNotContains('Leia');
$this->assertSession()->pageTextContains('Darth');
// If there is just one target_bundle, the contextual filter
// should not be visible.
$this->assertSession()->fieldNotExists('Type');
}
/**
* Tests entity_browser_entity_form_reference_form_validate.
*/
public function testEntityFormReferenceFormValidate() {
$boxer = $this->createNode(['type' => 'shark', 'title' => 'Boxer']);
$napoleon = $this->createNode(['type' => 'jet', 'title' => 'Napoleon']);
$this->drupalGet('node/add/ief_content');
$page = $this->getSession()->getPage();
$page->fillField('Title', 'Test IEF Title');
// Select the same node twice.
for ($i = 0; $i < 2; $i++) {
$this->assertSession()->buttonExists('Add existing node')->press();
$this->assertSession()->assertWaitOnAjaxRequest();
$this->getSession()->switchToIFrame('entity_browser_iframe_widget_context_default_value');
$this->assertSession()->fieldExists('entity_browser_select[node:' . $boxer->id() . ']')->check();
$this->assertSession()->buttonExists('Select entities')->press();
$this->assertSession()->buttonExists('Use selected')->press();
$this->assertSession()->assertWaitOnAjaxRequest();
$this->getSession()->switchToIFrame();
if (!$this->coreVersion('10.2')) {
$this->assertSession()->assertWaitOnAjaxRequest();
}
}
$this->assertSession()->pageTextContains('The selected node has already been added.');
// Select a different node.
$this->getSession()->switchToIFrame('entity_browser_iframe_widget_context_default_value');
$this->assertSession()->fieldExists('entity_browser_select[node:' . $napoleon->id() . ']')->check();
$this->assertSession()->buttonExists('Select entities')->press();
$this->assertSession()->buttonExists('Use selected')->press();
$this->assertSession()->assertWaitOnAjaxRequest();
$this->getSession()->switchToIFrame();
if (!$this->coreVersion('10.2')) {
$this->assertSession()->assertWaitOnAjaxRequest();
}
$this->assertSession()->pageTextNotContains('The selected node has already been added.');
$ief_table = $this->assertSession()->elementExists('xpath', '//table[contains(@id, "ief-entity-table-edit-field-nodes-entities")]');
$table_text = $ief_table->getText();
$this->assertStringContainsString('Boxer', $table_text);
$this->assertStringContainsString('Napoleon', $table_text);
}
/**
* {@inheritdoc}
*/
protected function sortableUpdate($item, $from, $to = NULL) {
list ($container) = explode(' ', $item, 2);
$js = <<<END
(Drupal.entityBrowserEntityReference || Drupal.entityBrowserMultiStepDisplay).entitiesReordered(document.querySelector("$container"));
END;
$this->getSession()->executeScript($js);
}
}
@@ -0,0 +1,251 @@
<?php
namespace Drupal\Tests\entity_browser\FunctionalJavascript;
use Drupal\Component\Utility\NestedArray;
/**
* Test for multi_step_display selection display.
*
* @group entity_browser
*
* @package Drupal\Tests\entity_browser\FunctionalJavascript
*/
class MultiStepSelectionDisplayTest extends EntityBrowserWebDriverTestBase {
/**
* Open iframe entity browser and change scope to iframe.
*/
protected function openEntityBrowser() {
$this->getSession()->getPage()->clickLink('Select entities');
$this->getSession()
->switchToIFrame('entity_browser_iframe_test_entity_browser_file');
}
/**
* Close iframe entity browser and change scope to base page.
*/
protected function closeEntityBrowser() {
$this->assertSession()->elementExists('xpath', '//*[@data-drupal-selector="edit-use-selected"]')->press();
$this->getSession()->switchToIFrame();
$this->waitForAjaxToFinish();
}
/**
* Click on entity in view to be selected.
*
* @param string $entityId
* Entity ID that will be selected. Format: "file:1".
*/
protected function clickViewEntity($entityId) {
$xpathViewRow = '//*[./*[contains(@class, "views-field-entity-browser-select") and .//input[@name="entity_browser_select[' . $entityId . ']"]]]';
$this->assertSession()->elementExists('xpath', $xpathViewRow)->press();
}
/**
* Wait for Ajax Commands to finish.
*
* Since commands are executed in batches, it can occur that one command is
* still running and new one will be collected for next batch. To ensure all
* of commands are executed, we have to add additional 200ms wait, before next
* batch is triggered.
*
* It's related to: Drupal.entityBrowserCommandQueue.executeCommands
*/
protected function waitSelectionDisplayAjaxCommands() {
$this->getSession()->wait(200);
$this->waitForAjaxToFinish();
}
/**
* Change selection mode for article reference field form display widget.
*
* @param array $configuration
* Configuration that will be used for field form display.
*/
protected function changeFieldFormDisplayConfig(array $configuration) {
/** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display */
$form_display = $this->container->get('entity_type.manager')
->getStorage('entity_form_display')
->load('node.article.default');
$form_display->setComponent(
'field_reference',
NestedArray::mergeDeep($form_display->getComponent('field_reference'), $configuration)
)->save();
}
/**
* Check that selection state in entity browser Inline Entity Form.
*/
public function testAjaxCommands() {
$this->createFile('test_file1');
$this->createFile('test_file2');
$this->createFile('test_file3');
// Testing Action buttons (adding and removing) with usage of HTML View.
$widget_configurations = [
// View widget configuration.
'774798f1-5ec5-4b63-84bd-124cd51ec07d' => [
'settings' => [
'view' => 'files_entity_browser_html',
'auto_select' => TRUE,
],
],
];
$this->getEntityBrowser('test_entity_browser_file', 'iframe', 'tabs', 'multi_step_display', [], [], [], $widget_configurations);
$this->drupalGet('node/add/article');
$this->openEntityBrowser();
// Check that action buttons are not there.
$this->assertSession()
->elementNotExists('xpath', '//*[@data-drupal-selector="edit-use-selected"]');
$this->assertSession()
->elementNotExists('xpath', '//*[@data-drupal-selector="edit-show-selection"]');
$this->clickViewEntity('file:1');
$this->waitSelectionDisplayAjaxCommands();
// Check that action buttons are there.
$this->assertSession()
->elementExists('xpath', '//*[@data-drupal-selector="edit-use-selected"]');
$this->assertSession()
->elementExists('xpath', '//*[@data-drupal-selector="edit-show-selection"]');
// Click on first entity Remove button.
$this->assertSession()->elementExists('xpath', '//input[@data-row-id="0"]')->press();
$this->waitSelectionDisplayAjaxCommands();
// Check that action buttons are not there.
$this->assertSession()
->elementNotExists('xpath', '//*[@data-drupal-selector="edit-use-selected"]');
$this->assertSession()
->elementNotExists('xpath', '//*[@data-drupal-selector="edit-show-selection"]');
$this->clickViewEntity('file:1');
$this->waitSelectionDisplayAjaxCommands();
$this->closeEntityBrowser();
// Testing quick adding and removing of entities with usage of Table
// (default) view.
$widget_configurations = [
// View widget configuration.
'774798f1-5ec5-4b63-84bd-124cd51ec07d' => [
'settings' => [
'view' => 'files_entity_browser',
'auto_select' => TRUE,
],
],
];
$this->getEntityBrowser('test_entity_browser_file', 'iframe', 'tabs', 'multi_step_display', [], [], [], $widget_configurations);
$this->drupalGet('node/add/article');
$this->openEntityBrowser();
// Quickly add 5 entities.
$entitiesToAdd = ['file:1', 'file:2', 'file:3', 'file:1', 'file:2'];
foreach ($entitiesToAdd as $entityId) {
$this->clickViewEntity($entityId);
}
$this->waitSelectionDisplayAjaxCommands();
// Check that there are 5 entities in selection display list.
$this->assertSession()
->elementsCount('xpath', '//div[contains(@class, "entities-list")]/*', 5);
// Quickly remove all 5 entities.
foreach (array_keys($entitiesToAdd) as $entityIndex) {
$this->assertSession()->elementExists('xpath', '//input[@data-row-id="' . $entityIndex . '"]')->press();
}
$this->waitSelectionDisplayAjaxCommands();
// Check that action buttons are not there.
$this->assertSession()
->elementNotExists('xpath', '//*[@data-drupal-selector="edit-use-selected"]');
$this->assertSession()
->elementNotExists('xpath', '//*[@data-drupal-selector="edit-show-selection"]');
$this->clickViewEntity('file:1');
$this->waitSelectionDisplayAjaxCommands();
$this->closeEntityBrowser();
// Testing adding with preselection with usage of Grid view.
$widget_configurations = [
// View widget configuration.
'774798f1-5ec5-4b63-84bd-124cd51ec07d' => [
'settings' => [
'view' => 'files_entity_browser_grid',
'auto_select' => TRUE,
],
],
];
$this->getEntityBrowser('test_entity_browser_file', 'iframe', 'tabs', 'multi_step_display', [], [], [], $widget_configurations);
// Change selection mode to 'Edit', to test adding/removing inside EB.
$this->changeFieldFormDisplayConfig([
'settings' => [
'selection_mode' => 'selection_edit',
],
]);
$this->drupalGet('node/add/article');
$this->openEntityBrowser();
$this->clickViewEntity('file:1');
$this->waitSelectionDisplayAjaxCommands();
$this->closeEntityBrowser();
$this->openEntityBrowser();
$this->clickViewEntity('file:2');
$this->waitSelectionDisplayAjaxCommands();
$this->closeEntityBrowser();
$this->assertSession()
->elementsCount('xpath', '//div[contains(@class, "entities-list")]/*', 2);
// Testing removing with preselection with usage of Unformatted view.
$widget_configurations = [
// View widget configuration.
'774798f1-5ec5-4b63-84bd-124cd51ec07d' => [
'settings' => [
'view' => 'files_entity_browser_unformatted',
'auto_select' => TRUE,
],
],
];
$this->getEntityBrowser('test_entity_browser_file', 'iframe', 'tabs', 'multi_step_display', [], [], [], $widget_configurations);
$this->drupalGet('node/add/article');
$this->openEntityBrowser();
// Select 3 entities.
$entitiesToAdd = ['file:1', 'file:2', 'file:3'];
foreach ($entitiesToAdd as $entityId) {
$this->clickViewEntity($entityId);
// For some reason PhantomJS crashes here on quick clicking. That's why
// waiting is added. Selenium works fine.
$this->waitSelectionDisplayAjaxCommands();
}
$this->closeEntityBrowser();
// Check that there are 3 entities in selection list after closing of EB.
$this->assertSession()
->elementsCount('xpath', '//div[contains(@class, "entities-list")]/*', 3);
$this->openEntityBrowser();
// Click on first entity Remove button.
$this->assertSession()->elementExists('xpath', '//input[@data-row-id="0"]')->press();
$this->waitSelectionDisplayAjaxCommands();
$this->closeEntityBrowser();
// Check that there are 2 entities in selection list after closing of EB.
$this->assertSession()
->elementsCount('xpath', '//div[contains(@class, "entities-list")]/*', 2);
}
}
@@ -0,0 +1,119 @@
<?php
namespace Drupal\Tests\entity_browser\FunctionalJavascript;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
/**
* Tests entity browser pager form element.
*
* @group entity_browser
*/
class PagerElementTest extends EntityBrowserWebDriverTestBase {
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = [
'entity_browser_test',
'node',
'field_ui',
'views_ui',
'system',
];
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->drupalCreateContentType(['type' => 'foo', 'name' => 'Foo']);
FieldStorageConfig::create([
'field_name' => 'field_reference_pager',
'type' => 'entity_reference',
'entity_type' => 'node',
'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
'settings' => [
'target_type' => 'node',
],
])->save();
FieldConfig::create([
'field_name' => 'field_reference_pager',
'entity_type' => 'node',
'bundle' => 'foo',
'label' => 'Reference',
'settings' => [],
])->save();
/** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display */
$form_display = $this->container->get('entity_type.manager')
->getStorage('entity_form_display')
->load('node.foo.default');
$form_display->setComponent('field_reference_pager', [
'type' => 'entity_browser_entity_reference',
'settings' => [
'entity_browser' => 'pager',
'field_widget_display' => 'label',
'open' => TRUE,
],
])->save();
$account = $this->drupalCreateUser([
'access pager entity browser pages',
'create foo content',
'access content',
]);
$this->drupalLogin($account);
}
/**
* Test entity browser pager form element.
*/
public function testPagerElement() {
$this->drupalGet('/entity-browser/iframe/pager');
// Go through pager next and previous buttons and assert pages.
$this->assertSession()->pageTextContains('Current page reported by the element is: 1.');
$this->assertSession()->buttonExists('‹ Previous')->hasAttribute('disabled');
$this->assertSession()->pageTextContains('Page 1');
$this->assertSession()->buttonExists('Next ›');
$this->getSession()->getPage()->pressButton('Next ›');
$this->assertSession()->pageTextContains('Current page reported by the element is: 2.');
$this->assertSession()->pageTextContains('Page 2');
$this->getSession()->getPage()->pressButton('Next ›');
$this->assertSession()->pageTextContains('Current page reported by the element is: 3.');
$this->assertSession()->pageTextContains('Page 3');
$this->getSession()->getPage()->pressButton('Next ›');
$this->assertSession()->pageTextContains('Current page reported by the element is: 4.');
$this->assertSession()->pageTextContains('Page 4');
$this->assertSession()->buttonExists('Next ›')->hasAttribute('disabled');
// Go back.
$this->getSession()->getPage()->pressButton('‹ Previous');
$this->assertSession()->pageTextContains('Current page reported by the element is: 3.');
$this->assertSession()->pageTextContains('Page 3');
$this->getSession()->getPage()->pressButton('‹ Previous');
$this->assertSession()->pageTextContains('Current page reported by the element is: 2.');
$this->assertSession()->pageTextContains('Page 2');
$this->getSession()->getPage()->pressButton('‹ Previous');
$this->assertSession()->pageTextContains('Current page reported by the element is: 1.');
$this->assertSession()->pageTextContains('Page 1');
$this->assertSession()->buttonExists('‹ Previous')->hasAttribute('disabled');
// Test reset button.
$this->getSession()->getPage()->pressButton('Last page');
$this->assertSession()->pageTextContains('Current page reported by the element is: 4.');
$this->assertSession()->pageTextContains('Page 4');
$this->getSession()->getPage()->pressButton('First page');
$this->assertSession()->pageTextContains('Current page reported by the element is: 1.');
$this->assertSession()->pageTextContains('Page 1');
}
}
@@ -0,0 +1,150 @@
<?php
namespace Drupal\Tests\entity_browser\FunctionalJavascript;
/**
* Tests entity browser integration with paragraphs.
*
* @group entity_browser
*/
class ParagraphsTest extends EntityBrowserWebDriverTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = [
'views',
'block',
'node',
'file',
'image',
'field_ui',
'views_ui',
'system',
'entity_browser_test_paragraphs',
];
/**
* {@inheritdoc}
*/
protected static $userPermissions = [
'access test_nodes entity browser pages',
'create paragraphs_test content',
'delete own paragraphs_test content',
'access content',
'edit own article content',
'edit any paragraphs_test content',
];
/**
* Tests a flow of adding/removing references with paragraphs.
*/
public function testParagraphs() {
// Create an article that we'll reference later.
$node = $this->createNode(['type' => 'article', 'title' => 'Hello world']);
$node_nested = $this->createNode(['type' => 'article', 'title' => 'Nested node']);
$node_nested_second = $this->createNode(['type' => 'article', 'title' => 'Nested second node']);
$this->drupalGet('node/add/paragraphs_test');
// Fill in the title field.
$title = $this->assertSession()->fieldExists('Title');
$title->setValue('Paragraph test');
// Create a new paragraph referencing our article.
$this->getSession()->getPage()->pressButton('field_paragraph_content_embed_add_more');
$this->waitForAjaxToFinish();
$this->assertSession()->linkExists('Select entities');
$this->getSession()->getPage()->clickLink('Select entities');
$this->getSession()->switchToIFrame('entity_browser_iframe_test_nodes');
$this->getSession()->getPage()->checkField('entity_browser_select[node:' . $node->id() . ']');
$this->getSession()->getPage()->pressButton('Select entities');
// Switch back to the main page.
$this->getSession()->switchToIFrame();
$this->waitForAjaxToFinish();
// Create another paragraph referencing our article.
$this->getSession()->getPage()->pressButton('field_paragraph_content_embed_add_more');
$this->waitForAjaxToFinish();
$this->assertSession()->linkExists('Select entities');
$this->getSession()->getPage()->clickLink('Select entities');
$this->getSession()->switchToIFrame('entity_browser_iframe_test_nodes');
$this->getSession()->getPage()->checkField('entity_browser_select[node:' . $node->id() . ']');
$this->getSession()->getPage()->pressButton('Select entities');
// Switch back to the main page.
$this->getSession()->switchToIFrame();
$this->waitForAjaxToFinish();
// Ensure that two paragraphs now exist.
$selector_1 = '.field--name-field-paragraph tbody tr:nth-child(1) .paragraphs-subform';
$selector_2 = str_replace('1', '2', $selector_1);
$this->assertSession()->elementExists('css', $selector_1);
$this->assertSession()->elementExists('css', $selector_2);
// Click the remove button on the second paragraph's article reference,
// and ensure that only that instance of our article is removed.
$this->click('.field--name-field-paragraph tbody tr:nth-child(2) .paragraphs-subform [value="Remove"]');
$this->waitForAjaxToFinish();
$this->assertSession()->elementTextNotContains('css', $selector_2, 'Hello world');
$this->assertSession()->elementTextContains('css', $selector_1, 'Hello world');
// Testing nested paragraphs field.
$this->getSession()->getPage()->pressButton('field_paragraph_0_subform_field_paragraphs_nested_nested_paragraph_add_more');
$this->waitForAjaxToFinish();
$this->assertSession()->linkExists('Select entities');
$this->getSession()->getPage()->clickLink('Select entities');
$this->getSession()->switchToIFrame('entity_browser_iframe_test_nodes');
$this->getSession()->getPage()->checkField('entity_browser_select[node:' . $node_nested->id() . ']');
$this->getSession()->getPage()->pressButton('Select entities');
// Switch back to the main page.
$this->getSession()->switchToIFrame();
$this->waitForAjaxToFinish();
$this->getSession()->getPage()->pressButton('field_paragraph_0_subform_field_paragraphs_nested_nested_paragraph_add_more');
$this->waitForAjaxToFinish();
$this->assertSession()->linkExists('Select entities');
$this->getSession()->getPage()->clickLink('Select entities');
$this->getSession()->switchToIFrame('entity_browser_iframe_test_nodes');
$this->getSession()->getPage()->checkField('entity_browser_select[node:' . $node_nested_second->id() . ']');
$this->getSession()->getPage()->pressButton('Select entities');
// Switch back to the main page.
$this->getSession()->switchToIFrame();
$this->waitForAjaxToFinish();
// Test editing node in nested paragraph.
$this->assertSession()->elementTextContains('css', '.field--name-field-paragraphs-nested tbody tr:nth-child(1) .paragraphs-subform', 'Nested node');
$this->click('.field--name-field-paragraphs-nested tbody tr:nth-child(1) .paragraphs-subform [value="Edit"]');
$this->waitForAjaxToFinish();
$this->assertSession()->elementExists('css', '.ui-dialog .node-article-edit-form .form-item-title-0-value [value="Nested node"]');
$this->getSession()->getPage()->pressButton('Close');
// Submit the form.
$this->submitForm([], 'Save');
$this->assertSession()->linkExists('Hello world');
$this->assertSession()->elementTextContains('css', '.paragraph--type--content-embed', 'Nested node');
$this->assertSession()->elementTextContains('css', '.paragraph--type--content-embed', 'Nested second node');
$parent_node = $this->container->get('entity_type.manager')
->getStorage('node')
->loadByProperties(['title' => 'Paragraph test']);
$this->drupalGet('node/' . current($parent_node)->id() . '/edit');
// Test removing node in nested paragraph.
$this->click('.field--name-field-paragraphs-nested tbody tr:nth-child(1) .paragraphs-subform [value="Remove"]');
$this->waitForAjaxToFinish();
$this->assertSession()->elementTextNotContains('css', '.field--name-field-paragraphs-nested tbody tr:nth-child(1) .paragraphs-subform', 'Nested node');
$this->assertSession()->elementTextContains('css', '.field--name-field-paragraphs-nested tbody tr:nth-child(2) .paragraphs-subform', 'Nested second node');
// Submit the form.
$this->submitForm([], 'Save');
// Make sure the form submitted and a link to the articles are present.
$this->assertSession()->linkExists('Hello world');
$this->assertSession()->linkNotExists('Nested node');
$this->assertSession()->elementTextContains('css', '.paragraph--type--content-embed', 'Nested second node');
}
}
@@ -0,0 +1,264 @@
<?php
namespace Drupal\Tests\entity_browser\FunctionalJavascript;
use Drupal\Core\Entity\Sql\SqlContentEntityStorageException;
/**
* Tests the entity_browser plugins.
*
* @group entity_browser
*/
class PluginsTest extends EntityBrowserWebDriverTestBase {
/**
* Tests the Entity browser iframe display plugin.
*/
public function testIframeDisplayPlugin() {
$browser = $this->getEntityBrowser('test_entity_browser_file', 'iframe', 'single', 'no_display');
$image = $this->createFile('lama');
// Tests view widget on single display.
$this->drupalGet('node/add/article');
$this->assertSession()->linkExists('Select entities');
$this->getSession()->getPage()->clickLink('Select entities');
$this->getSession()->switchToIFrame('entity_browser_iframe_test_entity_browser_file');
$this->getSession()->getPage()->checkField('entity_browser_select[file:' . $image->id() . ']');
$this->getSession()->getPage()->pressButton('Select entities');
$this->getSession()->switchToIFrame();
$this->assertSession()->waitForElement('css', '.field--type-entity-reference .button');
$this->assertSession()->pageTextContains('lama.jpg');
// Tests upload widget on single display. Gets the upload widget and sets
// the weight so we can test the view widget.
$upload_widget = $browser->getWidget('2dc1ab07-2f8f-42c9-aab7-7eef7f8b7d87');
$upload_widget->setWeight(0);
$browser->save();
$this->drupalGet('node/add/article');
$this->assertSession()->linkExists('Select entities');
$this->getSession()->getPage()->clickLink('Select entities');
$this->getSession()->switchToIFrame('entity_browser_iframe_test_entity_browser_file');
$this->getSession()->getPage()->checkField('entity_browser_select[file:' . $image->id() . ']');
$this->getSession()->getPage()->pressButton('Select entities');
$this->getSession()->switchToIFrame();
$this->assertSession()->waitForElement('css', '.field--type-entity-reference .button');
$this->assertSession()->pageTextContains('lama.jpg');
// Tests view tab with tabs widget selector.
$this->getEntityBrowser('test_entity_browser_file', 'iframe', 'tabs', 'no_display');
$this->drupalGet('node/add/article');
$this->assertSession()->linkExists('Select entities');
$this->getSession()->getPage()->clickLink('Select entities');
$this->getSession()->switchToIFrame('entity_browser_iframe_test_entity_browser_file');
$this->assertSession()->linkExists('view');
$this->assertSession()->linkExists('upload');
$this->clickLink('view');
$this->getSession()->getPage()->checkField('entity_browser_select[file:' . $image->id() . ']');
$this->getSession()->getPage()->pressButton('Select entities');
$this->getSession()->switchToIFrame();
$this->assertSession()->waitForElement('css', '.field--type-entity-reference .button');
$this->assertSession()->pageTextContains('lama.jpg');
// Tests upload tab with tabs widget selector.
$this->drupalGet('node/add/article');
$this->getSession()->getPage()->clickLink('Select entities');
$this->getSession()->switchToIFrame('entity_browser_iframe_test_entity_browser_file');
$this->clickLink('upload');
$this->getSession()->getPage()->attachFileToField('edit-upload-upload', $this->container->get('file_system')->realpath($image->getFileUri()));
$this->assertSession()->assertWaitOnAjaxRequest();
$image2 = $this->getLastUploadedFile();
$this->assertEquals('lama_0.jpg', $image2->label());
$this->getSession()->getPage()->checkField('upload[file_' . $image2->id() . '][selected]');
$this->getSession()->getPage()->pressButton('Select files');
$this->getSession()->switchToIFrame();
$this->assertSession()->assertWaitOnAjaxRequest();
$this->assertSession()->pageTextContains('lama_0.jpg');
// Tests view widget with drop down widget selector.
$this->getEntityBrowser('test_entity_browser_file', 'iframe', 'drop_down', 'no_display');
// DropDown widget selector does not work with exposed view filter. This is
// a known bug and we need to remove exposed filters from the view until
// that is fixed.
/** @var \Drupal\views\Entity\View $view */
$view = $this->container->get('entity_type.manager')->getStorage('view')->load('files_entity_browser');
$display = &$view->getDisplay('default');
$display['display_options']['filters'] = [];
$view->save();
$this->drupalGet('node/add/article');
$this->getSession()->getPage()->clickLink('Select entities');
$this->getSession()->switchToIFrame('entity_browser_iframe_test_entity_browser_file');
$this->assertSession()->selectExists('edit-widget');
$this->getSession()->getPage()->checkField('entity_browser_select[file:' . $image->id() . ']');
$this->getSession()->getPage()->pressButton('Select entities');
$this->getSession()->switchToIFrame();
$this->assertSession()->waitForElement('css', '.field--type-entity-reference .button');
$this->assertSession()->pageTextContains('lama.jpg');
// Tests upload widget with drop down widget selector.
$this->drupalGet('node/add/article');
$this->getSession()->getPage()->clickLink('Select entities');
$this->getSession()->switchToIFrame('entity_browser_iframe_test_entity_browser_file');
$this->getSession()->getPage()->selectFieldOption('edit-widget', '2dc1ab07-2f8f-42c9-aab7-7eef7f8b7d87');
$this->assertSession()->assertWaitOnAjaxRequest();
$this->getSession()->getPage()->attachFileToField('files[upload][]', $this->container->get('file_system')->realpath($image->getFileUri()));
$this->assertSession()->assertWaitOnAjaxRequest();
$image3 = $this->getLastUploadedFile();
$this->getSession()->getPage()->checkField('upload[file_' . $image3->id() . '][selected]');
$this->getSession()->getPage()->pressButton('Select files');
$this->getSession()->switchToIFrame();
$this->assertSession()->assertWaitOnAjaxRequest();
// In iframe I get page not found, so this fails.
$this->assertSession()->pageTextContains($image3->label());
// Tests view selection display.
$view_configuration = [
'view' => 'test_selection_display_view',
'view_display' => 'entity_browser_1',
];
$browser = $this->getEntityBrowser('test_entity_browser_file', 'iframe', 'single', 'view', [], [], $view_configuration);
$this->drupalGet('node/add/article');
$this->getSession()->getPage()->clickLink('Select entities');
$this->getSession()->switchToIFrame('entity_browser_iframe_test_entity_browser_file');
// Tests multistep selection display.
$dragon_image = $this->createFile('dragon');
$unicorn_image = $this->createFile('unicorn');
$upload_widget = $browser->getWidget('2dc1ab07-2f8f-42c9-aab7-7eef7f8b7d87');
$upload_widget->setWeight(-9);
$browser->save();
$multistep_configuration = [
'entity_type' => 'file',
'display' => 'label',
'display_settings' => [],
'select_text' => 'Use selected',
'selection_hidden' => 0,
];
$browser = $this->getEntityBrowser('test_entity_browser_file', 'iframe', 'tabs', 'multi_step_display', [], [], $multistep_configuration);
$upload_widget = $browser->getWidget('774798f1-5ec5-4b63-84bd-124cd51ec07d');
$upload_widget->setWeight(0);
$browser->save();
$this->drupalGet('node/add/article');
$this->getSession()->getPage()->clickLink('Select entities');
$this->getSession()->switchToIFrame('entity_browser_iframe_test_entity_browser_file');
$this->getSession()->getPage()->attachFileToField('files[upload][]', $this->container->get('file_system')->realpath($dragon_image->getFileUri()));
$this->assertSession()->assertWaitOnAjaxRequest();
$this->getSession()->getPage()->pressButton('Select files');
$image4 = $this->getLastUploadedFile();
$this->assertEquals('dragon_0.jpg', $image4->label());
$this->assertSession()->pageTextContains('dragon_0.jpg');
$this->assertSession()->pageTextNotContains('unicorn.jpg');
$this->getSession()->getPage()->clickLink('view');
$this->assertSession()->waitForField('entity_browser_select[file:' . $unicorn_image->id() . ']')->check();
$this->getSession()->getPage()->pressButton('Select entities');
$this->assertSession()
->waitForElement('css', '#edit-selected-items-2-1-remove-button');
$this->assertSession()
->waitForElement('css', '#edit-selected-items-1-0-remove-button');
$this->getSession()->getPage()->pressButton('Use selected');
$this->assertSession()->assertWaitOnAjaxRequest();
$this->getSession()->switchToIFrame();
if (!$this->coreVersion('10.2')) {
$this->assertSession()->assertWaitOnAjaxRequest();
}
$this->assertSession()->pageTextContains('dragon_0.jpg');
$this->assertSession()->pageTextContains('unicorn.jpg');
}
/**
* Tests Entity browser modal display plugin.
*/
public function testModalDisplay() {
$modal_display_config = [
'width' => '650',
'height' => '500',
'link_text' => 'Select entities',
];
$this->getEntityBrowser('test_entity_browser_file', 'modal', 'single', 'no_display', $modal_display_config);
$image = $this->createFile('lama');
$this->drupalGet('node/add/article');
$this->assertSession()->buttonExists('Select entities');
$this->getSession()->getPage()->pressButton('Select entities');
$this->assertSession()->assertWaitOnAjaxRequest();
$this->getSession()->switchToIFrame('entity_browser_iframe_test_entity_browser_file');
$this->getSession()->getPage()->checkField('entity_browser_select[file:' . $image->id() . ']');
$this->getSession()->getPage()->pressButton('Select entities');
$this->getSession()->switchToIFrame();
$this->assertSession()->assertWaitOnAjaxRequest();
$this->assertSession()->pageTextContains('lama');
}
/**
* Tests Entity browser standalone display plugin.
*/
public function testStandaloneDisplay() {
$image = $this->createFile('lama');
$standalone_configuration = [
'entity_browser_id' => 'test_entity_browser_file',
'path' => 'test',
];
$this->getEntityBrowser('test_entity_browser_file', 'standalone', 'single', 'no_display', $standalone_configuration);
$this->drupalGet('test');
$this->assertSession()->buttonExists('Select entities');
$this->getSession()->getPage()->pressButton('Select entities');
$this->getSession()->getPage()->checkField('entity_browser_select[file:' . $image->id() . ']');
$this->getSession()->getPage()->pressButton('Select entities');
// TODO test if entities were selected. Will most likely need a custom event
// subscriber that displays a message or something along those lines.
}
/**
* Get the most recently uploaded file.
*
* @return \Drupal\file\FileInterface
* File entity.
*
* @throws \Drupal\Core\Entity\Sql\SqlContentEntityStorageException
* Thrown if no results from query.
*/
protected function getLastUploadedFile() {
$entity_type_manager = \Drupal::service('entity_type.manager');
$results = $entity_type_manager
->getStorage('file')->getQuery()
->accessCheck(TRUE)
->range(0, 1)
->sort('fid', 'DESC')
->execute();
if (!empty($results)) {
return $entity_type_manager->getStorage('file')->load(reset($results));
}
else {
throw new SqlContentEntityStorageException('File not found');
}
}
}
@@ -0,0 +1,71 @@
<?php
namespace Drupal\Tests\entity_browser\FunctionalJavascript;
use Drupal\user\Entity\Role;
/**
* Tests the Upload Widget.
*
* @group entity_browser
*/
class UploadWidgetTest extends EntityBrowserWebDriverTestBase {
/**
* {@inheritdoc}
*/
public function setUp(): void {
parent::setUp();
// Grant permission to this user to use also the EB page we are testing.
/** @var \Drupal\user\RoleInterface $role */
$role = Role::load('authenticated');
$this->grantPermissions($role, ['access test_entity_browser_standalone_upload entity browser pages']);
}
/**
* Tests Entity Browser upload widget.
*/
public function testUploadWidget() {
/** @var \Drupal\entity_browser\EntityBrowserInterface $browser */
$browser = $this->container->get('entity_type.manager')
->getStorage('entity_browser')
->load('test_entity_browser_standalone_upload');
$page = $this->getSession()->getPage();
// Make sure the test file is not present beforehand.
$this->assertFileDoesNotExist('public://druplicon.png');
// Go to the widget standalone page and test the upload.
$this->drupalGet($browser->getDisplay()->path());
$page->attachFileToField('edit-upload-upload', \Drupal::root() . '/core/misc/druplicon.png');
$this->waitForAjaxToFinish();
$this->assertSession()->fieldExists('druplicon.png');
$page->pressButton('Select files');
// Check if the file was correctly uploaded to the EB destination.
$this->assertFileExists('public://druplicon.png');
// Now change upload location and submit label and check again.
$widget = $browser->getWidget('2dc1ab07-2f8f-42c9-aab7-7eef7f8b7d87');
$config = $widget->getConfiguration();
$config['settings']['upload_location'] = 'public://some_location';
$config['settings']['submit_text'] = 'Fancy submit';
$widget->setConfiguration($config);
$browser->save();
$this->drupalGet($browser->getDisplay()->path());
$page->attachFileToField('edit-upload-upload', \Drupal::root() . '/core/misc/druplicon.png');
$this->waitForAjaxToFinish();
$this->assertSession()->fieldExists('druplicon.png');
$page->pressButton('Fancy submit');
// Check if the file was correctly uploaded to the EB destination.
$this->assertFileExists('public://some_location/druplicon.png');
}
}
@@ -0,0 +1,507 @@
<?php
namespace Drupal\Tests\entity_browser\Kernel\Extension;
use Drupal\Component\FileCache\FileCacheFactory;
use Drupal\Component\Plugin\Exception\PluginException;
use Drupal\Core\Config\Entity\ConfigEntityStorage;
use Drupal\Core\Entity\EntityMalformedException;
use Drupal\Core\Form\FormState;
use Drupal\entity_browser\DisplayInterface;
use Drupal\entity_browser\EntityBrowserInterface;
use Drupal\entity_browser\SelectionDisplayInterface;
use Drupal\entity_browser\WidgetInterface;
use Drupal\entity_browser\WidgetSelectorInterface;
use Drupal\KernelTests\KernelTestBase;
use Drupal\views\Entity\View;
use Symfony\Component\Routing\RouteCollection;
/**
* Tests the entity_browser config entity.
*
* @group entity_browser
*/
class EntityBrowserTest extends KernelTestBase {
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = [
'system',
'user',
'views',
'file',
'node',
'entity_browser',
'entity_browser_test',
];
/**
* The entity browser storage.
*
* @var \Drupal\Core\Config\Entity\ConfigEntityStorageInterface
*/
protected $controller;
/**
* Pre-generated UUID.
*
* @var string
*/
protected $widgetUUID;
/**
* Route provider service.
*
* @var \Drupal\Core\Routing\RouteProviderInterface
*/
protected $routeProvider;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
FileCacheFactory::setPrefix($this->randomString(4));
parent::setUp();
$this->controller = $this->container->get('entity_type.manager')->getStorage('entity_browser');
$this->widgetUUID = $this->container->get('uuid')->generate();
$this->routeProvider = $this->container->get('router.route_provider');
$this->installSchema('system', ['sequences']);
View::create(['id' => 'test_view'])->save();
}
/**
* Tests CRUD operations.
*/
public function testEntityBrowserCrud() {
$this->assertInstanceOf(ConfigEntityStorage::class, $this->controller, 'The entity_browser storage is loaded.');
// Run each test method in the same installation.
$this->createTests();
$this->loadTests();
$this->deleteTests();
}
/**
* Tests the creation of entity_browser.
*/
protected function createTests() {
$plugin = [
'name' => 'test_browser',
'label' => 'Testing entity browser instance',
'display' => 'standalone',
'display_configuration' => ['path' => 'test-browser-test'],
'selection_display' => 'no_display',
'selection_display_configuration' => [],
'widget_selector' => 'single',
'widget_selector_configuration' => [],
'widgets' => [
$this->widgetUUID => [
'id' => 'view',
'label' => 'View widget',
'uuid' => $this->widgetUUID,
'weight' => 0,
'settings' => [
'view' => 'test_view',
'view_display' => 'test_display',
],
],
],
];
foreach ([
'display' => 'getDisplay',
'selection_display' => 'getSelectionDisplay',
'widget_selector' => 'getWidgetSelector',
] as $plugin_type => $function_name) {
$current_plugin = $plugin;
unset($current_plugin[$plugin_type]);
// Attempt to create an entity_browser without required plugin.
try {
$entity = $this->controller->create($current_plugin);
$entity->{$function_name}();
$this->fail('An entity browser without required ' . $plugin_type . ' created with no exception thrown.');
}
catch (PluginException $e) {
$this->assertStringContainsString('The "" plugin does not exist.', $e->getMessage(), 'An exception was thrown when an entity_browser was created without a ' . $plugin_type . ' plugin.');
}
}
// Try to create an entity browser w/o the ID.
$current_plugin = $plugin;
unset($current_plugin['name']);
try {
$entity = $this->controller->create($current_plugin);
$entity->save();
$this->fail('An entity browser without required name created with no exception thrown.');
}
catch (EntityMalformedException $e) {
$this->assertEquals('The entity does not have an ID.', $e->getMessage(), 'An exception was thrown when an entity_browser was created without a name.');
}
// Create an entity_browser with required values.
$entity = $this->controller->create($plugin);
$entity->save();
$this->assertInstanceOf(EntityBrowserInterface::class, $entity, 'The newly created entity is an Entity browser.');
// Verify all of the properties.
$actual_properties = $this->container->get('config.factory')
->get('entity_browser.browser.test_browser')
->get();
$this->assertTrue(!empty($actual_properties['uuid']), 'The entity browser UUID is set.');
unset($actual_properties['uuid']);
// Ensure that default values are filled in.
$expected_properties = [
'langcode' => $this->container->get('language_manager')->getDefaultLanguage()->getId(),
'status' => TRUE,
'dependencies' => [
'config' => ['views.view.test_view'],
'module' => ['views'],
],
'name' => 'test_browser',
'label' => 'Testing entity browser instance',
'display' => 'standalone',
'display_configuration' => ['path' => 'test-browser-test'],
'selection_display' => 'no_display',
'selection_display_configuration' => [],
'widget_selector' => 'single',
'widget_selector_configuration' => [],
'widgets' => [
$this->widgetUUID => [
'id' => 'view',
'label' => 'View widget',
'uuid' => $this->widgetUUID,
'weight' => 0,
'settings' => [
'view' => 'test_view',
'view_display' => 'test_display',
'submit_text' => 'Select entities',
'auto_select' => FALSE,
],
],
],
];
$this->assertEquals($actual_properties, $expected_properties, 'Actual config properties are structured as expected.');
// Ensure that rebuilding routes works.
$route = $this->routeProvider->getRoutesByPattern('/test-browser-test');
$this->assertInstanceOf(RouteCollection::class, $route);
}
/**
* Tests the loading of entity browser.
*/
protected function loadTests() {
/** @var \Drupal\entity_browser\EntityBrowserInterface $entity */
$entity = $this->controller->load('test_browser');
$this->assertInstanceOf(EntityBrowserInterface::class, $entity, 'The loaded entity is an entity browser.');
// Verify several properties of the entity browser.
$this->assertEquals($entity->label(), 'Testing entity browser instance');
$this->assertNotEmpty($entity->uuid());
$plugin = $entity->getDisplay();
$this->assertInstanceOf(DisplayInterface::class, $plugin, 'Testing display plugin.');
$this->assertEquals($plugin->getPluginId(), 'standalone');
$plugin = $entity->getSelectionDisplay();
$this->assertInstanceOf(SelectionDisplayInterface::class, $plugin, 'Testing selection display plugin.');
$this->assertEquals($plugin->getPluginId(), 'no_display');
$plugin = $entity->getWidgetSelector();
$this->assertInstanceOf(WidgetSelectorInterface::class, $plugin, 'Testing widget selector plugin.');
$this->assertEquals($plugin->getPluginId(), 'single');
$plugin = $entity->getWidget($this->widgetUUID);
$this->assertInstanceOf(WidgetInterface::class, $plugin, 'Testing widget plugin.');
$this->assertEquals($plugin->getPluginId(), 'view');
}
/**
* Tests the deleting of entity browser.
*/
protected function deleteTests() {
$entity = $this->controller->load('test_browser');
// Ensure that the storage isn't currently empty.
$config_storage = $this->container->get('config.storage');
$config = $config_storage->listAll('entity_browser.browser.');
$this->assertFalse(empty($config), 'There are entity browsers in config storage.');
// Delete the entity browser.
$entity->delete();
// Ensure that the storage is now empty.
$config = $config_storage->listAll('entity_browser.browser.');
$this->assertTrue(empty($config), 'There are no entity browsers in config storage.');
}
/**
* Tests dynamic routes.
*/
public function testDynamicRoutes() {
$this->installConfig(['entity_browser_test']);
$this->container->get('router.builder')->rebuild();
/** @var \Drupal\entity_browser\EntityBrowserInterface $entity */
$entity = $this->controller->load('test');
$route = $entity->route();
$this->assertEquals($route->getPath(), '/entity-browser/test', 'Dynamic path matches.');
$this->assertEquals($route->getDefault('entity_browser_id'), $entity->id(), 'Entity browser ID matches.');
$this->assertEquals($route->getDefault('_controller'), 'Drupal\entity_browser\Controllers\EntityBrowserFormController::getContentResult', 'Controller matches.');
$this->assertEquals($route->getDefault('_title_callback'), 'Drupal\entity_browser\Controllers\EntityBrowserFormController::title', 'Title callback matches.');
$this->assertEquals($route->getRequirement('_permission'), 'access ' . $entity->id() . ' entity browser pages', 'Permission matches.');
$registered_route = $this->routeProvider->getRouteByName('entity_browser.' . $entity->id());
$this->assertEquals($registered_route->getPath(), '/entity-browser/test', 'Dynamic path matches.');
$this->assertEquals($registered_route->getDefault('entity_browser_id'), $entity->id(), 'Entity browser ID matches.');
$this->assertEquals($registered_route->getDefault('_controller'), 'Drupal\entity_browser\Controllers\EntityBrowserFormController::getContentResult', 'Controller matches.');
$this->assertEquals($registered_route->getDefault('_title_callback'), 'Drupal\entity_browser\Controllers\EntityBrowserFormController::title', 'Title callback matches.');
$this->assertEquals($registered_route->getRequirement('_permission'), 'access ' . $entity->id() . ' entity browser pages', 'Permission matches.');
}
/**
* Tests dynamically generated permissions.
*/
public function testDynamicPermissions() {
$this->installConfig(['entity_browser_test']);
$permissions = $this->container->get('user.permissions')->getPermissions();
/** @var \Drupal\entity_browser\EntityBrowserInterface $entity */
$entity = $this->controller->load('test');
$expected_permission_name = 'access ' . $entity->id() . ' entity browser pages';
$expected_permission = [
'title' => $this->container->get('string_translation')
->translate('Access @name pages', ['@name' => $entity->label()])
->render(),
'description' => $this->container->get('string_translation')
->translate('Access pages that %browser uses to operate.', ['%browser' => $entity->label()])
->render(),
'provider' => 'entity_browser',
'dependencies' => [
'config' => [
'entity_browser.browser.test',
],
],
];
$this->assertSame($permissions[$expected_permission_name]['title']->render(), $expected_permission['title'], 'Dynamically generated permission title found.');
$this->assertSame($permissions[$expected_permission_name]['description']->render(), $expected_permission['description'], 'Dynamically generated permission description found.');
$this->assertSame($permissions[$expected_permission_name]['provider'], $expected_permission['provider'], 'Dynamically generated permission provider found.');
$this->assertSame($permissions[$expected_permission_name]['dependencies'], $expected_permission['dependencies'], 'Dynamically generated permission dependencies found.');
}
/**
* Tests default widget selector.
*/
public function testDefaultWidget() {
$this->installConfig(['entity_browser_test']);
/** @var \Drupal\entity_browser\EntityBrowserInterface $entity */
$entity = $this->controller->load('test');
/** @var \Drupal\entity_browser\EntityBrowserFormInterface $form_object */
$form_object = $entity->getFormObject();
$form_object->setEntityBrowser($entity);
$form_state = new FormState();
$form = [];
$form = $form_object->buildForm($form, $form_state);
$this->assertEquals($form['widget']['#markup'], 'Number one', 'First widget is active.');
// Change weight and expect second widget to become first.
$entity->getWidget($entity->getFirstWidget())->setWeight(3);
$form_state->set('entity_browser_current_widget', NULL);
$entity->getWidgets()->sort();
$form = [];
$form = $form_object->buildForm($form, $form_state);
$this->assertEquals($form['widget']['#markup'], 'Number two', 'Second widget is active after changing widgets.');
}
/**
* Test selected event dispatch.
*/
public function testSelectedEvent() {
$this->installConfig(['entity_browser_test']);
/** @var \Drupal\entity_browser\EntityBrowserInterface $entity */
$entity = $this->controller->load('dummy_widget');
/** @var \Drupal\entity_browser\EntityBrowserFormInterface $form_object */
$form_object = $entity->getFormObject();
$form_object->setEntityBrowser($entity);
$form_state = new FormState();
$entity->getWidgets()->get($entity->getFirstWidget())->entity = $entity;
$this->container->get('form_builder')->buildForm($form_object, $form_state);
$this->assertEquals(0, count($form_state->get([
'entity_browser',
'selected_entities',
])), 'Correct number of entities was propagated.');
$this->container->get('form_builder')->submitForm($form_object, $form_state);
// Event should be dispatched from widget and added to list of selected
// entities.
$selected_entities = $form_state->get([
'entity_browser',
'selected_entities',
]);
$this->assertEquals($selected_entities, [$entity], 'Expected selected entities detected.');
}
/**
* Tests propagation of existing selection.
*/
public function testExistingSelection() {
$this->installConfig(['entity_browser_test']);
$this->installEntitySchema('user');
/** @var \Drupal\entity_browser\EntityBrowserInterface $entity */
$entity = $this->controller->load('test');
/** @var \Drupal\user\UserInterface $user */
$user = $this->container->get('entity_type.manager')
->getStorage('user')
->create([
'name' => $this->randomString(),
'mail' => '[email protected]',
]);
$user->save();
/** @var \Symfony\Component\HttpFoundation\Request $request */
$uuid = $this->container->get('uuid')->generate();
$this->container->get('request_stack')
->getCurrentRequest()
->query
->set('uuid', $uuid);
$this->container->get('entity_browser.selection_storage')->setWithExpire($uuid, ['selected_entities' => [$user]], 21600);
/** @var \Drupal\entity_browser\EntityBrowserFormInterface $form_object */
$form_object = $entity->getFormObject();
$form_object->setEntityBrowser($entity);
$form_state = new FormState();
$form = [];
$form_object->buildForm($form, $form_state);
$propagated_entities = $form_state->get([
'entity_browser',
'selected_entities',
]);
$this->assertEquals(1, count($propagated_entities), 'Correct number of entities was propagated.');
$this->assertEquals($user->id(), $propagated_entities[0]->id(), 'Propagated entity ID is correct.');
$this->assertEquals($user->getAccountName(), $propagated_entities[0]->getAccountName(), 'Propagated entity name is correct.');
$this->assertEquals($user->getEmail(), $propagated_entities[0]->getEmail(), 'Propagated entity name is correct.');
}
/**
* Tests validators.
*/
public function testValidators() {
$this->installConfig(['entity_browser_test']);
$this->installEntitySchema('user');
/** @var \Drupal\entity_browser\EntityBrowserInterface $entity */
$entity = $this->controller->load('test');
/** @var \Drupal\user\UserInterface $user */
$user = $this->container->get('entity_type.manager')
->getStorage('user')
->create([
'name' => $this->randomString(),
'mail' => '[email protected]',
]);
$user->save();
/** @var \Symfony\Component\HttpFoundation\Request $request */
$uuid = $this->container->get('uuid')->generate();
$this->container->get('request_stack')
->getCurrentRequest()
->query
->set('uuid', $uuid);
$storage = [
'validators' => [
'entity_type' => ['type' => 'user'],
],
];
$this->container->get('entity_browser.selection_storage')->setWithExpire($uuid, $storage, 21600);
/** @var \Drupal\entity_browser\EntityBrowserFormInterface $form_object */
$form_object = $entity->getFormObject();
$form_object->setEntityBrowser($entity);
$form_state = new FormState();
$form = $form_object->buildForm([], $form_state);
$validators = $form_state->get(['entity_browser', 'validators']);
$this->assertSame($validators, $storage['validators'], 'Correct validators were passed to form');
// Set a valid triggering element
// (see \Drupal\entity_browser\WidgetBase::validate())
$element = [
'#array_parents' => ['submit'],
];
$form_state->setTriggeringElement($element);
// Use an entity that we know will fail validation.
$form_state->setValue('dummy_entities', [$entity]);
$form_object->validateForm($form, $form_state);
$this->assertNotEmpty($form_state->getErrors(), 'Validation failed where expected');
// Use an entity that we know will pass validation.
$form_state->clearErrors();
$form_state->setValue('dummy_entities', [$user]);
$form_object->validateForm($form, $form_state);
$this->assertEmpty($form_state->getErrors(), 'Validation succeeded where expected');
}
/**
* Tests view widget access.
*/
public function testViewWidgetAccess() {
$this->installConfig(['entity_browser_test']);
$this->installEntitySchema('user');
$this->installEntitySchema('user_role');
/** @var \Drupal\entity_browser\EntityBrowserInterface $entity */
$entity = $this->controller->load('test_entity_browser_file');
$this->assertFalse($entity->getWidget('774798f1-5ec5-4b63-84bd-124cd51ec07d')->access()->isAllowed());
// Create a user that has permission to access the view and try with it.
/** @var \Drupal\user\RoleInterface $role */
$role = $this->container->get('entity_type.manager')
->getStorage('user_role')
->create([
'label' => $this->randomString(),
'id' => $this->randomMachineName(),
]);
$role->grantPermission('access content');
$role->save();
$user = $this->container->get('entity_type.manager')
->getStorage('user')
->create([
'name' => $this->randomString(),
'mail' => '[email protected]',
'roles' => $role->id(),
]);
$user->save();
\Drupal::currentUser()->setAccount($user);
$this->assertTrue($entity->getWidget('774798f1-5ec5-4b63-84bd-124cd51ec07d')->access()->isAllowed());
}
}
@@ -0,0 +1,76 @@
<?php
namespace Drupal\Tests\entity_browser\Kernel\Plugin;
use Drupal\KernelTests\KernelTestBase;
/**
* Tests field widget display plugins.
*
* @group entity_browser
*/
class FieldWidgetDisplayTest extends KernelTestBase {
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = [
'entity_browser', 'image', 'comment',
];
/**
* Field widget display plugin manager.
*
* @var \Drupal\entity_browser\FieldWidgetDisplayManager
*/
protected $pluginManager;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->pluginManager = $this->container->get('plugin.manager.entity_browser.field_widget_display');
$image_style = $this->container->get('entity_type.manager')->getStorage('image_style');
$image_style->create(['name' => 'thumbnail', 'label' => 'Thumbnail'])->save();
$image_style->create(['name' => 'large', 'label' => 'Large'])->save();
$comment_type = $this->container->get('entity_type.manager')->getStorage('comment_type');
$comment_type->create(['id' => 'comment', 'label' => 'Comment'])->save();
$view_mode = $this->container->get('entity_type.manager')->getStorage('entity_view_mode');
$view_mode->create(['id' => 'comment.full', 'targetEntityType' => 'comment'])->save();
}
/**
* Test field widget display plugins configuration and dependencies.
*/
public function testDefaultConfiguration() {
// Check default configuration for image thumbnail plugin.
$image_thumbnail_plugin = $this->pluginManager->createInstance('thumbnail');
$this->assertEquals(['image_style' => 'thumbnail'], $image_thumbnail_plugin->defaultConfiguration());
$this->assertEquals(['image_style' => 'thumbnail'], $image_thumbnail_plugin->getConfiguration());
$this->assertEquals(['config' => [0 => 'image.style.thumbnail']], $image_thumbnail_plugin->calculateDependencies());
// Set configuration different then default.
$image_thumbnail_plugin->setConfiguration(['image_style' => 'large']);
$this->assertEquals(['image_style' => 'thumbnail'], $image_thumbnail_plugin->defaultConfiguration());
$this->assertEquals(['image_style' => 'large'], $image_thumbnail_plugin->getConfiguration());
$this->assertEquals(['config' => [0 => 'image.style.large']], $image_thumbnail_plugin->calculateDependencies());
// Check default configuration for rendered entity plugin.
$rendered_entity_plugin = $this->pluginManager->createInstance('rendered_entity', ['entity_type' => 'comment']);
$this->assertEquals(['view_mode' => 'default'], $rendered_entity_plugin->defaultConfiguration());
$this->assertEquals(['view_mode' => 'default', 'entity_type' => 'comment'], $rendered_entity_plugin->getConfiguration());
$this->assertEquals([], $rendered_entity_plugin->calculateDependencies());
// Set configuration different then default.
$rendered_entity_plugin->setConfiguration(['entity_type' => 'comment', 'view_mode' => 'full']);
$this->assertEquals(['view_mode' => 'default'], $rendered_entity_plugin->defaultConfiguration());
$this->assertEquals(['view_mode' => 'full', 'entity_type' => 'comment'], $rendered_entity_plugin->getConfiguration());
$this->assertEquals(['config' => [0 => 'core.entity_view_mode.comment.full']], $rendered_entity_plugin->calculateDependencies());
}
}