- We will need to create the src/Plugin/Field/FieldFormatter directory in the module's base location. The Field module discovers field formatters in the Plugin\Field\FieldFormatter namespace.
- Create a RealNameFormatter.php file in the newly created directory so that we can define the RealNameFormatter class. This will provide a custom form element to display the field's values:
- The RealNameFormatter class will extend the \Drupal\Core\Field\FormatterBase class:
<?php
namespace Drupal\mymodule\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Field\FieldItemListInterface;
class RealNameFormatter extends FormatterBase {
}
- We will provide the field widget's identifier, label, and supported field types:
<?php
namespace Drupal\mymodule\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Field\FieldItemListInterface;
/**
* Plugin implementation of the 'realname_one_line' formatter.
*
* @FieldFormatter(
* id = "realname_one_line",
* label = @Translation("Real name (one line)"),
* field_types = {
* "realname"
* }
* )
*/
class RealNameFormatter extends FormatterBase {
}
- We will need to implement the viewElements method to satisfy the \Drupal\Core\Field\FormatterInferface interface. This is used to render the field data. Add the following method to your class:
/**
{@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$element = [];
foreach ($items as $delta => $item) {
$element[$delta] = [
'#markup' => $this->t('@first @last', [
'@first' => $item->first_name,
'@last' => $item->last_name,
]),
];
}
return $element;
}
- Next, we will need to modify our original RealName field type's plugin class to use the default formatter that we created. Open the src/Plugin/FieldType/RealName.php file, and update the default_formatter annotation property as realname_one_line:
/**
* Plugin implementation of the 'realname' field type.
*
* @FieldType(
* id = "realname",
* label = @Translation("Real name"),
* description = @Translation("This field stores a first and last name."),
* category = @Translation("General"),
* default_widget = " string_textfield ",
* default_formatter = "realname_one_line"
* )
*/
- Rebuild Drupal's cache so that the plugin system can discover the new field widget.
- Update an entity view mode with a Real name field to use the Real name (one line) formatter: