public function FieldAttachStorageTest::testFieldAttachLoadMultiple in Drupal 8
Same name and namespace in other branches
- 9 core/modules/field/tests/src/Kernel/FieldAttachStorageTest.php \Drupal\Tests\field\Kernel\FieldAttachStorageTest::testFieldAttachLoadMultiple()
Test the 'multiple' load feature.
File
- core/
modules/ field/ tests/ src/ Kernel/ FieldAttachStorageTest.php, line 76
Class
- FieldAttachStorageTest
- Tests storage-related Field Attach API functions.
Namespace
Drupal\Tests\field\KernelCode
public function testFieldAttachLoadMultiple() {
$entity_type = 'entity_test_rev';
// Define 2 bundles.
$bundles = [
1 => 'test_bundle_1',
2 => 'test_bundle_2',
];
entity_test_create_bundle($bundles[1]);
entity_test_create_bundle($bundles[2]);
// Define 3 fields:
// - field_1 is in bundle_1 and bundle_2,
// - field_2 is in bundle_1,
// - field_3 is in bundle_2.
$field_bundles_map = [
1 => [
1,
2,
],
2 => [
1,
],
3 => [
2,
],
];
for ($i = 1; $i <= 3; $i++) {
$field_names[$i] = 'field_' . $i;
$field_storage = FieldStorageConfig::create([
'field_name' => $field_names[$i],
'entity_type' => $entity_type,
'type' => 'test_field',
]);
$field_storage
->save();
$field_ids[$i] = $field_storage
->uuid();
foreach ($field_bundles_map[$i] as $bundle) {
FieldConfig::create([
'field_name' => $field_names[$i],
'entity_type' => $entity_type,
'bundle' => $bundles[$bundle],
])
->save();
}
}
// Create one test entity per bundle, with random values.
foreach ($bundles as $index => $bundle) {
$entities[$index] = $this->container
->get('entity_type.manager')
->getStorage($entity_type)
->create([
'id' => $index,
'revision_id' => $index,
'type' => $bundle,
]);
$entity = clone $entities[$index];
foreach ($field_names as $field_name) {
if (!$entity
->hasField($field_name)) {
continue;
}
$values[$index][$field_name] = mt_rand(1, 127);
$entity->{$field_name}
->setValue([
'value' => $values[$index][$field_name],
]);
}
$entity
->enforceIsnew();
$entity
->save();
}
// Check that a single load correctly loads field values for both entities.
$controller = \Drupal::entityTypeManager()
->getStorage($entity
->getEntityTypeId());
$controller
->resetCache();
$entities = $controller
->loadMultiple();
foreach ($entities as $index => $entity) {
foreach ($field_names as $field_name) {
if (!$entity
->hasField($field_name)) {
continue;
}
// The field value loaded matches the one inserted.
$this
->assertEqual($entity->{$field_name}->value, $values[$index][$field_name], new FormattableMarkup('Entity %index: expected value was found.', [
'%index' => $index,
]));
}
}
}