How to set default value for entity reference programmatically in a form in drupal

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?

Buy me a drink 🍺 to keep me motivated to create free content like this!