file_bulkupload_translations-1.0.x-dev/tests/src/Traits/FileBulkuploadTranslationsCreationTrait.php
tests/src/Traits/FileBulkuploadTranslationsCreationTrait.php
<?php
declare(strict_types=1);
namespace Drupal\Tests\file_bulkupload_translations\Traits;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\field\Entity\FieldConfig;
use Drupal\language\Entity\ConfigurableLanguage;
/**
* Provides methods for creating file fields.
*/
trait FileBulkuploadTranslationsCreationTrait {
/**
* Creates a new file field.
*
* @param string $name
* The name of the new field (all lowercase). The Field UI 'field_' prefix
* is not added to the field name.
* @param string $entity_type
* The entity type.
* @param string $bundle
* The bundle that this field will be added to.
*
* @return \Drupal\field\FieldStorageConfigInterface
* The file field.
*/
protected function createFileBulkuploadTranslations($name, $entity_type, $bundle) {
$storage_settings = [
'display_field' => '1',
'display_default' => '1',
'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
];
$field_settings = [
'max_filesize' => '200k',
'file_extensions' => 'pdf',
];
$widget_settings = [];
$field_storage = FieldStorageConfig::create([
'entity_type' => $entity_type,
'field_name' => $name,
'type' => 'file_bulkupload_translations',
'settings' => $storage_settings,
'cardinality' => -1,
]);
$field_storage->save();
$this->attachFileField($name, $entity_type, $bundle, $field_settings, $widget_settings);
return $field_storage;
}
/**
* Attaches a file field to an entity.
*
* @param string $name
* The name of the new field (all lowercase). The Field UI 'field_' prefix
* is not added to the field name.
* @param string $entity_type
* The entity type this field will be added to.
* @param string $bundle
* The bundle this field will be added to.
* @param array $field_settings
* A list of field settings that will be added to the defaults.
* @param array $widget_settings
* A list of widget settings that will be added to the widget defaults.
*/
protected function attachFileField($name, $entity_type, $bundle, $field_settings = [], $widget_settings = []) {
$field = [
'field_name' => $name,
'label' => $name,
'entity_type' => $entity_type,
'bundle' => $bundle,
'required' => !empty($field_settings['required']),
'settings' => $field_settings,
];
FieldConfig::create($field)->save();
\Drupal::service('entity_display.repository')->getFormDisplay($entity_type, $bundle)
->setComponent($name, [
'type' => 'file_bulkupload_translations_widget',
'settings' => $widget_settings,
])
->save();
// Assign display settings.
\Drupal::service('entity_display.repository')->getViewDisplay($entity_type, $bundle)
->setComponent($name, [
'label' => 'hidden',
'type' => 'file_default',
])
->save();
}
}
