first commit

This commit is contained in:
2024-07-15 12:33:27 +02:00
commit ce50ae282b
22084 changed files with 2623791 additions and 0 deletions

View File

@@ -0,0 +1,12 @@
name: 'Field Layout test'
type: module
description: 'Support module for Field Layout tests.'
package: Testing
# version: VERSION
dependencies:
- drupal:entity_test
# Information added by Drupal.org packaging script on 2024-07-04
version: '10.3.1'
project: 'drupal'
datestamp: 1720094222

View File

@@ -0,0 +1,16 @@
<?php
/**
* @file
* Contains hook implementations for field_layout_test.
*/
/**
* Implements hook_layout_alter().
*/
function field_layout_test_layout_alter(&$definitions) {
/** @var \Drupal\Core\Layout\LayoutDefinition[] $definitions */
if (\Drupal::state()->get('field_layout_test.alter_regions') && isset($definitions['layout_onecol'])) {
$definitions['layout_onecol']->setRegions(['foo' => ['label' => 'Foo']]);
}
}

View File

@@ -0,0 +1,14 @@
entity.entity_test.test_view_mode:
path: '/entity_test/{entity_test}/test'
defaults:
_entity_view: 'entity_test.test'
_title: 'Test test view mode'
requirements:
_entity_access: 'entity_test.view'
field_layout_test.embedded_form:
path: '/field-layout-embedded-form'
defaults:
_form: 'Drupal\field_layout_test\Form\EmbeddedForm'
_title: 'Embedded entity form'
requirements:
_permission: 'access administration pages'

View File

@@ -0,0 +1,55 @@
<?php
namespace Drupal\field_layout_test\Form;
use Drupal\Core\Entity\Entity\EntityFormDisplay;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Form\SubformState;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\field_layout\FieldLayoutBuilder;
/**
* Provides the EmbeddedForm class.
*
* @package Drupal\field_layout_test\Form
*/
class EmbeddedForm extends FormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'field_layout_test_embedded_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form['foo'] = [
'#type' => 'fieldset',
'#title' => $this->t('Wrapper'),
'#tree' => TRUE,
'#parents' => ['foo'],
];
$entity = EntityTest::load(1);
if ($entity) {
if ($entity) {
$display = EntityFormDisplay::collectRenderDisplay($entity, 'default');
$subform_state = SubformState::createForSubform($form['foo'], $form, $form_state);
$display->buildForm($entity, $form['foo'], $subform_state);
\Drupal::classResolver(FieldLayoutBuilder::class)->buildForm($form['foo'], $display, $subform_state);
}
}
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
// Do nothing.
}
}

View File

@@ -0,0 +1,28 @@
<?php
namespace Drupal\field_layout_test\Plugin\Layout;
use Drupal\Core\Layout\Attribute\Layout;
use Drupal\Core\Layout\LayoutDefault;
use Drupal\Core\StringTranslation\TranslatableMarkup;
/**
* Provides a Layout plugin for field_layout tests.
*/
#[Layout(
id: 'test_layout_content_and_footer',
label: new TranslatableMarkup('Test plugin: Content and Footer'),
category: new TranslatableMarkup('Layout test'),
description: new TranslatableMarkup('Test layout'),
regions: [
"content" => [
"label" => new TranslatableMarkup("Content Region"),
],
"footer" => [
"label" => new TranslatableMarkup("Footer Region"),
],
],
)]
class TestLayoutContentFooter extends LayoutDefault {
}

View File

@@ -0,0 +1,51 @@
<?php
namespace Drupal\field_layout_test\Plugin\Layout;
use Drupal\Core\Layout\Attribute\Layout;
use Drupal\Core\Layout\LayoutDefault;
use Drupal\Core\StringTranslation\TranslatableMarkup;
/**
* Provides an attributed layout plugin for field_layout tests.
*/
#[Layout(
id: 'test_layout_main_and_footer',
label: new TranslatableMarkup('Test plugin: Main and Footer'),
category: new TranslatableMarkup('Layout test'),
description: new TranslatableMarkup('Test layout'),
regions: [
"main" => [
"label" => new TranslatableMarkup("Main Region"),
],
"footer" => [
"label" => new TranslatableMarkup("Footer Region"),
],
],
config_dependencies: [
"module" => [
"layout_discovery",
],
],
)]
class TestLayoutMainFooter extends LayoutDefault {
/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
return [
'setting_1' => 'Default',
];
}
/**
* {@inheritdoc}
*/
public function calculateDependencies() {
$dependencies = parent::calculateDependencies();
$dependencies['module'][] = 'system';
return $dependencies;
}
}

View File

@@ -0,0 +1,104 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\field_layout\Functional;
use Drupal\Tests\BrowserTestBase;
/**
* Tests using field layout for entity displays.
*
* @group field_layout
*/
class FieldLayoutTest extends BrowserTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = [
'field_layout',
'field_ui',
'node',
'field_layout_test',
];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->createContentType([
'type' => 'article',
]);
$this->createNode([
'type' => 'article',
'title' => 'The node title',
'body' => [
['value' => 'The node body'],
],
]);
$this->drupalLogin($this->drupalCreateUser([
'access administration pages',
'administer content types',
'administer nodes',
'administer node fields',
'administer node display',
'administer node form display',
'view the administration theme',
]));
}
/**
* Tests an entity type that has fields shown by default.
*/
public function testNodeView(): void {
// By default, the one-column layout is used.
$this->drupalGet('node/1');
$this->assertSession()->elementExists('css', '.layout--onecol');
$this->assertSession()->elementTextContains('css', '.layout__region--content', 'The node body');
$this->drupalGet('admin/structure/types/manage/article/display');
$this->assertEquals(['Content', 'Disabled'], $this->getRegionTitles());
$this->assertSession()->optionExists('fields[body][region]', 'content');
}
/**
* Tests that changes to the regions still leave the fields visible.
*/
public function testRegionChanges(): void {
$this->drupalGet('admin/structure/types/manage/article/display');
$this->assertEquals(['Content', 'Disabled'], $this->getRegionTitles());
$this->assertSession()->optionExists('fields[body][region]', 'content');
\Drupal::state()->set('field_layout_test.alter_regions', TRUE);
\Drupal::service('plugin.cache_clearer')->clearCachedDefinitions();
$this->drupalGet('admin/structure/types/manage/article/display');
$this->assertEquals(['Foo', 'Disabled'], $this->getRegionTitles());
$this->assertSession()->optionExists('fields[body][region]', 'hidden');
}
/**
* Gets the region titles on the page.
*
* @return string[]
* An array of region titles.
*/
protected function getRegionTitles() {
$region_titles = [];
$region_title_elements = $this->getSession()->getPage()->findAll('css', '.region-title td');
/** @var \Behat\Mink\Element\NodeElement[] $region_title_elements */
foreach ($region_title_elements as $region_title_element) {
$region_titles[] = $region_title_element->getText();
}
return $region_titles;
}
}

View File

@@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\field_layout\Functional;
use Drupal\Tests\system\Functional\Module\GenericModuleTestBase;
/**
* Generic module test for field_layout.
*
* @group field_layout
*/
class GenericTest extends GenericModuleTestBase {}

View File

@@ -0,0 +1,321 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\field_layout\FunctionalJavascript;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\FunctionalJavascriptTests\WebDriverTestBase;
/**
* Tests using field layout for entity displays.
*
* @group field_layout
*/
class FieldLayoutTest extends WebDriverTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = [
'field_layout',
'field_ui',
'field_layout_test',
'layout_test',
];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$entity = EntityTest::create([
'name' => 'The name for this entity',
'field_test_text' => [
['value' => 'The field test text value'],
],
]);
$entity->save();
$this->drupalLogin($this->drupalCreateUser([
'access administration pages',
'view test entity',
'administer entity_test content',
'administer entity_test fields',
'administer entity_test display',
'administer entity_test form display',
'view the administration theme',
]));
}
/**
* Tests that layouts are unique per view mode.
*/
public function testEntityViewModes(): void {
// By default, the field is not visible.
$this->drupalGet('entity_test/1/test');
$this->assertSession()->elementNotExists('css', '.layout__region--content ');
$this->drupalGet('entity_test/1');
$this->assertSession()->elementNotExists('css', '.layout__region--content');
// Change the layout for the "test" view mode. See
// core.entity_view_mode.entity_test.test.yml.
$this->drupalGet('entity_test/structure/entity_test/display');
$this->click('#edit-modes');
$this->getSession()->getPage()->checkField('display_modes_custom[test]');
$this->submitForm([], 'Save');
$this->clickLink('configure them');
$this->getSession()->getPage()->pressButton('Show row weights');
$this->getSession()->getPage()->selectFieldOption('fields[field_test_text][region]', 'content');
$this->submitForm([], 'Save');
// Each view mode has a different layout.
$this->drupalGet('entity_test/1/test');
$this->assertSession()->elementTextContains('css', '.layout__region--content', 'The field test text value');
$this->drupalGet('entity_test/1');
$this->assertSession()->elementNotExists('css', '.layout__region--content');
}
/**
* Tests the use of field layout for entity form displays.
*/
public function testEntityForm(): void {
// By default, the one-column layout is used.
$this->drupalGet('entity_test/manage/1/edit');
$this->assertFieldInRegion('field_test_text[0][value]', 'content');
// The one-column layout is in use.
$this->drupalGet('entity_test/structure/entity_test/form-display');
$this->assertEquals(['Content', 'Disabled'], $this->getRegionTitles());
// Switch the layout to two columns.
$this->click('#edit-field-layouts');
$this->getSession()->getPage()->selectFieldOption('field_layout', 'layout_twocol');
$this->assertSession()->assertWaitOnAjaxRequest();
$this->submitForm([], 'Save');
// The field is moved to the default region for the new layout.
$this->assertSession()->pageTextContains('Your settings have been saved.');
$this->assertEquals(['Top', 'First', 'Second', 'Bottom', 'Disabled'], $this->getRegionTitles());
$this->drupalGet('entity_test/manage/1/edit');
// No fields are visible, and the regions don't display when empty.
$this->assertFieldInRegion('field_test_text[0][value]', 'first');
$this->assertSession()->elementExists('css', '.layout__region--first .field--name-field-test-text');
// After a refresh the new regions are still there.
$this->drupalGet('entity_test/structure/entity_test/form-display');
$this->assertEquals(['Top', 'First', 'Second', 'Bottom', 'Disabled'], $this->getRegionTitles());
$this->assertSession()->waitForElement('css', '.tabledrag-handle');
$id = $this->getSession()->getPage()->find('css', '[name="form_build_id"]')->getValue();
// Drag the field to the second region.
$field_test_text_row = $this->getSession()->getPage()->find('css', '#field-test-text');
$second_region_row = $this->getSession()->getPage()->find('css', '.region-second-message');
$field_test_text_row->find('css', '.handle')->dragTo($second_region_row);
$this->assertSession()->assertWaitOnAjaxRequest();
$this->assertSession()->waitForElement('css', "[name='form_build_id']:not([value='$id'])");
$this->submitForm([], 'Save');
$this->assertSession()->pageTextContains('Your settings have been saved.');
// The new layout is used.
$this->drupalGet('entity_test/manage/1/edit');
$this->assertSession()->elementExists('css', '.layout__region--second .field--name-field-test-text');
$this->assertFieldInRegion('field_test_text[0][value]', 'second');
// Tests if this layout works in an embedded context.
$this->drupalGet('/field-layout-embedded-form');
$this->assertSession()->elementExists('css', '.layout__region--second .field--name-field-test-text');
$this->assertFieldInRegion('foo[field_test_text][0][value]', 'second');
// Move the field to the second region without tabledrag.
$this->drupalGet('entity_test/structure/entity_test/form-display');
$this->getSession()->getPage()->pressButton('Show row weights');
$this->getSession()->getPage()->selectFieldOption('fields[field_test_text][region]', 'second');
$this->submitForm([], 'Save');
$this->assertSession()->pageTextContains('Your settings have been saved.');
// The updated region is used.
$this->drupalGet('entity_test/manage/1/edit');
$this->assertFieldInRegion('field_test_text[0][value]', 'second');
// The layout is still in use without Field UI.
$this->container->get('module_installer')->uninstall(['field_ui']);
$this->drupalGet('entity_test/manage/1/edit');
$this->assertFieldInRegion('field_test_text[0][value]', 'second');
}
/**
* Tests the use of field layout for entity view displays.
*/
public function testEntityView(): void {
// The one-column layout is in use.
$this->drupalGet('entity_test/structure/entity_test/display');
$this->assertEquals(['Content', 'Disabled'], $this->getRegionTitles());
// Switch the layout to two columns.
$this->click('#edit-field-layouts');
$this->getSession()->getPage()->selectFieldOption('field_layout', 'layout_twocol');
$this->assertSession()->assertWaitOnAjaxRequest();
$this->submitForm([], 'Save');
$this->assertSession()->pageTextContains('Your settings have been saved.');
$this->assertEquals(['Top', 'First', 'Second', 'Bottom', 'Disabled'], $this->getRegionTitles());
$this->drupalGet('entity_test/1');
// No fields are visible, and the regions don't display when empty.
$this->assertSession()->elementNotExists('css', '.layout--twocol');
$this->assertSession()->elementNotExists('css', '.layout__region');
$this->assertSession()->pageTextNotContains('The field test text value');
// After a refresh the new regions are still there.
$this->drupalGet('entity_test/structure/entity_test/display');
$this->assertEquals(['Top', 'First', 'Second', 'Bottom', 'Disabled'], $this->getRegionTitles());
$this->assertSession()->waitForElement('css', '.tabledrag-handle');
$id = $this->getSession()->getPage()->find('css', '[name="form_build_id"]')->getValue();
// Drag the field to the first region.
$this->assertTrue($this->assertSession()->optionExists('fields[field_test_text][region]', 'hidden')->isSelected());
$field_test_text_row = $this->getSession()->getPage()->find('css', '#field-test-text');
$first_region_row = $this->getSession()->getPage()->find('css', '.region-first-message');
$field_test_text_row->find('css', '.handle')->dragTo($first_region_row);
$this->assertSession()->assertWaitOnAjaxRequest();
$this->assertFalse($this->assertSession()->optionExists('fields[field_test_text][region]', 'hidden')->isSelected());
$this->assertSession()->waitForElement('css', "[name='form_build_id']:not([value='$id'])");
$this->submitForm([], 'Save');
$this->assertSession()->pageTextContains('Your settings have been saved.');
// The new layout is used.
$this->drupalGet('entity_test/1');
$this->assertSession()->elementExists('css', '.layout--twocol');
$this->assertSession()->elementTextContains('css', '.layout__region--first', 'The field test text value');
// Move the field to the second region without tabledrag.
$this->drupalGet('entity_test/structure/entity_test/display');
$this->getSession()->getPage()->pressButton('Show row weights');
$this->getSession()->getPage()->selectFieldOption('fields[field_test_text][region]', 'second');
$this->submitForm([], 'Save');
$this->assertSession()->pageTextContains('Your settings have been saved.');
// The updated region is used.
$this->drupalGet('entity_test/1');
$this->assertSession()->elementTextContains('css', '.layout__region--second', 'The field test text value');
// The layout is still in use without Field UI.
$this->container->get('module_installer')->uninstall(['field_ui']);
$this->drupalGet('entity_test/1');
$this->assertSession()->elementExists('css', '.layout--twocol');
$this->assertSession()->elementTextContains('css', '.layout__region--second', 'The field test text value');
}
/**
* Tests layout plugins with forms.
*/
public function testLayoutForms(): void {
$this->drupalGet('entity_test/structure/entity_test/display');
// Switch to a field layout with settings.
$this->click('#edit-field-layouts');
// Test switching between layouts with and without forms.
$this->getSession()->getPage()->selectFieldOption('field_layout', 'layout_test_plugin');
$this->assertSession()->assertExpectedAjaxRequest(1);
$this->assertSession()->fieldExists('settings_wrapper[layout_settings][setting_1]');
$this->getSession()->getPage()->selectFieldOption('field_layout', 'layout_test_2col');
$this->assertSession()->assertExpectedAjaxRequest(2);
$this->assertSession()->fieldNotExists('settings_wrapper[layout_settings][setting_1]');
$this->getSession()->getPage()->selectFieldOption('field_layout', 'layout_test_plugin');
$this->assertSession()->assertExpectedAjaxRequest(3);
$this->assertSession()->fieldExists('settings_wrapper[layout_settings][setting_1]');
// Move the test field to the content region.
$this->getSession()->getPage()->pressButton('Show row weights');
$this->getSession()->getPage()->selectFieldOption('fields[field_test_text][region]', 'content');
$this->submitForm([], 'Save');
$this->drupalGet('entity_test/1');
$this->assertSession()->pageTextContains('Blah: Default');
// Update the field layout settings.
$this->drupalGet('entity_test/structure/entity_test/display');
$this->click('#edit-field-layouts');
$this->getSession()->getPage()->fillField('settings_wrapper[layout_settings][setting_1]', 'Test text');
$this->submitForm([], 'Save');
$this->drupalGet('entity_test/1');
$this->assertSession()->pageTextContains('Blah: Test text');
}
/**
* Tests changing the formatter and region at the same time.
*/
public function testChangingFormatterAndRegion(): void {
$assert_session = $this->assertSession();
$page = $this->getSession()->getPage();
// Add the test field to the content region.
$this->drupalGet('entity_test/structure/entity_test/display');
$page->find('css', '#field-test-text .handle')->dragTo($page->find('css', '.region-content-message'));
$assert_session->assertWaitOnAjaxRequest();
$page->pressButton('Save');
$assert_session->fieldValueEquals('fields[field_test_text][region]', 'content');
$assert_session->fieldValueEquals('fields[field_test_text][type]', 'text_default');
// Switch the layout to two columns.
$this->click('#edit-field-layouts');
$page->selectFieldOption('field_layout', 'layout_twocol');
$assert_session->assertWaitOnAjaxRequest();
$page->pressButton('Save');
$assert_session->fieldValueEquals('fields[field_test_text][region]', 'first');
// Change the formatter and move to another region.
$page->selectFieldOption('fields[field_test_text][type]', 'text_trimmed');
$assert_session->assertWaitOnAjaxRequest();
$page->find('css', '#field-test-text .handle')->dragTo($page->find('css', '.region-second-message'));
$assert_session->assertWaitOnAjaxRequest();
$page->pressButton('Save');
// Assert that both the formatter and region change are persisted.
$assert_session->fieldValueEquals('fields[field_test_text][region]', 'second');
$assert_session->fieldValueEquals('fields[field_test_text][type]', 'text_trimmed');
}
/**
* Gets the region titles on the page.
*
* @return string[]
* An array of region titles.
*/
protected function getRegionTitles() {
$region_titles = [];
$region_title_elements = $this->getSession()->getPage()->findAll('css', '.region-title td');
/** @var \Behat\Mink\Element\NodeElement[] $region_title_elements */
foreach ($region_title_elements as $region_title_element) {
$region_titles[] = $region_title_element->getText();
}
return $region_titles;
}
/**
* Asserts that a field exists in a given region.
*
* @param string $field_selector
* The field selector, one of field id|name|label|value.
* @param string $region_name
* The machine name of the region.
*
* @internal
*/
protected function assertFieldInRegion(string $field_selector, string $region_name): void {
$region_element = $this->getSession()->getPage()->find('css', ".layout__region--$region_name");
$this->assertNotNull($region_element);
$this->assertSession()->fieldExists($field_selector, $region_element);
}
}

View File

@@ -0,0 +1,198 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\field_layout\Kernel;
use Drupal\field_layout\Entity\FieldLayoutEntityViewDisplay;
use Drupal\KernelTests\KernelTestBase;
/**
* @coversDefaultClass \Drupal\field_layout\Entity\FieldLayoutEntityDisplayTrait
* @group field_layout
*/
class FieldLayoutEntityDisplayTest extends KernelTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = [
'layout_discovery',
'field_layout',
'entity_test',
'field_layout_test',
'field_test',
'system',
];
/**
* @covers ::preSave
* @covers ::calculateDependencies
*/
public function testPreSave(): void {
// Create an entity display with one hidden and one visible field.
$entity_display = FieldLayoutEntityViewDisplay::create([
'targetEntityType' => 'entity_test',
'bundle' => 'entity_test',
'mode' => 'default',
'status' => TRUE,
'content' => [
'foo' => ['type' => 'field_no_settings'],
'name' => ['type' => 'hidden', 'region' => 'content'],
],
'hidden' => [
'bar' => TRUE,
],
]);
$expected = [
'langcode' => 'en',
'status' => TRUE,
'dependencies' => [],
'third_party_settings' => [
'field_layout' => [
'id' => 'layout_onecol',
'settings' => [
'label' => '',
],
],
],
'id' => 'entity_test.entity_test.default',
'targetEntityType' => 'entity_test',
'bundle' => 'entity_test',
'mode' => 'default',
'content' => [
'foo' => [
'type' => 'field_no_settings',
],
],
'hidden' => [
'bar' => TRUE,
],
];
$this->assertEntityValues($expected, $entity_display->toArray());
// Save the display.
// the 'content' property and the visible field has the default region set.
$entity_display->save();
// The dependencies have been updated.
$expected['dependencies']['module'] = [
'entity_test',
'field_layout',
'layout_discovery',
];
// A third party setting is added by the entity_test module.
$expected['third_party_settings']['entity_test'] = ['foo' => 'bar'];
// The visible field is assigned the default region.
$expected['content']['foo']['region'] = 'content';
$this->assertEntityValues($expected, $entity_display->toArray());
// Assign a new layout that has default settings and complex dependencies,
// but do not save yet.
$entity_display->setLayoutId('test_layout_main_and_footer');
// The default settings were added.
$expected['third_party_settings']['field_layout'] = [
'id' => 'test_layout_main_and_footer',
'settings' => [
'setting_1' => 'Default',
],
];
// The field was moved to the default region.
$expected['content']['foo'] = [
'type' => 'field_no_settings',
'region' => 'main',
'weight' => -4,
'settings' => [],
'third_party_settings' => [],
];
$this->assertEntityValues($expected, $entity_display->toArray());
// After saving, the dependencies have been updated.
$entity_display->save();
$expected['dependencies']['module'] = [
'entity_test',
'field_layout',
'field_layout_test',
'layout_discovery',
'system',
];
$this->assertEntityValues($expected, $entity_display->toArray());
// Assign a layout with provided settings.
$entity_display->setLayoutId('test_layout_main_and_footer', ['setting_1' => 'foobar']);
$entity_display->save();
// The setting overrides the default value.
$expected['third_party_settings']['field_layout']['settings']['setting_1'] = 'foobar';
$this->assertEntityValues($expected, $entity_display->toArray());
// Move a field to the non-default region.
$component = $entity_display->getComponent('foo');
$component['region'] = 'footer';
$entity_display->setComponent('foo', $component);
$entity_display->save();
// The field region is saved.
$expected['content']['foo']['region'] = 'footer';
$this->assertEntityValues($expected, $entity_display->toArray());
// Assign a different layout that shares the same non-default region.
$entity_display->setLayoutId('test_layout_content_and_footer');
$entity_display->save();
// The dependencies have been updated.
$expected['dependencies']['module'] = [
'entity_test',
'field_layout',
'field_layout_test',
];
// The layout has been updated.
$expected['third_party_settings']['field_layout'] = [
'id' => 'test_layout_content_and_footer',
'settings' => [
'label' => '',
],
];
// The field remains in its current region instead of moving to the default.
$this->assertEntityValues($expected, $entity_display->toArray());
$this->container->get('module_installer')->uninstall(['field_layout']);
$entity_storage = $this->container->get('entity_type.manager')->getStorage('entity_view_display');
$entity_display = $entity_storage->load('entity_test.entity_test.default');
// The dependencies have been updated.
$expected['dependencies']['module'] = [
'entity_test',
];
// All field_layout settings were removed.
unset($expected['third_party_settings']['field_layout']);
// The field has returned to the default content region.
$expected['content']['foo']['region'] = 'content';
$this->assertEntityValues($expected, $entity_display->toArray());
}
/**
* Asserts than an entity has the correct values.
*
* @param array $expected
* The expected values.
* @param array $values
* The actual values.
* @param string $message
* (optional) An error message.
*
* @internal
*/
public static function assertEntityValues(array $expected, array $values, string $message = ''): void {
static::assertArrayHasKey('uuid', $values);
unset($values['uuid']);
static::assertEquals($expected, $values, $message);
}
}

View File

@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\field_layout\Kernel;
use Drupal\Tests\layout_builder\Kernel\LayoutBuilderCompatibilityTestBase;
/**
* @group field_layout
*/
class FieldLayoutUninstallTest extends LayoutBuilderCompatibilityTestBase {
/**
* Ensures field layout can be uninstalled with layout builder enabled.
*/
public function testFieldLayoutUninstall(): void {
// Setup user schema so user hook uninstall hook doesn't break.
$this->installSchema('user', 'users_data');
// Setup layout builder and same displays.
$this->installLayoutBuilder();
// Ensure install hook can handle displays without a layout.
$this->container->get('module_installer')->install(['field_layout']);
// Ensure uninstall hook can handle displays without a layout.
$this->container->get('module_installer')->uninstall(['field_layout']);
}
}

View File

@@ -0,0 +1,334 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\field_layout\Unit;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\field_layout\Display\EntityDisplayWithLayoutInterface;
use Drupal\field_layout\FieldLayoutBuilder;
use Drupal\Core\Layout\LayoutPluginManagerInterface;
use Drupal\Core\Layout\LayoutDefault;
use Drupal\Core\Layout\LayoutDefinition;
use Drupal\Tests\UnitTestCase;
use Prophecy\Argument;
/**
* @coversDefaultClass \Drupal\field_layout\FieldLayoutBuilder
* @group field_layout
*/
class FieldLayoutBuilderTest extends UnitTestCase {
/**
* @var \Drupal\Core\Layout\LayoutPluginManager|\Prophecy\Prophecy\ProphecyInterface
*/
protected $layoutPluginManager;
/**
* @var \Drupal\Core\Entity\EntityFieldManagerInterface|\Prophecy\Prophecy\ProphecyInterface
*/
protected $entityFieldManager;
/**
* @var \Drupal\field_layout\FieldLayoutBuilder
*/
protected $fieldLayoutBuilder;
/**
* @var \Drupal\Core\Layout\LayoutInterface
*/
protected $layoutPlugin;
/**
* @var \Drupal\Core\Layout\LayoutDefinition
*/
protected $pluginDefinition;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->pluginDefinition = new LayoutDefinition([
'library' => 'field_layout/drupal.layout.twocol',
'theme_hook' => 'layout__twocol',
'regions' => [
'left' => [
'label' => 'Left',
],
'right' => [
'label' => 'Right',
],
],
]);
$this->layoutPlugin = new LayoutDefault([], 'two_column', $this->pluginDefinition);
$this->layoutPluginManager = $this->prophesize(LayoutPluginManagerInterface::class);
$this->layoutPluginManager->getDefinition('unknown', FALSE)->willReturn(NULL);
$this->layoutPluginManager->getDefinition('two_column', FALSE)->willReturn($this->pluginDefinition);
$this->entityFieldManager = $this->prophesize(EntityFieldManagerInterface::class);
$this->fieldLayoutBuilder = new FieldLayoutBuilder($this->layoutPluginManager->reveal(), $this->entityFieldManager->reveal());
}
/**
* @covers ::buildView
* @covers ::getFields
*/
public function testBuildView(): void {
$definitions = [];
$non_configurable_field_definition = $this->prophesize(FieldDefinitionInterface::class);
$non_configurable_field_definition->isDisplayConfigurable('view')->willReturn(FALSE);
$definitions['non_configurable_field'] = $non_configurable_field_definition->reveal();
$definitions['non_configurable_field_with_extra_field'] = $non_configurable_field_definition->reveal();
$this->entityFieldManager->getFieldDefinitions('the_entity_type_id', 'the_entity_type_bundle')->willReturn($definitions);
$extra_fields = [];
$extra_fields['non_configurable_field_with_extra_field'] = [
'label' => 'This non-configurable field is also defined in hook_entity_extra_field_info()',
];
$this->entityFieldManager->getExtraFields('the_entity_type_id', 'the_entity_type_bundle')->willReturn($extra_fields);
$build = [
'test1' => [
'#markup' => 'Test1',
],
'test2' => [
'#markup' => 'Test2',
],
'non_configurable_field' => [
'#markup' => 'Non-configurable',
],
'non_configurable_field_with_extra_field' => [
'#markup' => 'Non-configurable with extra field',
],
];
$display = $this->prophesize(EntityDisplayWithLayoutInterface::class);
$display->getTargetEntityTypeId()->willReturn('the_entity_type_id');
$display->getTargetBundle()->willReturn('the_entity_type_bundle');
$display->getLayout()->willReturn($this->layoutPlugin);
$display->getLayoutId()->willReturn('two_column');
$display->getLayoutSettings()->willReturn([]);
$display->getComponents()->willReturn([
'test1' => [
'region' => 'right',
],
'test2' => [
'region' => 'unknown_region',
],
'non_configurable_field' => [
'region' => 'left',
],
'non_configurable_field_with_extra_field' => [
'region' => 'left',
],
]);
$expected = [
'test2' => [
'#markup' => 'Test2',
],
'non_configurable_field' => [
'#markup' => 'Non-configurable',
],
'_field_layout' => [
'left' => [
'non_configurable_field_with_extra_field' => [
'#markup' => 'Non-configurable with extra field',
],
],
'right' => [
'test1' => [
'#markup' => 'Test1',
],
],
'#in_preview' => FALSE,
'#settings' => [
'label' => '',
],
'#layout' => $this->pluginDefinition,
'#theme' => 'layout__twocol',
'#attached' => [
'library' => [
'field_layout/drupal.layout.twocol',
],
],
],
];
$this->fieldLayoutBuilder->buildView($build, $display->reveal());
$this->assertEquals($expected, $build);
$this->assertSame($expected, $build);
}
/**
* @covers ::buildForm
* @covers ::getFields
*/
public function testBuildForm(): void {
$definitions = [];
$non_configurable_field_definition = $this->prophesize(FieldDefinitionInterface::class);
$non_configurable_field_definition->isDisplayConfigurable('form')->willReturn(FALSE);
$definitions['non_configurable_field'] = $non_configurable_field_definition->reveal();
$this->entityFieldManager->getFieldDefinitions('the_entity_type_id', 'the_entity_type_bundle')->willReturn($definitions);
$this->entityFieldManager->getExtraFields('the_entity_type_id', 'the_entity_type_bundle')->willReturn([]);
$build = [
'test1' => [
'#markup' => 'Test1',
],
'test2' => [
'#markup' => 'Test2',
'#group' => 'existing_group',
],
'test3' => [
'#markup' => 'Test3',
],
'field_layout' => [
'#markup' => 'Field created through the UI happens to be named "Layout"',
],
'non_configurable_field' => [
'#markup' => 'Non-configurable',
],
];
$display = $this->prophesize(EntityDisplayWithLayoutInterface::class);
$display->getTargetEntityTypeId()->willReturn('the_entity_type_id');
$display->getTargetBundle()->willReturn('the_entity_type_bundle');
$display->getLayout()->willReturn($this->layoutPlugin);
$display->getLayoutId()->willReturn('two_column');
$display->getLayoutSettings()->willReturn([]);
$display->getComponents()->willReturn([
'test1' => [
'region' => 'right',
],
'test2' => [
'region' => 'left',
],
'test3' => [
'region' => 'unknown_region',
],
'field_layout' => [
'region' => 'right',
],
'non_configurable_field' => [
'region' => 'left',
],
]);
$expected = [
'test1' => [
'#markup' => 'Test1',
'#group' => 'right',
],
'test2' => [
'#markup' => 'Test2',
'#group' => 'existing_group',
],
'test3' => [
'#markup' => 'Test3',
],
'field_layout' => [
'#markup' => 'Field created through the UI happens to be named "Layout"',
'#group' => 'right',
],
'non_configurable_field' => [
'#markup' => 'Non-configurable',
],
'_field_layout' => [
'left' => [
'#process' => ['\Drupal\Core\Render\Element\RenderElementBase::processGroup'],
'#pre_render' => ['\Drupal\Core\Render\Element\RenderElementBase::preRenderGroup'],
],
'right' => [
'#process' => ['\Drupal\Core\Render\Element\RenderElementBase::processGroup'],
'#pre_render' => ['\Drupal\Core\Render\Element\RenderElementBase::preRenderGroup'],
],
'#in_preview' => FALSE,
'#settings' => [
'label' => '',
],
'#layout' => $this->pluginDefinition,
'#theme' => 'layout__twocol',
'#attached' => [
'library' => [
'field_layout/drupal.layout.twocol',
],
],
],
];
$this->fieldLayoutBuilder->buildForm($build, $display->reveal());
$this->assertEquals($expected, $build);
$this->assertSame($expected, $build);
}
/**
* @covers ::buildForm
*/
public function testBuildFormEmpty(): void {
$definitions = [];
$non_configurable_field_definition = $this->prophesize(FieldDefinitionInterface::class);
$non_configurable_field_definition->isDisplayConfigurable('form')->willReturn(FALSE);
$definitions['non_configurable_field'] = $non_configurable_field_definition->reveal();
$this->entityFieldManager->getFieldDefinitions('the_entity_type_id', 'the_entity_type_bundle')->willReturn($definitions);
$this->entityFieldManager->getExtraFields('the_entity_type_id', 'the_entity_type_bundle')->willReturn([]);
$build = [
'non_configurable_field' => [
'#markup' => 'Non-configurable',
],
];
$display = $this->prophesize(EntityDisplayWithLayoutInterface::class);
$display->getTargetEntityTypeId()->willReturn('the_entity_type_id');
$display->getTargetBundle()->willReturn('the_entity_type_bundle');
$display->getLayout()->willReturn($this->layoutPlugin);
$display->getLayoutId()->willReturn('two_column');
$display->getLayoutSettings()->willReturn([]);
$display->getComponents()->willReturn([
'test1' => [
'region' => 'right',
],
'non_configurable_field' => [
'region' => 'left',
],
]);
$expected = [
'non_configurable_field' => [
'#markup' => 'Non-configurable',
],
];
$this->fieldLayoutBuilder->buildForm($build, $display->reveal());
$this->assertSame($expected, $build);
}
/**
* @covers ::buildForm
*/
public function testBuildFormNoLayout(): void {
$this->entityFieldManager->getFieldDefinitions(Argument::any(), Argument::any())->shouldNotBeCalled();
$build = [
'test1' => [
'#markup' => 'Test1',
],
];
$display = $this->prophesize(EntityDisplayWithLayoutInterface::class);
$display->getLayoutId()->willReturn('unknown');
$display->getLayoutSettings()->willReturn([]);
$display->getComponents()->shouldNotBeCalled();
$expected = [
'test1' => [
'#markup' => 'Test1',
],
];
$this->fieldLayoutBuilder->buildForm($build, $display->reveal());
$this->assertSame($expected, $build);
}
}