3 namespace Drupal\field\Tests\EntityReference;
5 use Drupal\field\Entity\FieldConfig;
6 use Drupal\field\Entity\FieldStorageConfig;
9 * Provides common functionality for the EntityReference test classes.
11 trait EntityReferenceTestTrait {
14 * Creates a field of an entity reference field storage on the specified bundle.
16 * @param string $entity_type
17 * The type of entity the field will be attached to.
18 * @param string $bundle
19 * The bundle name of the entity the field will be attached to.
20 * @param string $field_name
21 * The name of the field; if it already exists, a new instance of the existing
22 * field will be created.
23 * @param string $field_label
24 * The label of the field.
25 * @param string $target_entity_type
26 * The type of the referenced entity.
27 * @param string $selection_handler
28 * The selection handler used by this field.
29 * @param array $selection_handler_settings
30 * An array of settings supported by the selection handler specified above.
31 * (e.g. 'target_bundles', 'sort', 'auto_create', etc).
32 * @param int $cardinality
33 * The cardinality of the field.
35 * @see \Drupal\Core\Entity\Plugin\EntityReferenceSelection\SelectionBase::buildConfigurationForm()
37 protected function createEntityReferenceField($entity_type, $bundle, $field_name, $field_label, $target_entity_type, $selection_handler = 'default', $selection_handler_settings = [], $cardinality = 1) {
38 // Look for or add the specified field to the requested entity bundle.
39 if (!FieldStorageConfig::loadByName($entity_type, $field_name)) {
40 FieldStorageConfig::create([
41 'field_name' => $field_name,
42 'type' => 'entity_reference',
43 'entity_type' => $entity_type,
44 'cardinality' => $cardinality,
46 'target_type' => $target_entity_type,
50 if (!FieldConfig::loadByName($entity_type, $bundle, $field_name)) {
52 'field_name' => $field_name,
53 'entity_type' => $entity_type,
55 'label' => $field_label,
57 'handler' => $selection_handler,
58 'handler_settings' => $selection_handler_settings,