1<?php 2 3namespace Drupal\Tests\file\Functional; 4 5use Drupal\field\Entity\FieldStorageConfig; 6use Drupal\field\Entity\FieldConfig; 7 8/** 9 * Provides methods for creating file fields. 10 */ 11trait FileFieldCreationTrait { 12 13 /** 14 * Creates a new file field. 15 * 16 * @param string $name 17 * The name of the new field (all lowercase), exclude the "field_" prefix. 18 * @param string $entity_type 19 * The 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. 28 * 29 * @return \Drupal\field\FieldStorageConfigInterface 30 * The file field. 31 */ 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, 36 'type' => 'file', 37 'settings' => $storage_settings, 38 'cardinality' => !empty($storage_settings['cardinality']) ? $storage_settings['cardinality'] : 1, 39 ]); 40 $field_storage->save(); 41 42 $this->attachFileField($name, $entity_type, $bundle, $field_settings, $widget_settings); 43 return $field_storage; 44 } 45 46 /** 47 * Attaches a file field to an entity. 48 * 49 * @param string $name 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. 59 */ 60 public function attachFileField($name, $entity_type, $bundle, $field_settings = [], $widget_settings = []) { 61 $field = [ 62 'field_name' => $name, 63 'label' => $name, 64 'entity_type' => $entity_type, 65 'bundle' => $bundle, 66 'required' => !empty($field_settings['required']), 67 'settings' => $field_settings, 68 ]; 69 FieldConfig::create($field)->save(); 70 71 \Drupal::service('entity_display.repository')->getFormDisplay($entity_type, $bundle) 72 ->setComponent($name, [ 73 'type' => 'file_generic', 74 'settings' => $widget_settings, 75 ]) 76 ->save(); 77 // Assign display settings. 78 \Drupal::service('entity_display.repository')->getViewDisplay($entity_type, $bundle) 79 ->setComponent($name, [ 80 'label' => 'hidden', 81 'type' => 'file_default', 82 ]) 83 ->save(); 84 } 85 86} 87