The default widget used for the entity reference fields (with the exception of entity reference fields for taxonomy tags) is implemented by the EntityReferenceAutocompleteWidget
class which, in its formElement()
implementation, returns the following form element.
$element += [
'#type' => 'entity_autocomplete',
'#target_type' => $this->getFieldSetting('target_type'),
'#selection_handler' => $this->getFieldSetting('handler'),
'#selection_settings' => $selection_settings,
// Entity reference field items are handling validation themselves via
// the 'ValidReference' constraint.
'#validate_reference' => FALSE,
'#maxlength' => 1024,
'#default_value' => isset($referenced_entities[$delta]) ? $referenced_entities[$delta] : NULL,
'#size' => $this->getSetting('size'),
'#placeholder' => $this->getSetting('placeholder'),
];
Instead of form['field_name']['widget'][0]['target_id']['#default_value']
, the code should set form['field_name']['widget'][0]['#default_value']
.
form['field_name']['widget'][0]['#default_value'] = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
As side note, to alter the form element(s) returned from a field widget, Drupal make hook_field_widget_complete_form_alter()
(and hook_field_widget_complete_WIDGET_TYPE_form_alter()
) available for this purpose. It has access of the following information.
- The widget plugin instance (
$context['widget']
), which allows to access the widget ID (for example, entity_reference_autocomplete, entity_reference_autocomplete_tags) with $context['widget']->getPluginId()
- The field values (
$context['items']
), which allows to get the target type of the reference field ($context['items']->getFieldDefinition()->getFieldStorageDefinition()->getSetting('target_type')
)or the field type ($context['items']->getFieldDefinition()->getType()
), for example
When possible, it should preferable to use this hook for field widgets, instead of hook_form_alter()
.
media_field_widget_complete_form_alter()
is the implementation of that hook done by the Media module.