Skip to content

NameItemList

NameItemList is the field item list class for the name field type. It extends Drupal's FieldItemList and adds two convenience methods for formatting names directly from a field accessor — no separate service call required.

This follows the same pattern Drupal core uses for EntityReferenceFieldItemList::referencedEntities().

Methods

format()

Formats the first non-empty name item using the given format ID.

public function format(
  string $type = 'default',
  ?string $langcode = NULL,
): \Drupal\Component\Render\MarkupInterface
  • $type — a NameFormat config entity ID (e.g. 'full', 'default').
  • $langcode — language code, or NULL for the current UI language.
  • Returns an empty markup object when the field has no values.

Example:

$label = $node->get('field_name')->format('full');

formatList()

Formats all non-empty name items as a joined list using the given format and list format IDs.

public function formatList(
  string $type = 'default',
  string $list_type = 'default',
  ?string $langcode = NULL,
): \Drupal\Component\Render\MarkupInterface
  • $type — a NameFormat config entity ID.
  • $list_type — a NameListFormat config entity ID.
  • $langcode — language code, or NULL for the current UI language.
  • Returns an empty markup object when the field has no values.

Example:

// "Alice Jones and Bob Brown"
$list = $node->get('field_authors')->formatList('full', 'default');

When to use this vs the service directly

Situation Recommended approach
Formatting from a field on an entity $entity->get('field')->format()
Formatting a raw component array \Drupal::service('name.formatter')->format()
Formatting a list of raw component arrays \Drupal::service('name.formatter')->formatList()
Need custom settings (e.g. link target) Use the service and call setSetting() first

Class and service reference

  • Class: Drupal\name\Plugin\Field\FieldType\NameItemList
  • Delegates to: name.formatter service
  • Format entities: NameFormat config entities (e.g. default, full)
  • List format entities: NameListFormat config entities (e.g. default)

See Formatter service for the full service API, including setSetting() for link targets and other display options.