1

I have created class content type and set Allowed number of values to unlimited" to "Division" field Now I want to get "Division" field values programmatically in node presave hook I'm using below code.

function example_node_presave(Drupal\Core\Entity\EntityInterface $node){
  if($node->bundle() == "class") {
     $getDivison = $node->get('field_class_division')->target_id;
   }
}

If i print $getDivison then I get 739 only. Division field

2 Answers 2

4

You can loop over a field object and access each item separately, that's often more convenient than going through getValue():

function example_node_presave(Drupal\Core\Entity\EntityInterface $node){

  if($node->bundle() == "class") {
     foreach ($node->get('field_class_division') as $item) {
       echo $item->target_id;
     }
   }
}

And to access a specific delta (that's what the index in a multi-value field is called in the Field API), you can access it like an array as well, but you need to make sure that the deltas exist:

echo $node->get('field_class_division')[1]->target_id

See https://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet for a very useful cheat sheet on how to work with the Entity Field API.

1
  • Entity Cheatsheet link is dead and redirects to a different domain. Mar 25 at 15:32
2

You can use:

function example_node_presave(Drupal\Core\Entity\EntityInterface $node){

  if($node->bundle() == "class") {
     // Use getValue() to get multiple values in array.
     $getDivison = $node->get('field_class_division')->getValue();
   }
}
1
  • yeah, it's the perfect answer, you just need to run a foreach loop the $getDivison variable, you could easily fetch the individual value.
    – sekharctc
    Mar 22, 2021 at 11:09

Your Answer

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

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