0

i want to display a taget_id values for user in node's field but i can't print them , this is what I have done in the hook :

 $node = \Drupal::routeMatch()->getParameter('node');
  if ($node && $node->bundle() == 'MynodeType') {
    $members = $node->field_members->getValue();
    $members_ids = [];
    $current_user = \Drupal::currentUser();
    $user_id = \Drupal\user\Entity\User::load($current_user->id());

    foreach ($members as $member){
      $members_ids[] = $member['target_id'];
      echo $members_ids; // why this is not like (1,8,....)?
    }
4
  • Welcome to Drupal Stackoverflow. Are you using PHPStorm like editor with xDebug mode enabled? It helps a lot. By putting breakpoint & see what result you are getting. . Please try $member_ids = array_map(function ($member) { return $member['target_id']; }, $node->get('members')->getValue());
    – Mighty
    Commented Mar 6, 2020 at 8:48
  • or $members_ids = array_column($node->field_members->getValue(), 'target_id'); see drupal.stackexchange.com/a/207715/47547
    – 4uk4
    Commented Mar 6, 2020 at 10:05
  • @4k4 thank you so much
    – coding mv
    Commented Mar 6, 2020 at 11:09
  • @Julia thank you so much
    – coding mv
    Commented Mar 6, 2020 at 11:09

1 Answer 1

1

Looks like this one has to be solved this way

  $members = $node->field_members;
  foreach ($members as $member) {
      $members_ids[] = $member->getValue()['target_id'];
  }
2
  • Error : Call to undefined method Drupal\Core\Field\EntityReferenceFieldItemList::getTarget()
    – coding mv
    Commented Mar 6, 2020 at 10:15
  • @drupalcoding updated answer.
    – No Sssweat
    Commented Mar 6, 2020 at 10:47

Your Answer

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

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