3 namespace Drupal\file\Plugin\Field\FieldFormatter;
5 use Drupal\Core\Field\FieldDefinitionInterface;
6 use Drupal\Core\Field\FieldItemInterface;
7 use Drupal\Core\Form\FormStateInterface;
10 * Formatter to render a filename as file extension.
13 * id = "file_extension",
14 * label = @Translation("File extension"),
20 class FileExtensionFormatter extends BaseFieldFileFormatterBase {
25 public static function defaultSettings() {
26 $settings = parent::defaultSettings();
28 $settings['extension_detect_tar'] = FALSE;
35 public function settingsForm(array $form, FormStateInterface $form_state) {
36 $form = parent::settingsForm($form, $form_state);
37 $form['extension_detect_tar'] = [
38 '#type' => 'checkbox',
39 '#title' => $this->t('Include tar in extension'),
40 '#description' => $this->t("If the part of the filename just before the extension is '.tar', include this in the extension output."),
41 '#default_value' => $this->getSetting('extension_detect_tar'),
49 protected function viewValue(FieldItemInterface $item) {
50 $filename = $item->value;
51 if (!$this->getSetting('extension_detect_tar')) {
52 return pathinfo($filename, PATHINFO_EXTENSION);
55 $file_parts = explode('.', basename($filename));
56 if (count($file_parts) > 1) {
57 $extension = array_pop($file_parts);
58 $last_part_in_name = array_pop($file_parts);
59 if ($last_part_in_name === 'tar') {
60 $extension = 'tar.' . $extension;
70 public static function isApplicable(FieldDefinitionInterface $field_definition) {
71 // Just show this file extension formatter on the filename field.
72 return parent::isApplicable($field_definition) && $field_definition->getName() === 'filename';