1

I am creating a simple administration page that shows all content types and some details about each content type field.

  • I am getting the list of content types with node_type_get_types()
  • I am getting the list of fields with field_info_instances()

When the widget module is entityreference I'd like to display the target bundle(s) of that entity reference field.

foreach(node_type_get_types() as $value) {

  $fields = field_info_instances('node', $value->type);

  // Loop through fields
  foreach($fields as $field) {

    if ($field['widget']['module'] == 'entityreference') {

      // Get the target bundle(s) for this field
    }
  }
}

Thanks in advance for any help on that!

2 Answers 2

2

Drupal 8 version:

$bundles = \Drupal::entityManager()
->getAllBundleInfo()['node'];
 foreach ($bundles as $id => $value) {
 $node_fields = \Drupal::entityManager()
  ->getFieldDefinitions('node', $id);
   foreach ($node_fields as $field) {
      if ($field instanceof \Drupal\field\Entity\FieldConfig) {
        if ($field->getType() == 'entity_reference') {
          $target_bundle = $field->getSettings()['handler_settings']['target_bundles'];
          kint($target_bundle);
        }
      }
    }
  }

With $target_bundle, You can do something like this as well to filter out a specific bundle:

if ($target_bundle != null && key($target_bundle) == 'mybundle'){
  kint($field->id());
}
1

Nevermind. I found a solution. I can get them with field_info_field():

foreach(node_type_get_types() as $value) {

  $fields = field_info_instances('node', $value->type);

  // Loop through fields
  foreach($fields as $field) {

    if ($field['widget']['module'] == 'entityreference') {

      // Get the target bundle(s) for this field
      $field_info_field = field_info_field($field['field_name']);
      $target_bundles = $field_info_field['settings']['handler_settings']['target_bundles'];
    }
  }
}
2
  • Hey, would you mind to mark your answer as the accepted answer? This would help to connect the information together.
    – leymannx
    Oct 14, 2016 at 7:34
  • @leymannx done!
    – MrUpsidown
    Oct 17, 2016 at 8:05

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.