Version 1
[yaffs-website] / web / core / modules / field / src / Tests / EntityReference / EntityReferenceTestTrait.php
1 <?php
2
3 namespace Drupal\field\Tests\EntityReference;
4
5 use Drupal\field\Entity\FieldConfig;
6 use Drupal\field\Entity\FieldStorageConfig;
7
8 /**
9  * Provides common functionality for the EntityReference test classes.
10  */
11 trait EntityReferenceTestTrait {
12
13   /**
14    * Creates a field of an entity reference field storage on the specified bundle.
15    *
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.
34    *
35    * @see \Drupal\Core\Entity\Plugin\EntityReferenceSelection\SelectionBase::buildConfigurationForm()
36    */
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,
45         'settings' => [
46           'target_type' => $target_entity_type,
47         ],
48       ])->save();
49     }
50     if (!FieldConfig::loadByName($entity_type, $bundle, $field_name)) {
51       FieldConfig::create([
52         'field_name' => $field_name,
53         'entity_type' => $entity_type,
54         'bundle' => $bundle,
55         'label' => $field_label,
56         'settings' => [
57           'handler' => $selection_handler,
58           'handler_settings' => $selection_handler_settings,
59         ],
60       ])->save();
61     }
62   }
63
64 }