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()->getStorage('taxonomy_term')->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()->getStorage('media')->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(&$form, FormStateInterface $form_state, $form_id) {
if ($form_id == 'node_article_form') {
// This works
$term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load(13);
$form['field_category']['widget'][0]['target_id']['#default_value'] = $term;
// This doesn't work
$media = \Drupal::entityTypeManager()->getStorage('media')->load(38);
$form['field_image']['widget'][0]['target_id']['#default_value'] = $media;
}
}