Class: Superform::Rails::Components::Select

Inherits:
Field
  • Object
show all
Defined in:
lib/superform/rails/components/select.rb

Instance Attribute Summary

Attributes inherited from Base

#dom, #field

Instance Method Summary collapse

Methods inherited from Base

#focus

Constructor Details

#initialize(field, options: [], collection: nil, multiple: false, **attributes) ⇒ Select

Returns a new instance of Select.



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/superform/rails/components/select.rb', line 5

def initialize(
  field,
  options: [],
  collection: nil,
  multiple: false,
  **attributes,
  &
)
  super(field, **attributes, &)

  # Handle deprecated collection parameter
  if collection && options.empty?
    warn "[DEPRECATION] Superform::Rails::Components::Select: " \
         "`collection:` keyword is deprecated and will be removed. " \
         "Use positional arguments instead: field.select([1, 'A'], [2, 'B'])"
    options = collection
  end

  @options = options
  @multiple = multiple
end

Instance Method Details

#blank_optionObject



56
57
58
# File 'lib/superform/rails/components/select.rb', line 56

def blank_option(&)
  option(selected: field.value.nil?, &)
end

#false_optionObject



64
65
66
# File 'lib/superform/rails/components/select.rb', line 64

def false_option(&)
  option(selected: field.value == false, value: false.to_s, &)
end

#options(*collection) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
# File 'lib/superform/rails/components/select.rb', line 44

def options(*collection)
  # Handle both single values and arrays (for multiple selects)
  selected_values = Array(field.value)
  map_options(collection).each do |key, value|
    if key.nil?
      blank_option
    else
      option(selected: selected_values.include?(key), value: key) { value }
    end
  end
end

#true_optionObject



60
61
62
# File 'lib/superform/rails/components/select.rb', line 60

def true_option(&)
  option(selected: field.value == true, value: true.to_s, &)
end

#view_template(&block) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/superform/rails/components/select.rb', line 27

def view_template(&block)
  # Hidden input ensures a value is sent even when all options are
  # deselected in a multiple select
  if @multiple
    hidden_name = field.parent.is_a?(Superform::Field) ? dom.name : dom.array_name
    input(type: "hidden", name: hidden_name, value: "")
  end

  if block_given?
    select(**attributes, &block)
  else
    select(**attributes) do
      options(*@options)
    end
  end
end