Skip to content

Helper Functions

The Name module provides several helper functions for working with name components, formats, and layouts. These functions are defined in name.module and are available globally once the module is enabled.

Component Functions

_name_translations()

Returns translated labels for name field components.

function _name_translations(?array $intersect = NULL);

Parameters:

  • $intersect (array|null) - Optional array to filter returned components

Returns: array - Associative array of component keys and translated labels

Usage:

// Get all component translations
$translations = _name_translations();
// Returns:
// [
//   'title' => 'Title',
//   'given' => 'Given',
//   'middle' => 'Middle name(s)',
//   'family' => 'Family',
//   'generational' => 'Generational',
//   'credentials' => 'Credentials',
// ]

// Get only specific components
$subset = _name_translations(['given' => '', 'family' => '']);
// Returns:
// [
//   'given' => 'Given',
//   'family' => 'Family',
// ]

Use Cases:

  • Building form elements with proper labels
  • Generating field settings interfaces
  • Displaying component names in the UI

_name_component_keys()

Returns the machine names of all name field components.

function _name_component_keys();

Returns: array - Associative array of component keys (key => key)

Usage:

$keys = _name_component_keys();
// Returns:
// [
//   'title' => 'title',
//   'given' => 'given',
//   'middle' => 'middle',
//   'family' => 'family',
//   'credentials' => 'credentials',
//   'generational' => 'generational',
// ]

// Check if a component exists
if (isset(_name_component_keys()[$component])) {
  // Component is valid
}

_name_component_layout()

Adjusts component weights and visibility based on layout type.

function _name_component_layout(&$element, $layout = 'default');

Parameters:

  • $element (array) - Form element array to modify (passed by reference)
  • $layout (string) - Layout type ('default', 'asian', 'eastern', 'german')

Effects:

  • Modifies the #weight property of child components
  • May hide components (like 'generational' in Asian/German layouts)
  • May set default values to empty strings

Layout Types:

Layout Description Component Order
default Western name order title, given, middle, family, generational, credentials
asian Asian name order title, family, given, middle, credentials (no generational)
eastern Eastern European title, family, given, middle, generational, credentials
german German name order title, credentials, given, middle, family (no generational)

Usage:

$element = [
  'title' => ['#type' => 'textfield', ...],
  'given' => ['#type' => 'textfield', ...],
  'family' => ['#type' => 'textfield', ...],
  // ... other components
];

// Apply Asian layout
_name_component_layout($element, 'asian');
// Now family appears before given, generational is hidden

Widget Functions

name_widget_layouts()

Returns available widget layout options from all modules.

function name_widget_layouts();

Returns: array - Associative array of layout definitions

Structure:

[
  'layout_id' => [
    'label' => 'Layout Label',
    'library' => ['module/library_name'],
    'wrapper_attributes' => [
      'class' => ['css-class'],
    ],
  ],
]

Usage:

$layouts = name_widget_layouts();

// Build a select list
$options = [];
foreach ($layouts as $key => $layout) {
  $options[$key] = $layout['label'];
}

$form['layout'] = [
  '#type' => 'select',
  '#title' => t('Widget Layout'),
  '#options' => $options,
];

Implementation Details:

  • Invokes hook_name_widget_layouts() on all modules
  • Results are cached for performance
  • Default layouts: 'stacked' and 'inline'

Format Functions

name_get_custom_format_options()

Gets available custom name formats as select options.

function name_get_custom_format_options();

Returns: array - Format options (machine_name => label)

Usage:

$form['name_format'] = [
  '#type' => 'select',
  '#title' => t('Name Format'),
  '#options' => name_get_custom_format_options(),
];

name_get_custom_list_format_options()

Gets available custom list formats as select options.

function name_get_custom_list_format_options();

Returns: array - List format options (machine_name => label)

Usage:

$form['list_format'] = [
  '#type' => 'select',
  '#title' => t('List Format'),
  '#options' => name_get_custom_list_format_options(),
];

name_get_format_by_machine_name()

Loads a name format configuration entity by machine name.

function name_get_format_by_machine_name($machine_name);

Parameters:

  • $machine_name (string) - Format machine name

Returns: string|null - Format pattern or NULL if not found

Usage:

$pattern = name_get_format_by_machine_name('full');
// Returns: "t g m f s c"

$pattern = name_get_format_by_machine_name('formal');
// Returns: "f, g m, s, c"

Element Functions

name_element_expand()

Expands a name form element into its component fields.

function name_element_expand($element, &$form_state, $complete_form);

Parameters:

  • $element (array) - The form element to expand
  • $form_state (FormStateInterface) - The form state
  • $complete_form (array) - The complete form array

Returns: array - Expanded form element with child components

Usage:

This is called automatically by Drupal's Form API when processing a #type => 'name' element.

name_element_validate()

Validates a name form element.

function name_element_validate($element, &$form_state);

Parameters:

  • $element (array) - The form element to validate
  • $form_state (FormStateInterface) - The form state

Validation Rules:

  • Checks minimum and maximum length constraints
  • Validates required components
  • Ensures at least one substantive component has a value
  • Validates against allowed options (for title, generational)

name_element_validate_is_empty()

Checks if a name element contains any meaningful data.

function name_element_validate_is_empty(array $item);

Parameters:

  • $item (array) - Name component array

Returns: bool - TRUE if empty, FALSE if has data

Usage:

$name = ['title' => '', 'given' => '', 'family' => ''];
if (name_element_validate_is_empty($name)) {
  // Name is empty
}

$name = ['title' => '', 'given' => 'John', 'family' => ''];
if (!name_element_validate_is_empty($name)) {
  // Name has data
}

Note: Title and generational alone are not considered meaningful data.

Utility Functions

name_get_additional_component()

Retrieves an additional component value (preferred/alternative) from a referenced field.

function name_get_additional_component(
  EntityTypeManagerInterface $entityTypeManager, 
  RendererInterface $renderer, 
  FieldItemListInterface $items, 
  $key_value, 
  $sep_value
);

Parameters:

  • $entityTypeManager - Entity type manager service
  • $renderer - Renderer service
  • $items - Field items to process
  • $key_value - Reference key ('_self' or field name)
  • $sep_value - Separator for multiple values

Returns: string - The additional component value

_name_value_sanitize()

Sanitizes a name component value.

function _name_value_sanitize($item, $column = NULL, $type = 'default');

Parameters:

  • $item (mixed) - String or array containing the value
  • $column (string|null) - Column name if $item is array
  • $type (string) - Sanitization type:
  • 'default' - HTML escape (default)
  • 'plain' - Strip tags
  • 'raw' - No processing (not recommended)

Returns: string - Sanitized value

Usage:

// Sanitize a string
$safe = _name_value_sanitize('<script>alert("xss")</script>');
// Returns: "&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;"

// Sanitize an array value
$name = ['given' => '<b>John</b>'];
$safe = _name_value_sanitize($name, 'given', 'plain');
// Returns: "John"

_name_formatter_output_options()

Returns available output formatter options.

function _name_formatter_output_options();

Returns: array - Output options (key => label)

[
  'default' => 'Default',
  'plain' => 'Plain text',
  'raw' => 'Raw value (not recommended)',
]

_name_formatter_output_types()

Returns available formatter rendering methods.

function _name_formatter_output_types();

Returns: array - Output types (key => label)

[
  'default' => 'Default',
  'plain' => 'Plain',
  'raw' => 'Raw',
]

Theme Functions

name_theme()

Implements hook_theme() to register name-related theme hooks.

function name_theme();

Registered Templates:

  • name_item - Individual name display
  • name_item_list - List of names display
  • name - Name form element
  • name_format_parameter_help - Format pattern help text

Example: Building a Custom Name Form

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

class CustomNameForm extends FormBase {

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

  public function buildForm(array $form, FormStateInterface $form_state) {
    // Get component labels
    $labels = _name_translations();

    // Build form with only specific components
    $components = ['given', 'family'];

    foreach ($components as $component) {
      $form[$component] = [
        '#type' => 'textfield',
        '#title' => $labels[$component],
        '#required' => TRUE,
      ];
    }

    // Apply a layout
    _name_component_layout($form, 'default');

    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state->getValues();

    // Check if name is empty
    if (name_element_validate_is_empty($values)) {
      $this->messenger()->addWarning('Name is empty.');
      return;
    }

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

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

See Also