Set Default Value in entity reference field of content type Programmatically

In below example we are checking if reference field is empty or not then adding a default value to reference content type if there is no value 

use Drupal\Core\Form\FormStateInterface;

 

 

function custom_module_form_alter(&$form, FormStateInterface $form_state, $form_id) {

   if($form_id == 'node_basic_form'){

       $nid = 10;

       if(empty($form['field_reference_content']['widget'][0]['target_id']['#default_value'])){

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

       }

   }

}

 

 

If you want to add multiple values then you will have to use a loop and set values in that loop, one thing you will need to keep in mind that you will need to set a specific no. of entries possible in the field settings because unlimited fields only render 1 field so only one value will show up if you have set field storage to unlimited