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?
This does not work, nor do $pub_company or $newCompanyNode->id() by themselves.
$user->set("field_company", $pub_company . ' ' . $newCompanyNode->id());
$pub_company is the company name
$newCompany is the full newly created node
$newCompanyNode->id() holds the newly created 'company' node id
$user = User::create();
$userEmail = $form_state->getValue('user_email');
// Generate Password
$password = user_password();
// Save User
$user->setPassword($password);
$user->enforceIsNew();
$user->setEmail($userEmail);
$user->setUsername($userEmail);
$user->set("field_firstname", $form_state->getValue('user_firstname'));
$user->set("field_lastname", $form_state->getValue('user_lastname'));
$user->set("field_company", $pub_company . ' ' . $newCompanyNode->id());
$user->activate();
$user->save();
