What’s the correct way to get all of the key/values for a bundle on a media entity?

I am trying to create a media entity programmatically and I need to get all of the fields on the image bundle. I am not sure how to get the image bundle ID either.

In other words, I’d like the module I'm working on to be a bit more generic and reusable as I’ve seen the image bundle have different names depending on the installation.

Here’s what I have so far but the two main problems I see are that the image bundle ID can change and the field names on the bundle can be different.

   $entity = $this->createFile(
    // Save media entity
    $media = [
      'bundle' => 'image',
      'uid' => $this->currentUser->id(),
      'status' => 1,
      'image' => [
        'target_id' => $entity->id(),
        'alt' => t(basename($file[0]['filename'])),
        'title' => t(basename($file[0]['filename'])),
    $image = $this->entityTypeManager->getStorage('media')->create($media);

I'd like to be able to get the image bundle and dynamically figure out whichever field has the target_id and then assign the previously created file entity to that. I do not know how to get the image bundle schema, array signature, in order to traverse the key/values to find the target_id

1 Answer 1


You can traverse the field definitions of the media bundle image and look for a field with the type image:

$fields = \Drupal::service('entity_field.manager')->getFieldDefinitions('media', 'image');
foreach ($fields as $key => $field) {
  if ($field->getType() === 'image') {
    // found image field $key

To get all media bundles:

$bundles = \Drupal::service('entity_type.bundle.info')->getBundleInfo('media');

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.