afcapel / stimulus-autocomplete

Stimulus autocomplete component
MIT License
482 stars 62 forks source link

Send additional parameter to search relation #68

Closed ctilley83 closed 3 years ago

ctilley83 commented 3 years ago

I have two autocomplete fields. One selects a client, the other selects a client's products. Therefore the second autocomplete field depends on the value of the first autocomplete field. I need to send an additional parameter to the backend so I can run a query based off the id of the first autocomplete.

@products = Product.where('product_code like ?', "%#{params[:q]}%").where('client_id = ?,params[:client_id]

Is this possible?

afcapel commented 3 years ago

This is outside the scope of the autocomplete plugin. You'll have to code your on solution to handle this use case although the library already gives you all you need and it should be simple enough.

For example, you can listen to autocomplete.change events from the first autocomplete and when they happen update the data-autocomplete-value attribute in the second. The autocomplete.change event has a details property with the selected value.

// linked_contoller.js

export default class extends Controller {
  static targets = [ "second" ]

  updateSecondAutocomplete = (event) => {
    const newUrl = `/parts?product_id=${event.details.value}`
    this.secondTarget.dataset['autocomplete-url'] = newUrl
  }
}
<div data-controller="linked">
  <div data-controller="autocomplete" data-action="autcomplete.change->linked#updateSecondAutocomplete">
     <!-- First autocomplete -->
  </div>

  <div data-controller="autocomplete" data-linked-target="second">
     <!-- Second autocomplete -->
  </div>
</div>