8 – Custom autocomplete widget for custom field


I have a custom field type and I’d like to create an autocomplete widget for it. My custom field has two data definitions – target_id and target_bundle, both strings.

I’ve created a custom widget which hides those two fields and adds a text field with #autocomplete_route_name attribute set to controller that is returning json of possible values and that part works fine.

The problem arises when I’m submitting the value. In method massageFormValues of my custom autocomplete widget I’m trying to fill the values of hidden fields (target_id and target_bundle) but those values are left empty no matter what I try. Basically, I’m returning “fixed” $values method argument but those values are not stored later on. So on submit I’m getting form error: An illegal choice has been detected. Please contact the site administrator. because target_id and target_bundle are empty.

Here is what I’m trying to do for better understanding.

      /**
       * {@inheritdoc}
       */
      public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
        // Do not try to save an empty default value for the field.
        foreach (array_keys($values) as $key) {
          if (!empty($values($key)('autocomplete')) && $matches = $this->extractBundleIdFromAutocompleteInput($values($key)('autocomplete'))) {
            $values($key)('target_id') = $matches(1);       // <- not saved
            $values($key)('target_bundle') = $matches(0);   // <- not saved
          }
          if (empty($values($key)('target_id'))) {
            unset($values($key));
          }
        }
        return $values;
      }

Any ideas how to tackle this issue?