In Drupal 7, to get all fields used in a content type, I use the following code.
$fields = field_info_instances('node', 'article');
What is the equivalent for Drupal 8?
Drupal Answers is a question and answer site for Drupal developers and administrators. It only takes a minute to sign up.
Sign up to join this communityEntityManager is deprecated moving forward. The following can be used instead:
$entityFieldManager = \Drupal::service('entity_field.manager');
$fields = $entityFieldManager->getFieldDefinitions($entity_type, $bundle);
Whereas $entity_type
can be 'node'
and $bundle
can be 'article'
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();
}
}
nid, uuid, revisions, langcode, etc
) you can do if($field->getFieldStorageDefinition()->isBaseField() == FALSE)
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
$fields = $entity->getFieldDefinitions();
will do it. I'm not sure what the equivalent offield_info_instances()
is,FieldStorageConfig
doesn't appear to have one\Drupal::entityManager()->getFieldDefinitions('node', 'article')
did the job clive :)