Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Set selected option based on entity's attribute #69

Merged
merged 4 commits into from
Jul 5, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion Rakefile
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,3 @@ namespace :test do
end

task default: :test

16 changes: 15 additions & 1 deletion lib/hanami/helpers/form_helper/form_builder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -767,16 +767,30 @@ def password_field(name, attributes = {})
# # <option value="it">Italy</option>
# # <option value="us">United States</option>
# # </select>
#
# @example Selected option
# <%=
# # ...
# values = Hash['it' => 'Italy', 'us' => 'United States']
# select :stores, values, options: {selected: book.store}
# %>
#
# # Output:
# # <select name="book[store]" id="book-store">
# # <option value="it" selected="selected">Italy</option>
# # <option value="us">United States</option>
# # </select>
def select(name, values, attributes = {})
options = attributes.delete(:options) { {} }
attributes = { name: _input_name(name), id: _input_id(name) }.merge(attributes)
prompt = options.delete(:prompt)
selected = options.delete(:selected)

super(attributes) do
option(prompt) unless prompt.nil?

values.each do |content, value|
if _value(name) == value
if selected == value || _value(name) == value
option(content, {value: value, selected: SELECTED}.merge(options))
else
option(content, {value: value}.merge(options))
Expand Down
13 changes: 13 additions & 0 deletions test/form_helper_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1268,6 +1268,19 @@
end
end
end

describe "with selected attribute" do
let(:params) { Hash[book: { store: val }] }
let(:val) { 'it' }

it "sets the selected attribute" do
actual = view.form_for(:book, action) do
select :store, values, options: { selected: val }
end.to_s

actual.must_include %(<select name="book[store]" id="book-store">\n<option value="it" selected="selected">Italy</option>\n<option value="us">United States</option>\n</select>)
end
end
end

describe "#datalist" do
Expand Down