7

I need a list of all content entities, to query them all and check if they have a specific field.

Couldn't find this in the API doku.

1
  • Check the existence of field or empty value of field?
    – Jimmy Ko
    Commented Aug 2, 2016 at 9:02

3 Answers 3

10

This is what you need:

use Drupal\Core\Entity\ContentEntityType;

$content_entity_types = [];
$entity_type_definations = \Drupal::entityTypeManager()->getDefinitions();
/* @var $definition EntityTypeInterface */
foreach ($entity_type_definations as $definition) {
  if ($definition instanceof ContentEntityType) {
    $content_entity_types[] = $definition;
  }
}

But a better approach would be to get the field first and then the bundles which has this field. For example, we are looking for the "field_image" in "node" typed entities:

   use Drupal\field\FieldStorageConfig;

   $field_image = FieldStorageConfig::load('node.field_image') 
   $bundles = $field_image->getBundles();
1
  • 1
    the id is just that, the id. $field_image = FieldStorageConfig::load('node.field_image') or the helper loadByName('node', 'field_image') are much easier to use.
    – Berdir
    Commented Aug 2, 2016 at 15:25
1

Builds a list of entity type labels suitable for a Form API options list

\Drupal::entityManager()->getEntityTypeLabels(TRUE);

Use in form API

$element['target_type'] = [
  '#type' => 'select',
  '#title' => t('Type of item to reference'),
  '#options' => \Drupal::entityManager()->getEntityTypeLabels(TRUE),
  '#default_value' => '',
  '#required' => TRUE,
];
1
  • 2
    Thank you for the answer. It may help to provide a non-deprecated answer, which is to use the EntityRepositoryInterface rather than the EntityManagerInterface method.
    – mradcliffe
    Commented Apr 8, 2019 at 9:29
1
\Drupal::service('entity_type.repository')->getEntityTypeLabels(TRUE)['Content'];

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.