Pre-populate an entity reference field (media image) when creating a node I am trying to open a node creation form (for example, /node/add/article) and to have an Entity Reference field pre-populated.

My field (field_image) is an Entity Reference to a Media of type Image and the form uses the Media Library widget.

I essentially tried doing that by implementing hook_form_alter in a custom module but nothing that I have tried worked. I saw solutions like this one. It works with other field types that I have tried. For example:

// Pre-populate Entity Reference field to taxonomy term

$term = \Drupal::entityTypeManager()-&gt;getStorage('taxonomy_term')-&gt;load(13);
$form['field_category']['widget'][0]['target_id']['#default_value'] = $term;


The above works just fine. But the below doesn't.

// Pre-populate Entity Reference field to Media Image

$media = \Drupal::entityTypeManager()-&gt;getStorage('media')-&gt;load(38);
$form['field_image']['widget'][0]['target_id']['#default_value'] = $media;


I also tried by providing just the media id instead of the entity but it didn't work.

I have tried the Prepopulate module too but couldn't get it to work either although it works with all other field types that I have tried.

Anyone knows if this is feasible and how?

Edit: I should perhaps mention that I am not looking for a solution on how to set a default value for that field. The referenced entity must be set dynamically

For reference, here is my complete code:

/**
 * Implements hook_form_alter().
 */
function siteconfig_form_alter(&amp;$form, FormStateInterface $form_state, $form_id) {

  if ($form_id == 'node_article_form') {

    // This works
    $term = \Drupal::entityTypeManager()-&gt;getStorage('taxonomy_term')-&gt;load(13);
    $form['field_category']['widget'][0]['target_id']['#default_value'] = $term;

    // This doesn't work
    $media = \Drupal::entityTypeManager()-&gt;getStorage('media')-&gt;load(38);
    $form['field_image']['widget'][0]['target_id']['#default_value'] = $media;
  }
}
It's much easier to prepopulate field values on entity level rather than on form level:

/**
 * Implements hook_ENTITY_TYPE_create() for 'node'.
 */
function mymodule_node_create(\Drupal\node\NodeInterface $node) {

  if ($node-&gt;getType() == 'my_content_type') {
    $media = \Drupal::entityTypeManager()-&gt;getStorage('media')-&gt;load(38);
    $node-&gt;field_image[] = $media;
  }

}