3

I tried something below, which is not working in drupal 8.

$form['upload_documents'] = [
  '#type'          => 'media',
  '#tree'          => TRUE,
  '#title'         => t('Upload your documents'),
  '#default_value' => ['fid' => $default_value],
  '#media_options' => [
    'global' => [
      'file_extensions' => 'pdf doc docx',
      'types'           => ['document'],
    ],
  ],
  '#attached'      => [],
  '#extended'      => TRUE,
  '#required'      => TRUE,
];
6
  • Have you tried this one: drupal.org/project/media/issues/1510012#comment-9773961
    – leymannx
    Aug 10, 2018 at 10:03
  • Yes I tried that, which is for Drupal 7 , and it is not working
    – Ashi
    Aug 10, 2018 at 12:08
  • Scanning through the core code it seems a little bit that '#type' => 'media' form elements are not there yet in D8.
    – leymannx
    Aug 10, 2018 at 12:44
  • Media isn't a form element.
    – Kevin
    Aug 10, 2018 at 12:55
  • @Kevin - at least in D7 contrib it seemed to provide a form element.
    – leymannx
    Aug 10, 2018 at 15:01

3 Answers 3

4

I found the answer to create the media autocomplete field like below.

// $id is your media ID.
$media = \Drupal\media_entity\Entity\Media::load($id); 

$form['upload_doc'] = [
  '#type'          => 'entity_autocomplete',
  '#target_type'   => 'media',
  '#default_value' => $media,
];
0
3

There is also module (Media Library Form API Element) that supports this kind of implementation:

$form['image'] = [
  '#type' => 'media_library',
  '#allowed_bundles' => ['image'],
  '#title' => t('Upload your image'),
  '#default_value' => NULL|1,
  '#description' => t('Upload or select your profile image.'),
];
2
  • Thank you for the suggestion. This does work. It's odd that Media is a part of core and yet we have to use a contrib module for this, but that's Drupal. Mar 25, 2020 at 19:11
  • So, how do you render it back out? I have a page preprocess function and I need to pass along the media to the template.
    – shelane
    Aug 31, 2021 at 21:00
1

In Drupal 8, you can use the entity browser.

A simple example of available options:

$form['upload_documents'] = array(
  '#type' => 'entity_browser',
  '#entity_browser' => $entity_browser_id, // e.g. 'document_browser'
  '#cardinality' => $cardinality, // e.g. 1
  '#selection_mode' => $selection_mode, //e.g. 'selection_append'
  '#default_value' => $entities,
  '#custom_hidden_id' => $hidden_id,

);

In the form submit, it leaves the entity IDs of the selected entities in a hidden field.

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.