To get this working I had to create a hidden field to store the value and hijack the drupal autocompleteselect handler in JavaScript. I addeduse a custom selectHandler applied via class check on the autocomplete field to hopefully not disturb other autocompletes.
(function ($, Drupal) {
'use strict';
/**
* Override drupal selectHandler function
*/
function customSelectHandler(event, ui) {
var valueField = $(event.target);
if($(event.target).hasClass('MYCUSTOM-autocomplete')) {
var valueFieldName = event.target.name+'_value';
if($('input[name='+valueFieldName+']').length > 0) {
valueField = $('input[name='+valueFieldName+']');
// update the labels too
const labels = Drupal.autocomplete.splitValues(event.target.value);
labels.pop();
labels.push(ui.item.label);
event.target.value = labels.join(', ');
}
}
const terms = Drupal.autocomplete.splitValues(valueField.val());
// Remove the current input.
terms.pop();
// Add the selected item.
terms.push(ui.item.value);
valueField.val(terms.join(', '));
// Return false to tell jQuery UI that we've filled in the value already.
return false;
}
Drupal.behaviors.myCustomAutocomplete = {
attach: function(context, settings) {
// overrideattach drupal.autocompletecustom objectselect withhandler customto selectHandlerfields functionwith class
if(typeof Drupal.autocomplete != "undefined") Drupal.autocomplete$('input.optionsMYCUSTOM-autocomplete').autocomplete({
select: =customSelectHandler,
customSelectHandler; });
}
};
})(jQuery, Drupal);
$form['my_field'] = array(
'#type' => 'textfield',
'#title' => 'My Field',
'#attributes' => [
'class'['class' => ['MYCUSTOM-autocomplete'],
],
'#autocomplete_route_name' => 'mymodule.myfield_autocomplete',
'#default_value' => '',
);
// field value
$form['my_field_value'] = array(
'#type' => 'hidden',
'#value' => '', // default value can go here
);