Created
September 8, 2018 07:27
-
-
Save svetlio/97b6f519796efbb599928b042a1f3778 to your computer and use it in GitHub Desktop.
Drupal 8 FieldFormatter for file and image. Output file/image ID. Usable for rest in views. ($ drupal generate:plugin:fieldformatter)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @file FileIdFieldFormatter.php | |
* | |
* field formatter id for file and image | |
* | |
*/ | |
namespace Drupal\custom_fs\Plugin\Field\FieldFormatter; | |
use Drupal\Component\Utility\Html; | |
use Drupal\Core\Field\FieldItemInterface; | |
use Drupal\Core\Field\FieldItemListInterface; | |
use Drupal\Core\Field\FormatterBase; | |
use Drupal\Core\Form\FormStateInterface; | |
/** | |
* Plugin implementation of the 'file_id_field_formatter' formatter. | |
* | |
* @FieldFormatter( | |
* id = "file_id_field_formatter", | |
* label = @Translation("File ID"), | |
* field_types = { | |
* "image","file" | |
* } | |
* ) | |
*/ | |
class FileIdFieldFormatter extends FormatterBase { | |
/** | |
* {@inheritdoc} | |
*/ | |
public static function defaultSettings() { | |
return [ | |
// Implement default settings. | |
] + parent::defaultSettings(); | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function settingsForm(array $form, FormStateInterface $form_state) { | |
return [ | |
// Implement settings form. | |
] + parent::settingsForm($form, $form_state); | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function settingsSummary() { | |
$summary = []; | |
// Implement settings summary. | |
return $summary; | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function viewElements(FieldItemListInterface $items, $langcode) { | |
$elements = []; | |
foreach ($items as $delta => $item) { | |
//ksm($item); | |
$elements[$delta]['#markup'] = $item->target_id; | |
} | |
return $elements; | |
} | |
/** | |
* Generate the output appropriate for one field item. | |
* | |
* @param \Drupal\Core\Field\FieldItemInterface $item | |
* One field item. | |
* | |
* @return string | |
* The textual output generated. | |
*/ | |
protected function viewValue(FieldItemInterface $item) { | |
// The text value has no text format assigned to it, so the user input | |
// should equal the output, including newlines. | |
return nl2br(Html::escape($item->value)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment