3

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.

7

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]);
}
  • 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 Apr 25 '18 at 6:15
2

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.
}

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.