0

I would like to create a node programatically and one field field_supervisors has an entity reference field for the node type People.

In order to set the correct entity reference information I need to set:

[ ["target_id" => 1], ["target_id" => 2], // etc.. ] 

How can I get the individual id of the entity reference from the field_supervisors. Do I really need to look up the node People before to get the id like $node->id() or is there a way to return something like this pseudo code:

Field->field_supervisors->allReferencedEntitiyOptions which will return all People that are available ?

Thanks

3
  • 1
    Does this answer your question? How do I access a field value for an entity (e.g. node) object? Commented Nov 9, 2021 at 15:32
  • If you want to get the full referenced objects and not just the IDs use api.drupal.org/api/drupal/… Commented Nov 9, 2021 at 15:34
  • @Hudri thanks for your answer. I don't have a node as I'm creating one. So I need to create the node first and then set the reference entities field? Commented Nov 9, 2021 at 16:08

1 Answer 1

1

Do I really need to look up the node People before to get the id

Yes, there's no auto-magic method for that. It's not a lot of code though. Without DI, for example:

$ids = \Drupal::entityQuery('node')->condition('type', 'person')->execute(); 
2
  • thanks, I was hoping there is a way to return all entity reference options a certain field has, but that will do the job. Commented Nov 9, 2021 at 16:11
  • You could pull the ER field apart and I'm sure find the code to do that based on the field settings, but if you already know the conditions you want it seems like a waste of effort Commented Nov 9, 2021 at 16:12

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.