It seems this issue is being worked on at : #2568289: Not possible to reuse field formatters between entity_reference, file, and image fields
For now I've used the following code - included in the mytheme.theme file. (view mode custom_generic_file)
use Drupal\file\Plugin\Field\FieldType\FileItem;
/**
* Implements hook_preprocess_field().
*/
function mytheme_preprocess_field(&$variables, $hook) {
__mytheme_preprocess_field__generic_download_icons_view_mode($variables, $hook);
}
/**
* Ensure generic icon view mode for image media entities.
*
* Image field type doesn't have a generic file formatter.
*
* Called by hook_preprocess_field().
*
* @see Drupal\file\Plugin\Field\FieldFormatter\GenericFileFormatter::viewElements()
* @see https://www.drupal.org/project/drupal/issues/2568289
*/
function __mytheme_preprocess_field__generic_download_icons_view_mode(&$variables, $hook) {
if (isset($variables['entity_type'])
&& ($variables['entity_type'] == 'media')
&& isset($variables['field_type'])
&& ($variables['field_type'] == 'image')
&& isset($variables['element']['#view_mode'])
&& ($variables['element']['#view_mode'] == 'custom_generic_file')) {
foreach ($variables['items'] as $key => $item) {
/* @var Drupal\image\Plugin\Field\FieldType\ImageItem */
if (isset($item['content']['#item']) && $item['content']['#item'] instanceof FileItem) {
/** @var \Drupal\Core\Entity\Plugin\DataType\EntityReference $entityReference */
$entityReference = $item['content']['#item']->get('entity');
/** @var \Drupal\Core\Entity\Plugin\DataType\EntityAdapter $entityAdapter */
$entityAdapter = $entityReference->getTarget();
/** @var \Drupal\Core\Entity\EntityInterface $file */
/** @var \Drupal\file\Entity\File $file */
$file = $entityAdapter->getValue();
$item['content'] = [
'#theme' => 'file_link',
'#file' => $file,
'#description' => NULL,
'#cache' => [
'tags' => $file->getCacheTags(),
],
];
// Replace for real.
$variables['items'][$key]['content'] = $item['content'];
}
}
}
}