0

I have a content type which contains school information. School name and school id are two fields in the content type. I have the school ID and I am able to retrieve the node. How do I get the school name? Below is how I retrieve the particular school node. I used the getValue() to retrieve the school name however, I get an empty array as a response for that. I am able to see the school name if I var_dump the school node.

$schoolNode = \Drupal::entityTypeManager()
      ->getStorage('node')
      ->loadByProperties(['field_school_id' => $item['schoolId']]);
$schoolNode->field_school_name->getValue()
0

If you want to use node object from entityTypeManager, you need to get current value from the array after loading like below:

$schoolNode = \Drupal::entityTypeManager()
      ->getStorage('node')
      ->loadByProperties(['field_school_id' => $item['schoolId']]);
$node_load = current($schoolNode);
$schoolname = $node_load->field_school_name->getValue();

This is only for a single node. If you have multiple nodes, foreach node as

foreach(schoolNode as $node){
  $schoolname = $node->field_school_name->getValue();
}

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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