3 namespace Drupal\Tests\file\Functional;
5 use Drupal\field\Entity\FieldStorageConfig;
6 use Drupal\field\Entity\FieldConfig;
9 * Provides methods for creating file fields.
11 trait FileFieldCreationTrait {
14 * Creates a new file field.
17 * The name of the new field (all lowercase), exclude the "field_" prefix.
18 * @param string $entity_type
20 * @param string $bundle
21 * The bundle that this field will be added to.
22 * @param array $storage_settings
23 * A list of field storage settings that will be added to the defaults.
24 * @param array $field_settings
25 * A list of instance settings that will be added to the instance defaults.
26 * @param array $widget_settings
27 * A list of widget settings that will be added to the widget defaults.
29 * @return \Drupal\field\FieldStorageConfigInterface
32 public function createFileField($name, $entity_type, $bundle, $storage_settings = [], $field_settings = [], $widget_settings = []) {
33 $field_storage = FieldStorageConfig::create([
34 'entity_type' => $entity_type,
35 'field_name' => $name,
37 'settings' => $storage_settings,
38 'cardinality' => !empty($storage_settings['cardinality']) ? $storage_settings['cardinality'] : 1,
40 $field_storage->save();
42 $this->attachFileField($name, $entity_type, $bundle, $field_settings, $widget_settings);
43 return $field_storage;
47 * Attaches a file field to an entity.
50 * The name of the new field (all lowercase), exclude the "field_" prefix.
51 * @param string $entity_type
52 * The entity type this field will be added to.
53 * @param string $bundle
54 * The bundle this field will be added to.
55 * @param array $field_settings
56 * A list of field settings that will be added to the defaults.
57 * @param array $widget_settings
58 * A list of widget settings that will be added to the widget defaults.
60 public function attachFileField($name, $entity_type, $bundle, $field_settings = [], $widget_settings = []) {
62 'field_name' => $name,
64 'entity_type' => $entity_type,
66 'required' => !empty($field_settings['required']),
67 'settings' => $field_settings,
69 FieldConfig::create($field)->save();
71 entity_get_form_display($entity_type, $bundle, 'default')
72 ->setComponent($name, [
73 'type' => 'file_generic',
74 'settings' => $widget_settings,
77 // Assign display settings.
78 entity_get_display($entity_type, $bundle, 'default')
79 ->setComponent($name, [
81 'type' => 'file_default',