Get path from router and redirect after autocomplete selection I have a form that is inflated inside a box.  In that form I have an autocomplete field.  I want to allow the user, when they select an item from the autocomplete's suggestions they are automatically redirected to the appropriate page.

My current idea is to handle this in JS.  But I don't like this as it makes it very difficult to use Drupal's routing system to route -- instead I have to hardcode things, which is bad.

class AutocompleteSearchForm extends FormBase {

  public function getFormId() {
    return 'search_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['search'] = array(
      '#type' =&gt; 'textfield',
      '#title' =&gt; $this-&gt;t('Lookup'),
      '#description' =&gt; $this-&gt;t('Search.'),
      '#placeholder' =&gt; $this-&gt;t('Search'),
      '#autocomplete_route_name' =&gt; 'block.autocomplete.callback',
      '#autocomplete_route_parameters' =&gt; array('name' =&gt; 'name'),
      '#attached' =&gt; array(
        'library' =&gt; array('module/autocomplete'),
      ),
    );
    return $form;
  }

  public function submitForm(array &amp;$form, FormStateInterface $form_state) {
    \Drupal::logger('module')-&gt;warning('form submitted for' . $form_state-&gt;get('search'));
  }
}


And my JS is:

(function ($) {
    $('#edit-search').on('autocompleteclose', function (event, node) {
        var entity_id = $(this).val();
        alert(entity_id);
    });
}(jQuery));


As you can see, I tried to manage this through the callback, but I don't expose a button and this doesn't submit unless the user hits the "enter" button, which isn't exactly intuitive.

Is JS the best way to handle this?  If it is, is there a good way to get access to Drupal's path/router system from JS?
Try to use $build['#attached']['drupalSettings']['vartest'] = $test; to pass $test from PHP to JS. The variable $test contains the Drupal's path/routes.

Replace $build with the variable containing the form or the render array to which the settings are attached. In a form builder or hook_form_alter(), that would be $form.