I have a node called project which contains field building as a referenced item, I used the the hook on building node insert and, having this building id I need to get project id which this building is assigned to. How can I get the project id (the building's parent).

I have found the hostEntity() used in drupal 7 (As Far As I Know), but it seemed this is not applicable anymore in Drupal 8.

Any help?


I think hostEntity was specific to FieldCollection in D7 and not to entity reference. Field Collection is tied to one specific host Entity. With entity reference there is no specific host entity, you can possibly reference one entity in multiple host entities.

You can use Entity Query to get all (host) nodes that reference a specific entity within a specific field.

In a very basic form this would return all "Project" nodes that reference a specific building by field building:

$query = \Drupal::entityQuery('node')
  ->condition('field_building', $building_nid);
$nids = $query->execute();

$building_nid is the node id of the building. This will return "project" node ids in your case.

  • Perfect @stefan-korn, that solved my problem. – Naser Nikzad Sep 8 '19 at 7:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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