Dynamically add options for widget I'm developing a field widget for Drupal 8, similar to 'select' but with more functionality. Since the number of options is large and should be determined after querying an external API I was planning to retrieve options from ajax calls.

However AJAX - How to dynamically add options to select? states that it's not possible. What will be the possible workarounds or solutions?
The solution I used is below for anybody else who might have similar questions.

You can use the autocomplete_route_name property to get the options for autocompletion.

$element += array(
    '#type' =&gt; 'textfield',
    '#default_value' =&gt; $items[$delta]-&gt;value ?: NULL,
    '#autocomplete_route_name' =&gt; 'example.myroute',    //your route name
    '#placeholder' =&gt; $this-&gt;getSetting('placeholder'),
);


The route should be defined in your module_name.routing.yml file

example.myroute:
    path: &lt;url&gt;
    defaults:
      _controller: &lt;controller&gt;::&lt;method&gt;
    requirements:
      _permission: &lt;permission&gt;


Hope this helps :)