Setting entity reference field value in Drupal 8 programatically I have this following code that creates a node in the page.

$data = array(
  'type' =&gt; 'post',
  'field_post' =&gt; [
      'value' =&gt; 'test',
      'format' =&gt; 'basic_html',
    ],
  'field_visibility' =&gt; 1, 
  'user_id' =&gt; $uid
);
$node = Drupal::entityManager()
  -&gt;getStorage('post')
  -&gt;create($data);
$node-&gt;save();


I have another field field_pattern that is an entity reference for another content type. How can I properly set it inside my code?

Since with creating the content from the site when dealing with Entity reference field selects autocomplete to Title, then I tried to test this but fails. Meaning no value is set to entity reference.

$title = $entity-&gt;label();
$data = array(
  'type' =&gt; 'post',
  'field_post' =&gt; [
      'value' =&gt; 'test',
      'format' =&gt; 'basic_html',
    ],
  'field_pattern' =&gt; $title, // this is the entity reference field
  'field_visibility' =&gt; 1, 
  'user_id' =&gt; $uid
);
$node = Drupal::entityManager()
  -&gt;getStorage('post')
  -&gt;create($data);
$node-&gt;save();
If you are creating a node with reference field, see below code:

 use \Drupal\node\Entity\Node;
 $node = Node::create([
   'type' =&gt; 'post',
   'field_post' =&gt; [
     'value' =&gt; 'test',
     'format' =&gt; 'basic_html',
   ],
   'field_pattern' =&gt; [
      'target_id' =&gt; $ID_REFERENCE_ENTITY, // Here just provide referenced entity id.
   ],
   'field_visibility' =&gt; 1, 
   'user_id' =&gt; $uid
 ]);
 $node-&gt;save();


If you are are not creating node then just replace your field_pattern like below:

'field_pattern' =&gt; [
   'target_id' =&gt; $ID_REFERENCE_ENTITY, // Here just provide referenced entity id.
],