Documentation to implement as a custom form element

Created on 4 October 2024, 3 months ago

Problem/Motivation

I needed to implement this form element in a custom form. Available for anonymous users to select and/or create taxonomy terms in the tags vocabulary.
But I struggled setting it up based on the current documentation and other issues available.

Here's the code that ended up working:

$selection_settings = array(
        'target_bundles' => array('tags' => 'tags'),
        'sort' => array('field' => '_none'),
// Changing this value to 1 didn't enable the #autocreate property
        'auto_create' => (BOOL) 0,
        'auto_create_bundle' => 'tags',
        'match_operator' => 'CONTAINS',
      );
      $target_type = 'taxonomy_term';
      $selection_handler = 'default:taxonomy_term';
      $data = serialize($selection_settings) . $target_type .
        $selection_handler;
      $selection_settings_key = Crypt::hmacBase64(
        $data,
        Settings::getHashSalt()
      );
// This is needed so you don't get a 403 error. 
// See: https://www.drupal.org/project/autocomplete_deluxe/issues/3307367
      $key_value_storage = \Drupal::service('keyvalue')->get('entity_autocomplete');
      if (!$key_value_storage->has($selection_settings_key)) {
        $key_value_storage->set($selection_settings_key, $selection_settings);
      }
      $route_parameters = [
        'target_type' => $target_type,
        'selection_handler' => $selection_handler,
        'selection_settings_key' => $selection_settings_key,
      ];
      $url = Url::fromRoute(
        'autocomplete_deluxe.autocomplete',
        $route_parameters,
// ['absolute' => TRUE] didn't work, the base URL was added at the start of the generated URL.
        ['absolute' => FALSE]
// )->toString(); didn't work. 
// See: https://www.drupal.org/project/autocomplete_deluxe/issues/3307367
      )->getInternalPath();

      $form['mots_clefs'] = array(
        '#type' => 'autocomplete_deluxe',
        '#autocomplete_deluxe_path' => $url,
        '#selection_settings' => $selection_settings,
        '#multiple' => TRUE,
        '#cardinality' => [],
// This is the only way I got the auto_create to work. Based on the original entity_autocomplete form element.
        '#autocreate' => [
          'bundle' => 'tags',
          'uid' => 1,
        ],
        '#target_type' => $target_type,
        '#selection_handler' => $selection_handler,
        '#limit' => 10,
        '#size' => 60,
        '#new_terms' => 1,
        '#min_length' => 0,
        '#delimiter' => ',',
        '#not_found_message_allow' => 0,
        '#not_found_message' => "Le mot-clef '@term' sera créé.",
      );

Could this be added in the documentation? After being improved maybe?

💬 Support request
Status

Active

Version

2.1

Component

Documentation

Created by

🇫🇷France lizuka

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024