Score:0

Get all entity reference options from a field name

in flag

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

ru flag
Does this answer your question? [How do I access a field value for an entity (e.g. node) object?](https://drupal.stackexchange.com/questions/144947/how-do-i-access-a-field-value-for-an-entity-e-g-node-object)
ru flag
If you want to get the full referenced objects and not just the IDs use https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21Entity.php/function/Entity%3A%3AreferencedEntities/8.2.x
in flag
@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?
Score:1
cn flag

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();
in flag
thanks, I was hoping there is a way to return all entity reference options a certain field has, but that will do the job.
cn flag
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
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.