title: Drupal 8 - How to programmatically create a node entity reference variable?
body: <p>How do I create a node entity reference programmaticallly in Drupal 8?
  I have a custom form that creates a 'company' node and then creates a user account, the user account has a field 'field_company' that is an Entity reference linking to the node 'company'. So how do I save my newly created node reference in my new users 'field_company' field?</p>
  
  <p><a href="https://i.stack.imgur.com/l3wEw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/l3wEw.png" alt="field_company entity reference"></a></p>
  
  <p><a href="http://pastebin.com/iX7yAaeY" rel="nofollow noreferrer">http://pastebin.com/iX7yAaeY</a></p>
  
  <p>This does not work, nor do $pub_company or $newCompanyNode->id() by themselves.</p>
  
  <pre><code>$user-&gt;set("field_company", $pub_company . ' ' . $newCompanyNode-&gt;id());
  </code></pre>
  
  <p>$pub_company is the company name</p>
  
  <p>$newCompany is the full newly created node</p>
  
  <p>$newCompanyNode->id() holds the newly created 'company' node id</p>
  
  <pre><code>$user = User::create();
  $userEmail = $form_state-&gt;getValue('user_email');
  
  // Generate Password
  $password = user_password();
  
  // Save User
  $user-&gt;setPassword($password);
  $user-&gt;enforceIsNew();
  $user-&gt;setEmail($userEmail);
  $user-&gt;setUsername($userEmail);
  $user-&gt;set("field_firstname", $form_state-&gt;getValue('user_firstname'));
  $user-&gt;set("field_lastname", $form_state-&gt;getValue('user_lastname'));
  $user-&gt;set("field_company", $pub_company . ' ' . $newCompanyNode-&gt;id());
  $user-&gt;activate();
  $user-&gt;save();
  </code></pre>