user6742604
user6742604

Reputation:

Drupal 8 - How to programmatically create a node entity reference variable?

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?

field_company entity reference

http://pastebin.com/iX7yAaeY

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();

Upvotes: 2

Views: 5576

Answers (1)

user6742604
user6742604

Reputation:

Found the solution here, although a bit different and thus confusing at first: https://drupal.stackexchange.com/questions/213379/programmatically-update-an-entity-reference-field

$user->field_company->entity = $newCompanyNode;

Upvotes: 3

Related Questions