josefarias / hotwire_combobox

An accessible autocomplete for Ruby on Rails.
https://hotwirecombobox.com
MIT License
496 stars 32 forks source link

Custom partial: access both display and value #101

Closed Spone closed 7 months ago

Spone commented 7 months ago

Use case

I'd like to have the following rendering:

image

Current implementation

# Model
class Wine
  enum :color, {red: 0, white: 1, rose: 2}, suffix: true
end
<%# View %>
<%= f.combobox :color, Wine.colors, render_in: { partial: "colors/color" } %>
<%# Partial %>
<span class="color-dot" style="--color: var(--#{color})"></span>
<%= Wine.human_attribute_name("color.#{color}") %>

Problems

  1. When I'm choosing an option, the input displays the value, but I'd rather keep the display.

image

So instead of red I would see Rouge (no need to keep the colored dot, but that would be a nice plus.

  1. I'd like to avoid duplicating logic in my partial, so I'd rather pass a Hash, then access display and value instead of just the value:
# Model
class Wine
  enum :color, {red: 0, white: 1, rose: 2}, suffix: true

  def self.human_colors
    colors.to_h { |k, _v| [human_attribute_name("color.#{k}"), k] }
  end
end
<%# View %>
<%= f.combobox :color, Wine.human_colors, render_in: { partial: "colors/color" } %>
<%# Partial %>
<span class="color-dot" style="--color: var(--#{value})"></span>
<%= display %>
josefarias commented 7 months ago

Great idea! Thanks! Implemented in https://github.com/josefarias/hotwire_combobox/pull/107. See PR for instructions.

Spone commented 7 months ago

Awesome!

image

image