Prefilling values is a common task. This snippet shows how to prefill a entity reference field. Trick is to load the full object and to use the field widget.

$nid = 528;
$form['field_contest']['widget'][0]['target_id']['#default_value'] = \Drupal\node\Entity\Node::load($nid);

 


Saved you some valuable time?

Donate and get more free time-saving code on this website in the future.