public static function EntityReferenceRevisionsItem::generateSampleValue in Entity Reference Revisions 8
Generates placeholder field values.
Useful when populating site with placeholder content during site building or profiling.
Parameters
\Drupal\Core\Field\FieldDefinitionInterface $field_definition: The field definition.
Return value
array An associative array of values.
Overrides EntityReferenceItem::generateSampleValue
File
- src/
Plugin/ Field/ FieldType/ EntityReferenceRevisionsItem.php, line 471
Class
- EntityReferenceRevisionsItem
- Defines the 'entity_reference_revisions' entity field type.
Namespace
Drupal\entity_reference_revisions\Plugin\Field\FieldTypeCode
public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
$selection_manager = \Drupal::service('plugin.manager.entity_reference_selection');
$entity_manager = \Drupal::entityTypeManager();
// ERR field values are never cross referenced so we need to generate new
// target entities. First, find the target entity type.
$target_type_id = $field_definition
->getFieldStorageDefinition()
->getSetting('target_type');
$target_type = $entity_manager
->getDefinition($target_type_id);
$handler_settings = $field_definition
->getSetting('handler_settings');
// Determine referenceable bundles.
$bundle_manager = \Drupal::service('entity_type.bundle.info');
if (isset($handler_settings['target_bundles']) && is_array($handler_settings['target_bundles'])) {
if (empty($handler_settings['negate'])) {
$bundles = $handler_settings['target_bundles'];
}
else {
$bundles = array_filter($bundle_manager
->getBundleInfo($target_type_id), function ($bundle) use ($handler_settings) {
return !in_array($bundle, $handler_settings['target_bundles'], TRUE);
});
}
}
else {
$bundles = $bundle_manager
->getBundleInfo($target_type_id);
}
$bundle = array_rand($bundles);
$label = NULL;
if ($label_key = $target_type
->getKey('label')) {
$random = new Random();
// @TODO set the length somehow less arbitrary.
$label = $random
->word(mt_rand(1, 10));
}
// Create entity stub.
$entity = $selection_manager
->getSelectionHandler($field_definition)
->createNewEntity($target_type_id, $bundle, $label, 0);
// Populate entity values and save.
$instances = $entity_manager
->getStorage('field_config')
->loadByProperties([
'entity_type' => $target_type_id,
'bundle' => $bundle,
]);
foreach ($instances as $instance) {
$field_storage = $instance
->getFieldStorageDefinition();
$max = $cardinality = $field_storage
->getCardinality();
if ($cardinality == FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED) {
// Just an arbitrary number for 'unlimited'
$max = rand(1, 5);
}
$field_name = $field_storage
->getName();
$entity->{$field_name}
->generateSampleItems($max);
}
$entity
->save();
return [
'target_id' => $entity
->id(),
'target_revision_id' => $entity
->getRevisionId(),
];
}