pluginreference-2.0.0/tests/src/Traits/PluginReferenceTrait.php
tests/src/Traits/PluginReferenceTrait.php
<?php
namespace Drupal\Tests\pluginreference\Traits;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
/**
* Methods to create a plugin reference field based on default settings.
*
* This trait is meant to be used only by test classes.
*/
trait PluginReferenceTrait {
/**
* Create a plugin reference field.
*
* @param string $entity_type
* The entity type to which we want to add the plugin reference.
* @param string $bundle
* The bundle to which we want to add the plugin reference.
* @param string $field_name
* The name we want to give to the field.
* @param string $field_label
* The label of the field.
* @param string $target_type
* The plugin types we want to reference.
* @param string $selection_handler
* The selection handler used by this field.
* @param array $selection_handler_settings
* An array of settings supported by the selection handler specified above.
* (e.g. 'sort', etc).
* @param int $cardinality
* The cardinality of the field.
*
* @throws \Drupal\Core\Entity\EntityStorageException
*/
public function createPluginReferenceField(string $entity_type, string $bundle, string $field_name, string $field_label, string $target_type, string $selection_handler = 'default', array $selection_handler_settings = [], int $cardinality = 1): void {
$field_storage = FieldStorageConfig::create([
'field_name' => $field_name,
'type' => 'plugin_reference',
'entity_type' => $entity_type,
'cardinality' => $cardinality,
'settings' => [
'target_type' => $target_type,
],
]);
$field_storage->save();
FieldConfig::create([
'field_storage' => $field_storage,
'bundle' => $bundle,
'label' => $field_label,
'settings' => [
'handler' => $selection_handler,
'handler_settings' => $selection_handler_settings,
],
])->save();
}
}
