View source
<?php
namespace Drupal\Tests\field\Functional;
use Drupal\Component\Utility\Html;
use Drupal\Core\Entity\Entity\EntityFormDisplay;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Form\FormState;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\entity_test\Entity\EntityTestBaseFieldDisplay;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
class FormTest extends FieldTestBase {
protected static $modules = [
'node',
'field_test',
'options',
'entity_test',
'locale',
];
protected $defaultTheme = 'stark';
protected $fieldStorageSingle;
protected $fieldStorageMultiple;
protected $fieldStorageUnlimited;
protected $field;
protected function setUp() : void {
parent::setUp();
$web_user = $this
->drupalCreateUser([
'view test entity',
'administer entity_test content',
]);
$this
->drupalLogin($web_user);
$this->fieldStorageSingle = [
'field_name' => 'field_single',
'entity_type' => 'entity_test',
'type' => 'test_field',
];
$this->fieldStorageMultiple = [
'field_name' => 'field_multiple',
'entity_type' => 'entity_test',
'type' => 'test_field',
'cardinality' => 4,
];
$this->fieldStorageUnlimited = [
'field_name' => 'field_unlimited',
'entity_type' => 'entity_test',
'type' => 'test_field',
'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
];
$this->field = [
'entity_type' => 'entity_test',
'bundle' => 'entity_test',
'label' => $this
->randomMachineName() . '_label',
'description' => '[site:name]_description',
'weight' => mt_rand(0, 127),
'settings' => [
'test_field_setting' => $this
->randomMachineName(),
],
];
}
public function testFieldFormSingle() {
$field_storage = $this->fieldStorageSingle;
$field_name = $field_storage['field_name'];
$this->field['field_name'] = $field_name;
FieldStorageConfig::create($field_storage)
->save();
FieldConfig::create($this->field)
->save();
\Drupal::service('entity_display.repository')
->getFormDisplay($this->field['entity_type'], $this->field['bundle'])
->setComponent($field_name)
->save();
$this
->drupalGet('entity_test/add');
$token_description = Html::escape($this
->config('system.site')
->get('name')) . '_description';
$this
->assertSession()
->pageTextContains($token_description);
$this
->assertSession()
->fieldValueEquals("{$field_name}[0][value]", '');
$this
->assertSession()
->fieldNotExists("{$field_name}[1][value]");
$this
->assertSession()
->pageTextNotContains('From hook_field_widget_single_element_form_alter(): Default form is true.');
$this
->assertSession()
->pageTextNotContains('From hook_field_widget_complete_form_alter(): Default form is true.');
$edit = [
"{$field_name}[0][value]" => -1,
];
$this
->submitForm($edit, 'Save');
$this
->assertSession()
->pageTextContains("{$this->field['label']} does not accept the value -1.");
$value = mt_rand(1, 127);
$edit = [
"{$field_name}[0][value]" => $value,
];
$this
->submitForm($edit, 'Save');
preg_match('|entity_test/manage/(\\d+)|', $this
->getUrl(), $match);
$id = $match[1];
$this
->assertSession()
->pageTextContains('entity_test ' . $id . ' has been created.');
$entity = EntityTest::load($id);
$this
->assertEquals($value, $entity->{$field_name}->value, 'Field value was saved');
$this
->drupalGet('entity_test/manage/' . $id . '/edit');
$this
->assertSession()
->fieldValueEquals("{$field_name}[0][value]", $value);
$this
->assertSession()
->fieldNotExists("{$field_name}[1][value]");
$value = mt_rand(1, 127);
$edit = [
"{$field_name}[0][value]" => $value,
];
$this
->submitForm($edit, 'Save');
$this
->assertSession()
->pageTextContains('entity_test ' . $id . ' has been updated.');
$this->container
->get('entity_type.manager')
->getStorage('entity_test')
->resetCache([
$id,
]);
$entity = EntityTest::load($id);
$this
->assertEquals($value, $entity->{$field_name}->value, 'Field value was updated');
$value = '';
$edit = [
"{$field_name}[0][value]" => $value,
];
$this
->drupalGet('entity_test/manage/' . $id . '/edit');
$this
->submitForm($edit, 'Save');
$this
->assertSession()
->pageTextContains('entity_test ' . $id . ' has been updated.');
$this->container
->get('entity_type.manager')
->getStorage('entity_test')
->resetCache([
$id,
]);
$entity = EntityTest::load($id);
$this
->assertTrue($entity->{$field_name}
->isEmpty(), 'Field was emptied');
}
public function testFieldFormDefaultValue() {
$field_storage = $this->fieldStorageSingle;
$field_name = $field_storage['field_name'];
$this->field['field_name'] = $field_name;
$default = rand(1, 127);
$this->field['default_value'] = [
[
'value' => $default,
],
];
FieldStorageConfig::create($field_storage)
->save();
FieldConfig::create($this->field)
->save();
\Drupal::service('entity_display.repository')
->getFormDisplay($this->field['entity_type'], $this->field['bundle'])
->setComponent($field_name)
->save();
$this
->drupalGet('entity_test/add');
$this
->assertSession()
->fieldValueEquals("{$field_name}[0][value]", $default);
$edit = [
"{$field_name}[0][value]" => '',
];
$this
->submitForm($edit, 'Save');
preg_match('|entity_test/manage/(\\d+)|', $this
->getUrl(), $match);
$id = $match[1];
$this
->assertSession()
->pageTextContains('entity_test ' . $id . ' has been created.');
$entity = EntityTest::load($id);
$this
->assertTrue($entity->{$field_name}
->isEmpty(), 'Field is now empty.');
}
public function testFieldFormSingleRequired() {
$field_storage = $this->fieldStorageSingle;
$field_name = $field_storage['field_name'];
$this->field['field_name'] = $field_name;
$this->field['required'] = TRUE;
FieldStorageConfig::create($field_storage)
->save();
FieldConfig::create($this->field)
->save();
\Drupal::service('entity_display.repository')
->getFormDisplay($this->field['entity_type'], $this->field['bundle'])
->setComponent($field_name)
->save();
$edit = [];
$this
->drupalGet('entity_test/add');
$this
->submitForm($edit, 'Save');
$this
->assertSession()
->pageTextContains("{$this->field['label']} field is required.");
$value = mt_rand(1, 127);
$edit = [
"{$field_name}[0][value]" => $value,
];
$this
->submitForm($edit, 'Save');
preg_match('|entity_test/manage/(\\d+)|', $this
->getUrl(), $match);
$id = $match[1];
$this
->assertSession()
->pageTextContains('entity_test ' . $id . ' has been created.');
$entity = EntityTest::load($id);
$this
->assertEquals($value, $entity->{$field_name}->value, 'Field value was saved');
$value = '';
$edit = [
"{$field_name}[0][value]" => $value,
];
$this
->drupalGet('entity_test/manage/' . $id . '/edit');
$this
->submitForm($edit, 'Save');
$this
->assertSession()
->pageTextContains("{$this->field['label']} field is required.");
}
public function testFieldFormUnlimited() {
$field_storage = $this->fieldStorageUnlimited;
$field_name = $field_storage['field_name'];
$this->field['field_name'] = $field_name;
FieldStorageConfig::create($field_storage)
->save();
FieldConfig::create($this->field)
->save();
\Drupal::service('entity_display.repository')
->getFormDisplay($this->field['entity_type'], $this->field['bundle'])
->setComponent($field_name)
->save();
$this
->drupalGet('entity_test/add');
$this
->assertSession()
->fieldValueEquals("{$field_name}[0][value]", '');
$this
->assertSession()
->fieldNotExists("{$field_name}[1][value]");
$elements = $this
->xpath('//table[@id="field-unlimited-values" and @aria-describedby="edit-field-unlimited--description"]');
$this
->assertTrue(isset($elements[0]), 'aria-describedby attribute is properly placed on multiple value widgets.');
$this
->submitForm([], 'Add another item');
$this
->assertSession()
->fieldValueEquals("{$field_name}[0][value]", '');
$this
->assertSession()
->fieldValueEquals("{$field_name}[1][value]", '');
$this
->assertSession()
->fieldNotExists("{$field_name}[2][value]");
$this
->submitForm([], 'Add another item');
$count = 3;
$delta_range = $count - 1;
$values = $weights = $pattern = $expected_values = [];
$edit = [];
for ($delta = 0; $delta <= $delta_range; $delta++) {
do {
$value = mt_rand(1, 127);
} while (in_array($value, $values));
do {
$weight = mt_rand(-$delta_range, $delta_range);
} while (in_array($weight, $weights));
$edit["{$field_name}[{$delta}][value]"] = $value;
$edit["{$field_name}[{$delta}][_weight]"] = $weight;
$values[$delta] = $value;
$weights[$delta] = $weight;
$field_values[$weight]['value'] = (string) $value;
$pattern[$weight] = "<input [^>]*value=\"{$value}\" [^>]*";
}
$this
->submitForm($edit, 'Add another item');
for ($delta = 0; $delta <= $delta_range; $delta++) {
$this
->assertSession()
->fieldValueEquals("{$field_name}[{$delta}][value]", $values[$delta]);
$this
->assertSession()
->fieldValueEquals("{$field_name}[{$delta}][_weight]", $weights[$delta]);
}
ksort($pattern);
$pattern = implode('.*', array_values($pattern));
$this
->assertSession()
->responseMatches("|{$pattern}|s");
$this
->assertSession()
->fieldValueEquals("{$field_name}[{$delta}][value]", '');
$this
->assertSession()
->fieldValueEquals("{$field_name}[{$delta}][_weight]", $delta);
$this
->assertSession()
->fieldNotExists("{$field_name}[" . ($delta + 1) . '][value]');
$this
->submitForm($edit, 'Save');
preg_match('|entity_test/manage/(\\d+)|', $this
->getUrl(), $match);
$id = $match[1];
$this
->assertSession()
->pageTextContains('entity_test ' . $id . ' has been created.');
$entity = EntityTest::load($id);
ksort($field_values);
$field_values = array_values($field_values);
$this
->assertSame($field_values, $entity->{$field_name}
->getValue(), 'Field values were saved in the correct order');
}
public function testFieldFormUnlimitedRequired() {
$field_name = $this->fieldStorageUnlimited['field_name'];
$this->field['field_name'] = $field_name;
$this->field['required'] = TRUE;
FieldStorageConfig::create($this->fieldStorageUnlimited)
->save();
FieldConfig::create($this->field)
->save();
\Drupal::service('entity_display.repository')
->getFormDisplay($this->field['entity_type'], $this->field['bundle'])
->setComponent($field_name)
->save();
$this
->drupalGet('entity_test/add');
$element = $this
->xpath('//h4[contains(@class, "label") and contains(@class, "js-form-required") and contains(text(), :value)]', [
':value' => $this->field['label'],
]);
$this
->assertTrue(isset($element[0]), 'Required symbol added field label.');
$this
->assertSession()
->elementExists('xpath', "//label[@for='edit-field-unlimited-0-value' and contains(@class, 'visually-hidden') and contains(text(), '{$this->field['label']} (value 1)')]");
}
public function testFieldFormMultivalueWithRequiredRadio() {
$display_repository = \Drupal::service('entity_display.repository');
$field_storage = $this->fieldStorageUnlimited;
$field_name = $field_storage['field_name'];
$this->field['field_name'] = $field_name;
FieldStorageConfig::create($field_storage)
->save();
FieldConfig::create($this->field)
->save();
$display_repository
->getFormDisplay($this->field['entity_type'], $this->field['bundle'])
->setComponent($field_name)
->save();
FieldStorageConfig::create([
'field_name' => 'required_radio_test',
'entity_type' => 'entity_test',
'type' => 'list_string',
'settings' => [
'allowed_values' => [
'yes' => 'yes',
'no' => 'no',
],
],
])
->save();
$field = [
'field_name' => 'required_radio_test',
'entity_type' => 'entity_test',
'bundle' => 'entity_test',
'required' => TRUE,
];
FieldConfig::create($field)
->save();
$display_repository
->getFormDisplay($field['entity_type'], $field['bundle'])
->setComponent($field['field_name'], [
'type' => 'options_buttons',
])
->save();
$this
->drupalGet('entity_test/add');
$this
->submitForm([], 'Add another item');
$this
->assertSession()
->elementNotExists('xpath', '//div[contains(@class, "error")]');
$this
->assertSession()
->fieldValueEquals("{$field_name}[0][value]", '');
$this
->assertSession()
->fieldValueEquals("{$field_name}[1][value]", '');
$this
->assertSession()
->fieldNotExists("{$field_name}[2][value]");
}
public function testFieldFormMultipleWidget() {
$field_storage = $this->fieldStorageMultiple;
$field_name = $field_storage['field_name'];
$this->field['field_name'] = $field_name;
FieldStorageConfig::create($field_storage)
->save();
FieldConfig::create($this->field)
->save();
$form = \Drupal::service('entity_display.repository')
->getFormDisplay($this->field['entity_type'], $this->field['bundle'], 'default')
->setComponent($field_name, [
'type' => 'test_field_widget_multiple',
]);
$form
->save();
$session = $this
->assertSession();
$this
->drupalGet('entity_test/add');
$this
->assertSession()
->fieldValueEquals($field_name, '');
$edit = [
$field_name => '1, 2, 3',
];
$this
->submitForm($edit, 'Save');
preg_match('|entity_test/manage/(\\d+)|', $this
->getUrl(), $match);
$id = $match[1];
$entity_init = EntityTest::load($id);
$this
->assertFieldValues($entity_init, $field_name, [
1,
2,
3,
]);
$this
->drupalGet('entity_test/manage/' . $id . '/edit');
$this
->assertSession()
->fieldValueEquals($field_name, '1, 2, 3');
$edit = [
$field_name => '1, 2, 3, 4, 5',
];
$this
->submitForm($edit, 'Save');
$this
->assertSession()
->pageTextContains('this field cannot hold more than 4 values');
$this
->assertFieldValues($entity_init, $field_name, [
1,
2,
3,
]);
$form
->setComponent($field_name, [
'type' => 'entity_reference_autocomplete',
])
->save();
$this
->drupalGet('entity_test/manage/' . $id . '/edit');
$name = str_replace('_', '-', $field_name);
$session
->responseContains('data-drupal-selector="edit-' . $name . '"');
}
public function testFieldFormAccess() {
$display_repository = \Drupal::service('entity_display.repository');
$entity_type = 'entity_test_rev';
$field_storage = $this->fieldStorageSingle;
$field_storage['entity_type'] = $entity_type;
$field_name = $field_storage['field_name'];
$field = $this->field;
$field['field_name'] = $field_name;
$field['entity_type'] = $entity_type;
$field['bundle'] = $entity_type;
FieldStorageConfig::create($field_storage)
->save();
FieldConfig::create($field)
->save();
$display_repository
->getFormDisplay($entity_type, $entity_type)
->setComponent($field_name)
->save();
$field_storage_no_access = [
'field_name' => 'field_no_edit_access',
'entity_type' => $entity_type,
'type' => 'test_field',
];
$field_name_no_access = $field_storage_no_access['field_name'];
$field_no_access = [
'field_name' => $field_name_no_access,
'entity_type' => $entity_type,
'bundle' => $entity_type,
'default_value' => [
0 => [
'value' => 99,
],
],
];
FieldStorageConfig::create($field_storage_no_access)
->save();
FieldConfig::create($field_no_access)
->save();
$display_repository
->getFormDisplay($field_no_access['entity_type'], $field_no_access['bundle'])
->setComponent($field_name_no_access)
->save();
$entity = $this->container
->get('entity_type.manager')
->getStorage($entity_type)
->create([
'id' => 0,
'revision_id' => 0,
]);
$display = $display_repository
->getFormDisplay($entity_type, $entity_type);
$form = [];
$form_state = new FormState();
$display
->buildForm($entity, $form, $form_state);
$this
->assertFalse($form[$field_name_no_access]['#access'], 'Field #access is FALSE for the field without edit access.');
$this
->drupalGet($entity_type . '/add');
$this
->assertSession()
->fieldNotExists("{$field_name_no_access}[0][value]");
$edit = [
"{$field_name}[0][value]" => 1,
];
$this
->submitForm($edit, 'Save');
preg_match("|{$entity_type}/manage/(\\d+)|", $this
->getUrl(), $match);
$id = $match[1];
$storage = $this->container
->get('entity_type.manager')
->getStorage($entity_type);
$entity = $storage
->load($id);
$this
->assertEquals(99, $entity->{$field_name_no_access}->value, 'Default value was saved for the field with no edit access.');
$this
->assertEquals(1, $entity->{$field_name}->value, 'Entered value vas saved for the field with edit access.');
$edit = [
"{$field_name}[0][value]" => 2,
'revision' => TRUE,
];
$this
->drupalGet($entity_type . '/manage/' . $id . '/edit');
$this
->submitForm($edit, 'Save');
$storage
->resetCache([
$id,
]);
$entity = $storage
->load($id);
$this
->assertEquals(99, $entity->{$field_name_no_access}->value, 'New revision has the expected value for the field with no edit access.');
$this
->assertEquals(2, $entity->{$field_name}->value, 'New revision has the expected value for the field with edit access.');
$entity = $this->container
->get('entity_type.manager')
->getStorage($entity_type)
->loadRevision($entity
->getRevisionId());
$this
->assertEquals(99, $entity->{$field_name_no_access}->value, 'New revision has the expected value for the field with no edit access.');
$this
->assertEquals(2, $entity->{$field_name}->value, 'New revision has the expected value for the field with edit access.');
}
public function testHiddenField() {
$entity_type = 'entity_test_rev';
$field_storage = $this->fieldStorageSingle;
$field_storage['entity_type'] = $entity_type;
$field_name = $field_storage['field_name'];
$this->field['field_name'] = $field_name;
$this->field['default_value'] = [
0 => [
'value' => 99,
],
];
$this->field['entity_type'] = $entity_type;
$this->field['bundle'] = $entity_type;
FieldStorageConfig::create($field_storage)
->save();
$this->field = FieldConfig::create($this->field);
$this->field
->save();
$this
->drupalGet($entity_type . '/add');
$this
->assertSession()
->fieldNotExists("{$field_name}[0][value]");
$this
->submitForm([], 'Save');
preg_match('|' . $entity_type . '/manage/(\\d+)|', $this
->getUrl(), $match);
$id = $match[1];
$this
->assertSession()
->pageTextContains('entity_test_rev ' . $id . ' has been created.');
$storage = $this->container
->get('entity_type.manager')
->getStorage($entity_type);
$entity = $storage
->load($id);
$this
->assertEquals(99, $entity->{$field_name}->value, 'Default value was saved');
$this->field
->setDefaultValue([]);
$this->field
->save();
\Drupal::service('entity_display.repository')
->getFormDisplay($entity_type, $this->field
->getTargetBundle())
->setComponent($this->field
->getName(), [
'type' => 'test_field_widget',
])
->save();
$this
->drupalGet($entity_type . '/manage/' . $id . '/edit');
$this
->assertSession()
->fieldValueEquals("{$field_name}[0][value]", 99);
$value = mt_rand(1, 127);
$edit = [
"{$field_name}[0][value]" => $value,
];
$this
->submitForm($edit, 'Save');
$this
->assertSession()
->pageTextContains('entity_test_rev ' . $id . ' has been updated.');
$storage
->resetCache([
$id,
]);
$entity = $storage
->load($id);
$this
->assertEquals($value, $entity->{$field_name}->value, 'Field value was updated');
\Drupal::service('entity_display.repository')
->getFormDisplay($entity_type, $this->field
->getTargetBundle())
->removeComponent($this->field
->getName())
->save();
$edit = [
'revision' => TRUE,
];
$this
->drupalGet($entity_type . '/manage/' . $id . '/edit');
$this
->submitForm($edit, 'Save');
$storage
->resetCache([
$id,
]);
$entity = $storage
->load($id);
$this
->assertEquals($value, $entity->{$field_name}->value, 'New revision has the expected value for the field with the Hidden widget');
}
public function testLabelOnMultiValueFields() {
$user = $this
->drupalCreateUser([
'administer entity_test content',
]);
$this
->drupalLogin($user);
FieldStorageConfig::create([
'entity_type' => 'entity_test_base_field_display',
'field_name' => 'foo',
'type' => 'text',
'cardinality' => FieldStorageConfig::CARDINALITY_UNLIMITED,
])
->save();
FieldConfig::create([
'entity_type' => 'entity_test_base_field_display',
'bundle' => 'bar',
'field_name' => 'foo',
'label' => "<script>alert('a configurable field');</script>",
])
->save();
EntityFormDisplay::create([
'targetEntityType' => 'entity_test_base_field_display',
'bundle' => 'bar',
'mode' => 'default',
])
->setComponent('foo', [
'type' => 'text_textfield',
])
->enable()
->save();
$entity = EntityTestBaseFieldDisplay::create([
'type' => 'bar',
]);
$entity
->save();
$this
->drupalGet('entity_test_base_field_display/manage/' . $entity
->id());
$this
->assertSession()
->statusCodeEquals(200);
$this
->assertSession()
->pageTextContains('A field with multiple values');
$this
->assertSession()
->assertEscaped("<script>alert('a configurable field');</script>");
}
public function testFieldFormMultipleWidgetAlter() {
$this
->widgetAlterTest('hook_field_widget_complete_form_alter', 'test_field_widget_multiple');
}
public function testFieldFormMultipleWidgetAlterSingleValues() {
$this
->widgetAlterTest('hook_field_widget_complete_form_alter', 'test_field_widget_multiple_single_value');
}
public function testFieldFormMultipleWidgetTypeAlter() {
$this
->widgetAlterTest('hook_field_widget_complete_WIDGET_TYPE_form_alter', 'test_field_widget_multiple');
}
public function testFieldFormMultipleWidgetTypeAlterSingleValues() {
$this
->widgetAlterTest('hook_field_widget_complete_WIDGET_TYPE_form_alter', 'test_field_widget_multiple_single_value');
}
protected function widgetAlterTest($hook, $widget) {
$field_storage = $this->fieldStorageMultiple;
$field_name = $field_storage['field_name'];
$this->field['field_name'] = $field_name;
FieldStorageConfig::create($field_storage)
->save();
FieldConfig::create($this->field)
->save();
\Drupal::state()
->set("field_test.widget_alter_test", [
'hook' => $hook,
'field_name' => $field_name,
'widget' => $widget,
]);
\Drupal::service('entity_display.repository')
->getFormDisplay($this->field['entity_type'], $this->field['bundle'], 'default')
->setComponent($field_name, [
'type' => $widget,
])
->save();
$this
->rebuildAll();
$this
->drupalGet('entity_test/add');
$this
->assertSession()
->pageTextMatchesCount(1, '/From ' . $hook . '.* prefix on ' . $field_name . ' parent element\\./');
if ($widget === 'test_field_widget_multiple_single_value') {
$suffix_text = "From {$hook}(): suffix on {$field_name} child element.";
$this
->assertEquals($field_storage['cardinality'], substr_count($this
->getTextContent(), $suffix_text), "'{$suffix_text}' was found {$field_storage['cardinality']} times using widget {$widget}");
}
}
}