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

$form['upload_documents'] = array(
  '#type' => 'media',
  '#tree' => TRUE, 
  '#title' => t('Upload your documents'),
  '#default_value' => array('fid' => $default_value),
  '#media_options' => array(
    'global' => array(
      'file_extensions' => 'pdf doc docx',
      'types' => array('document'),
    ),
  ),
  '#attached' => array(), 
  '#extended' => TRUE, 
  '#required' => TRUE, 
);
  • 1
    Your code misses one closing bracket. – leymannx Aug 10 at 9:59
  • Have you tried this one: drupal.org/project/media/issues/1510012#comment-9773961 – leymannx Aug 10 at 10:03
  • Yes I tried that, which is for Drupal 7 , and it is not working – Ashi Aug 10 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 at 12:44
  • Media isn't a form element. – Kevin Aug 10 at 12:55
up vote 0 down vote accepted

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

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

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

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.