Reusable Images and Files with Media Bundles in Drupal

| Drupal
Reusable Images and Files with Media Bundles in Drupal

This week, an OSTraining member asked us how they could re-use media in Drupal 8.

Using the Drupal media modules, I will explain how you can upload PDFs, images and other media that can be re-used on your site.

In this tutorial, we're going to rely on the Media module. 

Step #1. Install the modules

In order to get started, you must download, install and enable the following modules: 

Step #2. Create a media bundle

  • Go to Structure > Media Bundles > Add Media Bundle.
  • Give the bundle a name.
  • Leave the "Type provider" as "Generic media". This will allow us to work with any file type we choose.

1

Now we have created the bundle we need to add a field to it.

  • Edit the new bundle you created.
  • Go to Manage Fields > add field
  • Under reference, choose "File". 
  • Enter a label for your field and click "Save and continue"

2

  • Make sure "Enable Display field" is checked.
  • Make sure "Files displayed by default" is checked.
  • Set "Allowed number of values" to "Unlimited".

3

Now we can define which file types we want to be usable with this field. In the example, below the default is "text" and I have added PDF and JPG. 

4

Step #3. Attach the media bundle to a content type

We have a media bundle, we need to attach it to a content type. For this tutorial, I will add the bundle to the Basic page content type.

  • Go to Structure > Content types > Basic page > Manage fields
  • Click "Add field"
  • Under "Reference" choose "Other..."
  • Enter a label for your field and click "Save and continue"

5

  • On the next page, under "Type of item to reference", choose "Media"
  • Set "Allowed number of values" to "Unlimited".

8

  • Under "Bundles", select the media bundle that you created.

9

Step #4. Configure the media display

Now we need to configure the form display for the media.

  • Go to the "Manage Display" for Basic page.
  • Change the widget to "Inline entity form - Complex".
  • Select "Allow users to add new media entities".
  • Set "Entity browser" to "Test entity browser for files" select update.

12

Step #5. Create content

  • Go to Content > Add content > Basic page.
  • You can now see your new media field. You can choose "Add media" to upload new media or click "Select entities" to select existing media.

13

  • If you choose "Select entities", you will be able to browse through previously uploaded files.
  • Save and publish your content. Your chosen media will be attached to your content!

14


About the author

Daniel is a web designer from UK, who's a friendly and helpful part of the support team here at OSTraining.