Symptom

Typing in an autocomplete field intermittently leads to the following fatal JavaScript error:

Uncaught TypeError: suggestions.indexOf is not a function

The error is triggered by showSuggestions() in core/misc/autocomplete.js.

Typing the same input will consistently trigger the error, but there's no obvious pattern for what kind of input triggers it.

Problem

The error is caused by inconsistent JSON structure in AJAX responses. Autocomplete expects an array but is sometimes getting an object with numeric keys.

On the Drupal side, the source of the inconsistency is json_encode(), which is called by Drupal to serialize the JsonResponse for autocomplete. When json_encode() receives an array with sequential keys it serializes as an array. When it receives an array with non-sequential keys it serializes as an object. This behavior was news to me, but it's in the PHP documentation.

ViewsAutocompleteFiltersController::autocomplete() calls array_unique() before returning the JsonResponse, which can *sometimes* lead to non-sequential keys.

Proposed resolution

Always reset array keys before passing autocomplete matches to JsonResponse.

Marking this as major since it compromises the basic functionality of the module.

Support from Acquia helps fund testing for Drupal Acquia logo

Comments

milesw created an issue. See original summary.

milesw’s picture

Status: Active » Needs review
FileSize
542 bytes

Patch to reset array keys.

trzcinski.t@gmail.com’s picture

+++ b/src/Controller/ViewsAutocompleteFiltersController.php
@@ -239,7 +239,7 @@ class ViewsAutocompleteFiltersController implements ContainerInjectionInterface
+    return new JsonResponse(array_values($matches));

Shouldn`t we add a comment here? Something like: "Reset array keys to make sure Drupal encodes results as an array"?

Other than that works perfectly :). Thanks a lot!

BTW - not sure if that should be RTBC or Needs work?

wolffereast’s picture

Patch from #2 worked for me. Added a comment explaining the change. Leaving in Needs Review so someone can take a look at the comment for validity. If that looks good then I think we are ready to move to RTBC

  • vasike committed a4d30bc on 8.x-1.x
    Issue #2665388 by Edith Illyés, YurikK_, vasike: Duplicate values in...
vasike’s picture

Status: Needs review » Fixed

Thank you all for this.

Solve within related issue #2665388: Duplicate values in dropdown on views with duplicates results

However i applied the array_values to array_unique directly.

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.