Allow setting a default target type

Created on 31 March 2023, over 1 year ago

Problem/Motivation

It would be nice to be able to set a default target type. Currently the widget sets the default to the first entity type which would be the first alphabetically.

Proposed resolution

Add config for default target type to widget settings.

Remaining tasks

Agree
Implement and test

User interface changes

Add new default target type setting to widget settings UI

API changes

None

Data model changes

Updated config schema.

Feature request
Status

Active

Version

3.0

Component

Code

Created by

🇦🇺Australia acbramley

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

  • Issue created by @acbramley
  • 🇦🇺Australia acbramley

    Currently it's possible to achieve this with some somewhat hacky alter code

     function my_module_field_widget_single_element_dynamic_entity_reference_default_form_alter(array &$element, FormStateInterface $formState, array $context): void {
        $items = $context['items'] ?? NULL;
        if (!$items instanceof DynamicEntityReferenceFieldItemList) {
          return;
        }
    
        // If the element already has an entity, bail.
        if (!empty($element['target_id']['#default_value'])) {
          return;
        }
    
        // Default to node.
        $targetType = 'node';
        $fieldSettings = $items->getFieldDefinition()->getSettings();
        $element['target_type']['#default_value'] = $targetType;
        $element['target_id']['#target_type'] = $targetType;
        $element['target_id']['#selection_handler'] = $fieldSettings[$targetType]['handler'];
      }
    
Production build 0.71.5 2024