function bat_event_series_type_add_target_entity_field in Booking and Availability Management Tools for Drupal 8
Create fields of type 'Entity Reference' to reference the target entity.
We need to create a field/instance for each possible target entity type.
1 call to bat_event_series_type_add_target_entity_field()
- EventSeriesType::save in modules/
bat_event_series/ src/ Entity/ EventSeriesType.php - Saves an entity permanently.
File
- modules/
bat_event_series/ bat_event_series.module, line 130
Code
function bat_event_series_type_add_target_entity_field($bundle, $target_entity_type) {
$entity_info = \Drupal::entityTypeManager()
->getDefinition($target_entity_type);
$field_name = 'event_' . $target_entity_type . '_reference';
$field_storage = FieldStorageConfig::loadByName('bat_event_series', $field_name);
$field = FieldConfig::loadByName('bat_event_series', $bundle, $field_name);
if (empty($field_storage)) {
$field_storage = FieldStorageConfig::create([
'field_name' => $field_name,
'entity_type' => 'bat_event_series',
'type' => 'entity_reference',
'cardinality' => 1,
'locked' => 1,
'settings' => [
'target_type' => $target_entity_type,
],
]);
$field_storage
->save();
}
if (empty($field)) {
$field = FieldConfig::create([
'field_storage' => $field_storage,
'entity_type' => 'bat_event_series',
'label' => $entity_info
->getLabel()
->__toString(),
'bundle' => $bundle,
'required' => TRUE,
'settings' => [
'handler' => 'default',
'handler_settings' => [],
],
]);
$field
->save();
$form_display = \Drupal::entityTypeManager()
->getStorage('entity_form_display')
->load('bat_event_series.' . $bundle . '.default');
if (!$form_display) {
$form_display = EntityFormDisplay::create([
'targetEntityType' => 'bat_event_series',
'bundle' => $bundle,
'mode' => 'default',
'status' => TRUE,
]);
}
$form_display
->setComponent($field_name, [
'type' => 'entity_reference_autocomplete',
'weight' => 3,
]);
$form_display
->save();
}
}