You are here

public static function LinkAutocompleteFormTrait::getLinkAutocompleteElement in Helper 8

Generates a autocomplete link element for a form.

@parma string $entity_type The entity type.

Parameters

string $default_value: The default value for the field.

Return value

array The autocomplete link form element.

File

src/LinkAutocompleteFormTrait.php, line 28

Class

LinkAutocompleteFormTrait
Provides helpers for adding a content autocomplete link element to a form.

Namespace

Drupal\helper

Code

public static function getLinkAutocompleteElement($entity_type, $default_value = NULL) {
  $type = \Drupal::entityTypeManager()
    ->getDefinition($entity_type);
  return [
    '#type' => 'entity_autocomplete',
    '#target_type' => $entity_type,
    '#default_value' => isset($default_value) ? static::getUriAsDisplayableString($default_value) : '',
    '#description' => t('Start typing the @label of a @type to select it. You can also enter an internal path such as %add-node or an external URL such as %url. Enter %front to link to the front page.', [
      '@label' => $type
        ->getKey('label'),
      '@type' => $type
        ->getSingularLabel(),
      '%add-node' => '/node/add',
      '%url' => 'http://example.com',
      '%front' => '<front>',
    ]),
    '#element_validate' => [
      [
        static::class,
        'validateLinkAutocompleteElement',
      ],
    ],
    // Disable autocompletion when the first character is '/', '#' or '?'.
    '#attributes' => [
      'data-autocomplete-first-character-blacklist' => '/#?',
    ],
    // Avoid the default value processing since we are doing it ourselves in
    // static::getUriAsDisplayableString().
    '#process_default_value' => FALSE,
  ];
}