6

How can I check if a bundle has a field? I know I can use $entity->hasField() if I have a specific entity (as is defined in this post), but how can I get this info with just the entity_type and bundle info?

I'm assuming I could just create an entity of the type and bundle (and never save it), and check against that, but that seems gross.

2 Answers 2

9

Woops, this is closely related to Get all fields defined in a bundle, but since that gets all fields, I'll post this.

Use the EntityFieldManager (entity_field.manager) service, specifically the getFieldDefinitions method, to get all field definitions, and then check for your specific field.

function doesBundleHaveField($entity_type = 'node', $bundle = 'page', $field_name = 'field_paragraphs') {
  $all_bundle_fields = \Drupal::service('entity_field.manager')->getFieldDefinitions($entity_type, $bundle);
  return isset($all_bundle_fields[$field_name]);
}
1
  • 4
    an isset($all_bundle_fields[$field_name]) is enough, array_key_exists() is only necessary if your array key might be NULL and you still want to return TRUE. Not the case here
    – Berdir
    Commented Apr 25, 2018 at 6:15
4

You can use static method loadByName from FieldStorageConfig, which will return field config entity if one exists for the provided field name, otherwise NULL. Then get the attached bundles and filter by your correspondent bundle:

use Drupal\field\Entity\FieldStorageConfig;
$field_storage = FieldStorageConfig::loadByName('node', 'field_foo');
if (!empty($field_storage) && in_array('page', $field_storage->getBundles())) {
  // TODO: Implement this.
}
1
  • I believe this answer is preferred since not all entity types support the getFieldDefinitions method. I was trying this on commerce_product_types and got the error: "Getting the base fields is not supported for entity type Product type." Commented Feb 1, 2022 at 17:41

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.