3 namespace Drupal\Tests\field\Kernel;
5 use Drupal\Component\Utility\Unicode;
6 use Drupal\Core\Entity\EntityStorageException;
7 use Drupal\Core\Field\FieldException;
8 use Drupal\entity_test\Entity\EntityTest;
9 use Drupal\field\Entity\FieldStorageConfig;
10 use Drupal\field\Entity\FieldConfig;
13 * Create field entities by attaching fields to entities.
15 * @coversDefaultClass \Drupal\Core\Field\FieldConfigBase
19 class FieldCrudTest extends FieldKernelTestBase {
22 * The field storage entity.
24 * @var \Drupal\field\Entity\FieldStorageConfig
26 protected $fieldStorage;
29 * The field entity definition.
33 protected $fieldStorageDefinition;
36 * The field entity definition.
40 protected $fieldDefinition;
42 public function setUp() {
45 $this->fieldStorageDefinition = [
46 'field_name' => Unicode::strtolower($this->randomMachineName()),
47 'entity_type' => 'entity_test',
48 'type' => 'test_field',
50 $this->fieldStorage = FieldStorageConfig::create($this->fieldStorageDefinition);
51 $this->fieldStorage->save();
52 $this->fieldDefinition = [
53 'field_name' => $this->fieldStorage->getName(),
54 'entity_type' => 'entity_test',
55 'bundle' => 'entity_test',
59 // TODO : test creation with
60 // - a full fledged $field structure, check that all the values are there
61 // - a minimal $field structure, check all default values are set
62 // defer actual $field comparison to a helper function, used for the two cases above,
63 // and for testUpdateField
66 * Test the creation of a field.
68 public function testCreateField() {
69 $field = FieldConfig::create($this->fieldDefinition);
72 $field = FieldConfig::load($field->id());
73 $this->assertTrue($field->getSetting('field_setting_from_config_data'));
74 $this->assertNull($field->getSetting('config_data_from_field_setting'));
76 // Read the configuration. Check against raw configuration data rather than
77 // the loaded ConfigEntity, to be sure we check that the defaults are
79 $config = $this->config('field.field.' . $field->id())->get();
80 $field_type_manager = \Drupal::service('plugin.manager.field.field_type');
82 $this->assertTrue($config['settings']['config_data_from_field_setting']);
83 $this->assertTrue(!isset($config['settings']['field_setting_from_config_data']));
85 // Since we are working with raw configuration, this needs to be unset
87 // @see Drupal\field_test\Plugin\Field\FieldType\TestItem::fieldSettingsFromConfigData()
88 unset($config['settings']['config_data_from_field_setting']);
90 // Check that default values are set.
91 $this->assertEqual($config['required'], FALSE, 'Required defaults to false.');
92 $this->assertIdentical($config['label'], $this->fieldDefinition['field_name'], 'Label defaults to field name.');
93 $this->assertIdentical($config['description'], '', 'Description defaults to empty string.');
95 // Check that default settings are set.
96 $this->assertEqual($config['settings'], $field_type_manager->getDefaultFieldSettings($this->fieldStorageDefinition['type']), 'Default field settings have been written.');
98 // Check that the denormalized 'field_type' was properly written.
99 $this->assertEqual($config['field_type'], $this->fieldStorageDefinition['type']);
101 // Guarantee that the field/bundle combination is unique.
103 FieldConfig::create($this->fieldDefinition)->save();
104 $this->fail(t('Cannot create two fields with the same field / bundle combination.'));
106 catch (EntityStorageException $e) {
107 $this->pass(t('Cannot create two fields with the same field / bundle combination.'));
110 // Check that the specified field exists.
112 $this->fieldDefinition['field_name'] = $this->randomMachineName();
113 FieldConfig::create($this->fieldDefinition)->save();
114 $this->fail(t('Cannot create a field with a non-existing storage.'));
116 catch (FieldException $e) {
117 $this->pass(t('Cannot create a field with a non-existing storage.'));
120 // TODO: test other failures.
124 * Tests setting and adding property constraints to a configurable field.
126 * @covers ::setPropertyConstraints
127 * @covers ::addPropertyConstraints
129 public function testFieldPropertyConstraints() {
130 $field = FieldConfig::create($this->fieldDefinition);
132 $field_name = $this->fieldStorage->getName();
134 // Test that constraints are applied to configurable fields. A TestField and
135 // a Range constraint are added dynamically to limit the field to values
137 // @see field_test_entity_bundle_field_info_alter()
138 \Drupal::state()->set('field_test_constraint', $field_name);
140 // Clear the field definitions cache so the new constraints added by
141 // field_test_entity_bundle_field_info_alter() are taken into consideration.
142 \Drupal::service('entity_field.manager')->clearCachedFieldDefinitions();
144 // Test the newly added property constraints in the same request as when the
145 // caches were cleared. This will test the field definitions that are stored
146 // in the static cache of
147 // \Drupal\Core\Entity\EntityFieldManager::getFieldDefinitions().
148 $this->doFieldPropertyConstraintsTests();
150 // In order to test a real-world scenario where the property constraints are
151 // only stored in the persistent cache of
152 // \Drupal\Core\Entity\EntityFieldManager::getFieldDefinitions(), we need to
153 // simulate a new request by removing the 'entity_field.manager' service,
154 // thus forcing it to be re-initialized without static caches.
155 \Drupal::getContainer()->set('entity_field.manager', NULL);
157 // This will test the field definitions that are stored in the persistent
158 // cache by \Drupal\Core\Entity\EntityFieldManager::getFieldDefinitions().
159 $this->doFieldPropertyConstraintsTests();
163 * Tests configurable field validation.
165 * @see field_test_entity_bundle_field_info_alter()
167 protected function doFieldPropertyConstraintsTests() {
168 $field_name = $this->fieldStorage->getName();
170 // Check that a valid value (not -2 and between 0 and 32) doesn't trigger
172 $entity = EntityTest::create();
173 $entity->set($field_name, 1);
174 $violations = $entity->validate();
175 $this->assertCount(0, $violations, 'No violations found when in-range value passed.');
177 // Check that a value that is specifically restricted triggers both
179 $entity->set($field_name, -2);
180 $violations = $entity->validate();
181 $this->assertCount(2, $violations, 'Two violations found when using a null and outside the range value.');
183 $this->assertEquals($field_name . '.0.value', $violations[0]->getPropertyPath());
184 $this->assertEquals(t('%name does not accept the value @value.', ['%name' => $field_name, '@value' => -2]), $violations[0]->getMessage());
186 $this->assertEquals($field_name . '.0.value', $violations[1]->getPropertyPath());
187 $this->assertEquals(t('This value should be %limit or more.', ['%limit' => 0]), $violations[1]->getMessage());
189 // Check that a value that is not specifically restricted but outside the
190 // range triggers the expected violation.
191 $entity->set($field_name, 33);
192 $violations = $entity->validate();
193 $this->assertCount(1, $violations, 'Violations found when using value outside the range.');
194 $this->assertEquals($field_name . '.0.value', $violations[0]->getPropertyPath());
195 $this->assertEquals(t('This value should be %limit or less.', ['%limit' => 32]), $violations[0]->getMessage());
199 * Test creating a field with custom storage set.
201 public function testCreateFieldCustomStorage() {
202 $field_name = Unicode::strtolower($this->randomMachineName());
203 \Drupal::state()->set('field_test_custom_storage', $field_name);
205 $field_storage = FieldStorageConfig::create([
206 'field_name' => $field_name,
207 'entity_type' => 'entity_test',
208 'type' => 'test_field',
209 'custom_storage' => TRUE,
211 $field_storage->save();
213 $field = FieldConfig::create([
214 'field_name' => $field_storage->getName(),
215 'entity_type' => 'entity_test',
216 'bundle' => 'entity_test',
220 \Drupal::entityManager()->clearCachedFieldDefinitions();
222 // Check that no table has been created for the field.
223 $this->assertFalse(\Drupal::database()->schema()->tableExists('entity_test__' . $field_storage->getName()));
225 // Save an entity with a value in the custom storage field and verify no
226 // data is retrieved on load.
227 $entity = EntityTest::create(['name' => $this->randomString(), $field_name => 'Test value']);
228 $this->assertIdentical('Test value', $entity->{$field_name}->value, 'The test value is set on the field.');
231 $entity = EntityTest::load($entity->id());
233 $this->assertNull($entity->{$field_name}->value, 'The loaded entity field value is NULL.');
237 * Test reading back a field definition.
239 public function testReadField() {
240 FieldConfig::create($this->fieldDefinition)->save();
242 // Read the field back.
243 $field = FieldConfig::load('entity_test.' . $this->fieldDefinition['bundle'] . '.' . $this->fieldDefinition['field_name']);
244 $this->assertTrue($this->fieldDefinition['field_name'] == $field->getName(), 'The field was properly read.');
245 $this->assertTrue($this->fieldDefinition['entity_type'] == $field->getTargetEntityTypeId(), 'The field was properly read.');
246 $this->assertTrue($this->fieldDefinition['bundle'] == $field->getTargetBundle(), 'The field was properly read.');
250 * Test the update of a field.
252 public function testUpdateField() {
253 FieldConfig::create($this->fieldDefinition)->save();
255 // Check that basic changes are saved.
256 $field = FieldConfig::load('entity_test.' . $this->fieldDefinition['bundle'] . '.' . $this->fieldDefinition['field_name']);
257 $field->setRequired(!$field->isRequired());
258 $field->setLabel($this->randomMachineName());
259 $field->set('description', $this->randomMachineName());
260 $field->setSetting('test_field_setting', $this->randomMachineName());
263 $field_new = FieldConfig::load('entity_test.' . $this->fieldDefinition['bundle'] . '.' . $this->fieldDefinition['field_name']);
264 $this->assertEqual($field->isRequired(), $field_new->isRequired(), '"required" change is saved');
265 $this->assertEqual($field->getLabel(), $field_new->getLabel(), '"label" change is saved');
266 $this->assertEqual($field->getDescription(), $field_new->getDescription(), '"description" change is saved');
268 // TODO: test failures.
272 * Test the deletion of a field.
274 public function testDeleteField() {
275 // TODO: Test deletion of the data stored in the field also.
276 // Need to check that data for a 'deleted' field / storage doesn't get loaded
277 // Need to check data marked deleted is cleaned on cron (not implemented yet...)
279 // Create two fields for the same field storage so we can test that only one
281 FieldConfig::create($this->fieldDefinition)->save();
282 $another_field_definition = $this->fieldDefinition;
283 $another_field_definition['bundle'] .= '_another_bundle';
284 entity_test_create_bundle($another_field_definition['bundle']);
285 FieldConfig::create($another_field_definition)->save();
287 // Test that the first field is not deleted, and then delete it.
288 $field = current(entity_load_multiple_by_properties('field_config', ['entity_type' => 'entity_test', 'field_name' => $this->fieldDefinition['field_name'], 'bundle' => $this->fieldDefinition['bundle'], 'include_deleted' => TRUE]));
289 $this->assertTrue(!empty($field) && empty($field->deleted), 'A new field is not marked for deletion.');
292 // Make sure the field is marked as deleted when it is specifically loaded.
293 $field = current(entity_load_multiple_by_properties('field_config', ['entity_type' => 'entity_test', 'field_name' => $this->fieldDefinition['field_name'], 'bundle' => $this->fieldDefinition['bundle'], 'include_deleted' => TRUE]));
294 $this->assertTrue($field->isDeleted(), 'A deleted field is marked for deletion.');
296 // Try to load the field normally and make sure it does not show up.
297 $field = FieldConfig::load('entity_test.' . '.' . $this->fieldDefinition['bundle'] . '.' . $this->fieldDefinition['field_name']);
298 $this->assertTrue(empty($field), 'A deleted field is not loaded by default.');
300 // Make sure the other field is not deleted.
301 $another_field = FieldConfig::load('entity_test.' . $another_field_definition['bundle'] . '.' . $another_field_definition['field_name']);
302 $this->assertTrue(!empty($another_field) && empty($another_field->deleted), 'A non-deleted field is not marked for deletion.');
306 * Tests the cross deletion behavior between field storages and fields.
308 public function testDeleteFieldCrossDeletion() {
309 $field_definition_2 = $this->fieldDefinition;
310 $field_definition_2['bundle'] .= '_another_bundle';
311 entity_test_create_bundle($field_definition_2['bundle']);
313 // Check that deletion of a field storage deletes its fields.
314 $field_storage = $this->fieldStorage;
315 FieldConfig::create($this->fieldDefinition)->save();
316 FieldConfig::create($field_definition_2)->save();
317 $field_storage->delete();
318 $this->assertFalse(FieldConfig::loadByName('entity_test', $this->fieldDefinition['bundle'], $field_storage->getName()));
319 $this->assertFalse(FieldConfig::loadByName('entity_test', $field_definition_2['bundle'], $field_storage->getName()));
321 // Check that deletion of the last field deletes the storage.
322 $field_storage = FieldStorageConfig::create($this->fieldStorageDefinition);
323 $field_storage->save();
324 $field = FieldConfig::create($this->fieldDefinition);
326 $field_2 = FieldConfig::create($field_definition_2);
329 $this->assertTrue(FieldStorageConfig::loadByName('entity_test', $field_storage->getName()));
331 $this->assertFalse(FieldStorageConfig::loadByName('entity_test', $field_storage->getName()));
333 // Check that deletion of all fields using a storage simultaneously deletes
335 $field_storage = FieldStorageConfig::create($this->fieldStorageDefinition);
336 $field_storage->save();
337 $field = FieldConfig::create($this->fieldDefinition);
339 $field_2 = FieldConfig::create($field_definition_2);
341 $this->container->get('entity.manager')->getStorage('field_config')->delete([$field, $field_2]);
342 $this->assertFalse(FieldStorageConfig::loadByName('entity_test', $field_storage->getName()));