Toggle refinement based on attribute value

Hi everyone
Per design I need to add many refinements to my search and I don’t really know if the approach I’m following is correct
I need help for building a custom refinement that filters the results based on the value of the ‘attribute’ I pass to it

At the moment I’m using the search.addWidgets([addStuff…]) approch

search.addWidgets([
 toggleRefinement({
  container: '#toggle-refinement-man',
  attribute: 'man',
 }),
])

And I would like to have something like this

search.addWidgets([
 toggleRefinement({
  container: '#toggle-refinement-man',
  attribute: 'man',
  filters: 'Gender:"Man"'
 }),
])

However the ‘filters’ feature is not available at this point but only on index.search() call

I need to know what is the best approach to implement this
I’m asking myself if it would be better to implement everything in a custom way bypassing the search.addWidgets([addStuff…]) approch

Thanks

Hey Gaetano,

From what I’m understanding of your issue:

  • You have a man attribute in your records. This attribute is a boolean.
  • You have a Gender attribute in your records. One possible value of this attribute is "Man".
  • When toggling the toggleRefinement which is currently set on the man attribute, you’d like to set a filter to 'Gender:"Man"' for your search results.

Is it all correct?

The toggleRefinement widget is set to automatically apply a filter based on the attribute you passed. In your case, when checking the box, it will set a filter to all records where attribute man is true. Why do you need to have a custom filter on Gender? Wouldn’t the filter on man=true be enough?

Now if you need to apply more complex logic for your filters you can do so using the onStateChange option on the instantsearch instance, but whenever you start using this option, the instance becomes controlled. This means you become responsible for updating the UI state with setUiState.

Before going this route, don’t hesitate to tell us more about your use case so we can determine what’s the most appropriate solution.