4

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.

  • Check the existence of field or empty value of field? – Jimmy Ko Aug 2 '16 at 9:02
8

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
    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 Aug 2 '16 at 15:25
0

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
    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 Apr 8 at 9:29

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.