Drupal - Get all fields defined in a bundle

EntityManager is deprecated moving forward. The following can be used instead:

$entityFieldManager = \Drupal::service('entity_field.manager');
$fields = $entityFieldManager->getFieldDefinitions($entity_type, $bundle);

I achieved it using getFieldDefinitions() defined in Class EntityManager. So in order get all fields used in a particular bundle, Here is a way:

$bundle_fields = \Drupal::entityManager()->getFieldDefinitions('node', 'article');

Though the above $bundle_fields also contains nid, uuid, revisions, langcode, etc as fields. So to get an accurate output I did something like this:

  $entity_type_id = 'node';
  $bundle = 'article';
  foreach (\Drupal::entityManager()->getFieldDefinitions($entity_type_id, $bundle) as $field_name => $field_definition) {
    if (!empty($field_definition->getTargetBundle())) {
      $bundleFields[$entity_type_id][$field_name]['type'] = $field_definition->getType();
      $bundleFields[$entity_type_id][$field_name]['label'] = $field_definition->getLabel();
    }
  }

EntityManager is deprecated and I used the next code. I added to Controller class:

/**
 * The entity field manager.
 *
 * @var \Drupal\Core\Entity\EntityFieldManager
 */
protected $entityFieldManager;
    
/**
 * Constructor.
 *
 * @param \Drupal\Core\Entity\EntityFieldManager $entity_field_manager
 *   The entity field manager.
 */
public function __construct(EntityFieldManager $entity_field_manager) {
  $this->entityFieldManager = $entity_field_manager;
}
    
/**
 * {@inheritdoc}
 */
public static function create(ContainerInterface $container) {
  return new static(
    $container->get('entity_field.manager')
  );
}

// Here some your functions

/**
 * Build table rows.
 */
protected function buildRows() {
  $entity_type_id = 'node';
  $bundle = 'article';
  $fields = $this->entityFieldManager->getFieldDefinitions($entity_type_id, $bundle);
  
  foreach ($fields as $field_name => $field_definition) {
    if (!empty($field_definition->getTargetBundle())) {               
      $listFields[$field_name]['type'] = $field_definition->getType();
      $listFields[$field_name]['label'] = $field_definition->getLabel();                  
    }
  }

  $rows = [];
  foreach ($listFields as $field_name => $info) {
    $rows[] = $this->buildRow($info, $field_name);
  }

  return $rows;
}

https://www.drupal.org/node/2549139 is what helped me

Tags:

Entities