1

It is kind of strange because my code creates the node with the referenced user uid in node_field_data, but when I open this node the user reference isn't working. Then I navigated the database and found that, when I update the user reference field in the interface, it is also written as a new registry in the table node__field_user, so I guess I should insert it there too.

But, I don't know how to do this with the API, and I think making it with a SQL query probably means security issues and is probably much more complicated than however it can be done with the API.

This is my code:

  $node = Node::create(['type' => 'nodetype']);
  $node->set('title', $username );
  $node->uid->entity = $userId;
  $node->enforceIsNew();
  $node->save();
1
  • 2
    Is this about the core base field for the node owner or a user reference field you have added to the content type?
    – 4uk4
    Commented Feb 21, 2020 at 8:42

1 Answer 1

1

Set owner $node->setOwnerId($uid);

Set field reference $node->field_user[] = $uid;

2
  • Thanks a lot! Worked perfectly, although I don't really know where is this field_user[] coming from.
    – Rajo
    Commented Feb 21, 2020 at 10:29
  • @Rajo – The question title states you want to set a reference field to a user.
    – leymannx
    Commented Feb 21, 2020 at 13:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.