Compound fields - Part 4

the Field Type Widget Formatter definition

In the previous section created the field type widget definition that will be used to format the field on the node form. In this section, we will create the file that defines the widget formatter used to pre-format the data before passing it on to a twig file.

NameFieldTypeDefaultFormatter.php

The default formatter file defines the format of the field data to be passed to the twig file for rendering. The name of the file (less the .php extension) will also be the name of the class defined within the file. The file should be placed in the path <my module>/src/Plugin/Field/FieldFormatter.


namespace Drupal\name_field_type\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;

These first lines are declaring the name space of the file, which should match up to the path in which you place the file, and the use instructions for dependency injection.


/**
 * Plugin implementation of the 'name_formatter' formatter.
 *
 * @FieldFormatter(
 *   id = "name_formatter",
 *   label = @Translation("Name Field Type Formatter"),
 *   field_types = {
 *     "name"
 *   }
 * )
 */

This annotation block defines the formatter.


class NameFormatter extends FormatterBase {
    public function viewElements(FieldItemListInterface $items, $langcode) {
        $element = [];
        foreach ($items as $delta => $item) {
            $name = [];
            if ($item->title) $name[] = $item->title;
            if ($item->first_name) $name[] = $item->first_name;
            if ($item->middle_name) $name[] = $item->middle_name;
            if ($item->last_name) $name[] = $item->last_name;
            if ($item->maternal_last_name) $name[] = $item->maternal_last_name;
            if ($item->suffix) $name[] = $item->suffix;
            $element[$delta] = [
                'name' => ['#markup' => implode(' ', $name)],
                '#theme' => 'name_field_type',
            ];
        }
        return $element;
    }
}

What is going on in this method? Each instance of the field ($item) is an object. We're going to want to have the pieces of the compound field assembled as a single string. In order to piece them together in a meaningful way, there should be a space between the items. An easy way of doing that is by using the PHP implode function, but that acts on arrays and not objects. So, we move the object properties that have values into an array, first.

In Part 5 we will create the twig file that renders the field.

 

Part 3  Part 5


Type:
Tutorial
Tags:
D8
field