Skip to content

Code Examples

This document provides practical examples for common tasks when working with the Name module programmatically.

Formatting Names

Basic Name Formatting

// Get the formatter service
$formatter = \Drupal::service('name.formatter');

// Name data array
$name = [
  'title' => 'Dr.',
  'given' => 'Jane',
  'middle' => 'Marie',
  'family' => 'Smith',
  'generational' => 'Jr.',
  'credentials' => 'PhD',
];

// Format using different formats
$full = $formatter->format($name, 'full');
// Result: "Dr. Jane Marie Smith Jr. PhD"

$formal = $formatter->format($name, 'formal');
// Result: "Smith, Jane Marie, Jr., PhD"

$family_only = $formatter->format($name, 'family');
// Result: "Smith"

$given_only = $formatter->format($name, 'given');
// Result: "Jane"

Formatting Name Lists

$formatter = \Drupal::service('name.formatter');

$names = [
  ['given' => 'John', 'family' => 'Doe'],
  ['given' => 'Jane', 'family' => 'Smith'],
  ['given' => 'Bob', 'family' => 'Johnson'],
];

// Format as a list
$list = $formatter->formatList($names, 'full', 'default');
// Result: "John Doe, Jane Smith and Bob Johnson"

Custom Formatting Settings

$formatter = \Drupal::service('name.formatter');

// Change separator settings
$formatter->setSetting('sep1', '-')
          ->setSetting('sep2', ' | ');

$name = ['given' => 'John', 'family' => 'Smith'];
$formatted = $formatter->format($name, 'full');
// Components are now separated by hyphens

Working with Name Fields

Creating a Name Field Programmatically

use Drupal\field\Entity\FieldStorageConfig;
use Drupal\field\Entity\FieldConfig;

// Create field storage
$field_storage = FieldStorageConfig::create([
  'field_name' => 'field_person_name',
  'entity_type' => 'node',
  'type' => 'name',
  'cardinality' => 1,
]);
$field_storage->save();

// Create field instance
$field = FieldConfig::create([
  'field_storage' => $field_storage,
  'bundle' => 'person',
  'label' => 'Full Name',
  'required' => TRUE,
  'settings' => [
    // Component settings
    'components' => [
      'title' => TRUE,
      'given' => TRUE,
      'middle' => TRUE,
      'family' => TRUE,
      'generational' => FALSE,
      'credentials' => FALSE,
    ],
    // Component labels
    'labels' => [
      'title' => 'Title',
      'given' => 'First Name',
      'middle' => 'Middle Name',
      'family' => 'Last Name',
    ],
    // Minimum required components
    'minimum_components' => [
      'given' => 'given',
      'family' => 'family',
    ],
    // Title options
    'title_options' => [
      'Mr.',
      'Mrs.',
      'Ms.',
      'Dr.',
    ],
    // Maximum lengths
    'max_length' => [
      'title' => 31,
      'given' => 63,
      'middle' => 127,
      'family' => 63,
      'generational' => 15,
      'credentials' => 255,
    ],
  ],
]);
$field->save();

Setting Name Field Values

use Drupal\node\Entity\Node;

// Create a node with name field
$node = Node::create([
  'type' => 'person',
  'title' => 'Person Node',
  'field_person_name' => [
    'title' => 'Dr.',
    'given' => 'Jane',
    'middle' => 'Marie',
    'family' => 'Smith',
    'credentials' => 'PhD',
  ],
]);
$node->save();

Reading Name Field Values

// Load a node
$node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);

// Get the name field
$name_field = $node->get('field_person_name');

// Check if field has a value
if (!$name_field->isEmpty()) {
  // Get first item
  $name = $name_field->first()->getValue();

  // Access individual components
  $given_name = $name['given'];
  $family_name = $name['family'];

  // Format for display
  $formatter = \Drupal::service('name.formatter');
  $formatted = $formatter->format($name, 'full');

  echo $formatted;
}

Multiple Name Values

// Create field with multiple values
$field_storage = FieldStorageConfig::create([
  'field_name' => 'field_authors',
  'entity_type' => 'node',
  'type' => 'name',
  'cardinality' => -1,  // Unlimited
]);
$field_storage->save();

// Set multiple names
$node = Node::create([
  'type' => 'article',
  'title' => 'Research Paper',
  'field_authors' => [
    ['given' => 'John', 'family' => 'Doe'],
    ['given' => 'Jane', 'family' => 'Smith'],
    ['given' => 'Bob', 'family' => 'Johnson'],
  ],
]);
$node->save();

// Read multiple values
$authors = $node->get('field_authors');
foreach ($authors as $author_item) {
  $author = $author_item->getValue();
  echo $author['given'] . ' ' . $author['family'] . "\n";
}

// Format as a list
$formatter = \Drupal::service('name.formatter');
$names = [];
foreach ($authors as $author_item) {
  $names[] = $author_item->getValue();
}
$author_list = $formatter->formatList($names, 'full', 'default');

Using the Name Form Element

Basic Name Element

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class MyCustomForm extends FormBase {

  public function getFormId() {
    return 'my_custom_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['person_name'] = [
      '#type' => 'name',
      '#title' => $this->t('Full Name'),
      '#required' => TRUE,
      '#components' => [
        'given' => 'given',
        'middle' => 'middle',
        'family' => 'family',
      ],
      '#minimum_components' => [
        'given' => 'given',
        'family' => 'family',
      ],
      '#default_value' => [
        'given' => '',
        'middle' => '',
        'family' => '',
      ],
    ];

    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
    ];

    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $name = $form_state->getValue('person_name');

    // Format the submitted name
    $formatter = \Drupal::service('name.formatter');
    $formatted = $formatter->format($name, 'full');

    $this->messenger()->addStatus($this->t('Submitted name: @name', [
      '@name' => $formatted,
    ]));
  }
}

Custom Component Labels

$form['name'] = [
  '#type' => 'name',
  '#title' => $this->t('Contact Name'),
  '#labels' => [
    'given' => $this->t('First Name'),
    'family' => $this->t('Last Name'),
    'title' => $this->t('Salutation'),
  ],
  '#components' => [
    'title' => 'title',
    'given' => 'given',
    'family' => 'family',
  ],
];

Different Layout Options

// Asian name order (family before given)
$form['name_asian'] = [
  '#type' => 'name',
  '#title' => $this->t('Name (Asian Order)'),
  '#component_layout' => 'asian',
  '#components' => [
    'family' => 'family',
    'given' => 'given',
    'middle' => 'middle',
  ],
];

// German name order
$form['name_german'] = [
  '#type' => 'name',
  '#title' => $this->t('Name (German Order)'),
  '#component_layout' => 'german',
  '#components' => [
    'title' => 'title',
    'credentials' => 'credentials',
    'given' => 'given',
    'middle' => 'middle',
    'family' => 'family',
  ],
];

Generating Sample Names

Basic Name Generation

$generator = \Drupal::service('name.generator');

// Generate 5 sample names
$samples = $generator->generateSampleNames(5);

foreach ($samples as $name) {
  $formatter = \Drupal::service('name.formatter');
  echo $formatter->format($name, 'full') . "\n";
}

Field-Specific Sample Names

use Drupal\field\Entity\FieldConfig;

$generator = \Drupal::service('name.generator');

// Get field definition
$field = FieldConfig::loadByName('node', 'person', 'field_person_name');

// Generate names respecting field settings
$samples = $generator->generateSampleNames(10, $field);

Loading Specific Component Samples

$generator = \Drupal::service('name.generator');

// Get male given names
$male_names = $generator->loadSampleValues('given', 'm');

// Get female given names
$female_names = $generator->loadSampleValues('given', 'f');

// Get family names (no gender)
$family_names = $generator->loadSampleValues('family');

// Get titles
$titles = $generator->loadSampleValues('title');

Working with Name Formats

Creating Custom Name Formats

use Drupal\name\Entity\NameFormat;

// Create a custom format
$format = NameFormat::create([
  'id' => 'initials_last',
  'label' => 'Initials + Last Name',
  'pattern' => 'ig. im. f',
  'locked' => FALSE,
]);
$format->save();

// Use the custom format
$formatter = \Drupal::service('name.formatter');
$name = [
  'given' => 'John',
  'middle' => 'Robert',
  'family' => 'Smith',
];
$formatted = $formatter->format($name, 'initials_last');
// Result: "J. R. Smith"

Loading and Modifying Formats

use Drupal\name\Entity\NameFormat;

// Load an existing format
$format = NameFormat::load('full');
$pattern = $format->get('pattern');

// Create a variation
$custom = NameFormat::create([
  'id' => 'custom_full',
  'label' => 'Custom Full Name',
  'pattern' => 't Ug f c',  // Uppercase given name
]);
$custom->save();

Creating List Formats

use Drupal\name\Entity\NameListFormat;

// Create a custom list format
$list_format = NameListFormat::create([
  'id' => 'semicolon_list',
  'label' => 'Semicolon Separated List',
  'delimiter' => '; ',
  'and' => 'symbol',  // Use "&"
  'delimiter_precedes_last' => 'always',
  'el_al_min' => 5,  // Use "et al" after 5 names
  'el_al_first' => 3,  // Show first 3 before "et al"
]);
$list_format->save();

// Use the custom list format
$formatter = \Drupal::service('name.formatter');
$names = [
  ['given' => 'John', 'family' => 'Doe'],
  ['given' => 'Jane', 'family' => 'Smith'],
];
$list = $formatter->formatList($names, 'full', 'semicolon_list');
// Result: "John Doe; & Jane Smith"

Autocomplete Integration

Custom Autocomplete Handler

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\name\NameAutocomplete;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

class CustomAutocompleteController extends ControllerBase {

  protected $nameAutocomplete;

  public function __construct(NameAutocomplete $name_autocomplete) {
    $this->nameAutocomplete = $name_autocomplete;
  }

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('name.autocomplete')
    );
  }

  public function autocomplete(Request $request, $field_name) {
    $string = $request->query->get('q');

    // Load field definition
    $field = FieldConfig::loadByName('node', 'person', $field_name);

    // Get matches
    $matches = $this->nameAutocomplete->getMatches(
      $field,
      'given',  // Component to search
      $string
    );

    // Filter or modify matches
    $filtered = array_slice($matches, 0, 5);

    return new JsonResponse($filtered);
  }
}

User Name Integration

Setting User Display Name

The Name module can integrate with user accounts to set display names.

use Drupal\user\Entity\User;

// Load a user
$user = User::load($uid);

// If user has a name field, it's automatically used for display
// This happens through hook_user_format_name_alter()

// Get the formatted name
$display_name = $user->getDisplayName();

// The name comes from the configured user name field
// Set at: /admin/config/regional/name

Configuring User Preferred Name Field

// Set the preferred user name field
\Drupal::configFactory()
  ->getEditable('name.settings')
  ->set('user_preferred', 'field_full_name')
  ->save();

// Now user display names will use this field

Dependency Injection Examples

In a Custom Service

namespace Drupal\my_module\Service;

use Drupal\name\NameFormatterInterface;
use Drupal\name\NameGeneratorInterface;

class NameProcessingService {

  protected $nameFormatter;
  protected $nameGenerator;

  public function __construct(
    NameFormatterInterface $name_formatter,
    NameGeneratorInterface $name_generator
  ) {
    $this->nameFormatter = $name_formatter;
    $this->nameGenerator = $name_generator;
  }

  public function processName(array $name_data) {
    // Format the name
    $formatted = $this->nameFormatter->format($name_data, 'full');

    // Do something with it
    return $formatted;
  }

  public function createTestData($count) {
    return $this->nameGenerator->generateSampleNames($count);
  }
}

In a Controller

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\name\NameFormatterInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class NameDisplayController extends ControllerBase {

  protected $nameFormatter;

  public function __construct(NameFormatterInterface $name_formatter) {
    $this->nameFormatter = $name_formatter;
  }

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('name.formatter')
    );
  }

  public function displayNames() {
    $names = $this->getNameData();

    $list = $this->nameFormatter->formatList($names, 'full', 'default');

    return [
      '#markup' => $list,
    ];
  }
}

Advanced Examples

Custom Field Widget Using Name Components

namespace Drupal\my_module\Plugin\Field\FieldWidget;

use Drupal\Core\Field\Attribute\FieldWidget;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;

/**
 * Custom Name Widget for parsing full names.
 */
#[FieldWidget(
  id: 'custom_name_widget',
  label: new TranslatableMarkup('Custom Name Widget'),
  field_types: [
    'name',
  ],
)]
class CustomNameWidget extends WidgetBase {

  public function formElement(
    FieldItemListInterface $items,
    $delta,
    array $element,
    array &$form,
    FormStateInterface $form_state
  ) {
    $item = $items[$delta];

    $element['#type'] = 'fieldset';
    $element['#title'] = $this->t('Name');

    // Create custom layout
    $element['full_name'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Full Name'),
      '#default_value' => implode(' ', array_filter([
        $item->given ?? '',
        $item->family ?? '',
      ])),
      '#description' => $this->t('Enter first and last name.'),
    ];

    // Add AJAX parsing button
    $element['parse'] = [
      '#type' => 'button',
      '#value' => $this->t('Parse Name'),
      '#ajax' => [
        'callback' => [$this, 'parseNameAjax'],
        'wrapper' => 'name-components-wrapper',
      ],
    ];

    $element['components'] = [
      '#type' => 'container',
      '#prefix' => '<div id="name-components-wrapper">',
      '#suffix' => '</div>',
    ];

    $element['components']['given'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Given Name'),
      '#default_value' => $item->given ?? '',
    ];

    $element['components']['family'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Family Name'),
      '#default_value' => $item->family ?? '',
    ];

    return $element;
  }
}

See Also