Score:1

How do I set the default value for a user entity reference field in hook_form_alter()?

us flag
CKL

I tried the following code, but it doesn't work.

$form['field_name']['widget'][0]['target_id']['#default_value'] = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
Score:1
us flag

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.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.