FilemimeFormatter.php

Same filename and directory in other branches
  1. 9 core/modules/file/src/Plugin/Field/FieldFormatter/FilemimeFormatter.php
  2. 8.9.x core/modules/file/src/Plugin/Field/FieldFormatter/FilemimeFormatter.php
  3. 10 core/modules/file/src/Plugin/Field/FieldFormatter/FilemimeFormatter.php

Namespace

Drupal\file\Plugin\Field\FieldFormatter

File

core/modules/file/src/Plugin/Field/FieldFormatter/FilemimeFormatter.php

View source
<?php

namespace Drupal\file\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\Attribute\FieldFormatter;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;

/**
 * Formatter to render the file MIME type, with an optional icon.
 */
class FilemimeFormatter extends BaseFieldFileFormatterBase {
    
    /**
     * {@inheritdoc}
     */
    public static function isApplicable(FieldDefinitionInterface $field_definition) {
        return parent::isApplicable($field_definition) && $field_definition->getName() === 'filemime';
    }
    
    /**
     * {@inheritdoc}
     */
    public static function defaultSettings() {
        $settings = parent::defaultSettings();
        $settings['filemime_image'] = FALSE;
        return $settings;
    }
    
    /**
     * {@inheritdoc}
     */
    public function settingsForm(array $form, FormStateInterface $form_state) {
        $form = parent::settingsForm($form, $form_state);
        $form['filemime_image'] = [
            '#title' => $this->t('Display an icon'),
            '#description' => $this->t('The icon is representing the file type, instead of the MIME text (such as "image/jpeg")'),
            '#type' => 'checkbox',
            '#default_value' => $this->getSetting('filemime_image'),
        ];
        return $form;
    }
    
    /**
     * {@inheritdoc}
     */
    protected function viewValue(FieldItemInterface $item) {
        $value = $item->value;
        if ($this->getSetting('filemime_image') && $value) {
            $file_icon = [
                '#theme' => 'image__file_icon',
                '#file' => $item->getEntity(),
            ];
            return $file_icon;
        }
        return $value;
    }

}

Classes

Title Deprecated Summary
FilemimeFormatter Formatter to render the file MIME type, with an optional icon.

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.