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— aNameFormatconfig entity ID (e.g.'full','default').$langcode— language code, orNULLfor the current UI language.- Returns an empty markup object when the field has no values.
Example:
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— aNameFormatconfig entity ID.$list_type— aNameListFormatconfig entity ID.$langcode— language code, orNULLfor the current UI language.- Returns an empty markup object when the field has no values.
Example:
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.formatterservice - Format entities:
NameFormatconfig entities (e.g.default,full) - List format entities:
NameListFormatconfig entities (e.g.default)
See Formatter service for the full service API,
including setSetting() for link targets and other display options.