From 9afec1639d42d7d9a496775cd5239fedce27ec22 Mon Sep 17 00:00:00 2001 From: Serj Prikhodko Date: Thu, 22 Feb 2018 21:37:15 +0300 Subject: [PATCH] Let select render default selected option for required field --- actionview/CHANGELOG.md | 21 +++++++++++++++++++ .../lib/action_view/helpers/tags/base.rb | 6 +++++- .../test/template/form_options_helper_test.rb | 10 +++++++++ 3 files changed, 36 insertions(+), 1 deletion(-) diff --git a/actionview/CHANGELOG.md b/actionview/CHANGELOG.md index 896f79fef9..001cc21181 100644 --- a/actionview/CHANGELOG.md +++ b/actionview/CHANGELOG.md @@ -1,5 +1,26 @@ ## Rails 6.0.0.alpha (Unreleased) ## +* Enable select tag helper to mark `prompt` option as `selected` and/or `disabled` for `required` + field. Example: + + select :post, + :category, + ["lifestyle", "programming", "spiritual"], + { selected: "", disabled: "", prompt: "Choose one" }, + { required: true } + + Placeholder option would be selected and disabled. The HTML produced: + + + + For details see GH#32080 + + *Sergey Prikhodko* + * Don't enforce UTF-8 by default With the disabling of TLS 1.0 by most major websites, continuing to run diff --git a/actionview/lib/action_view/helpers/tags/base.rb b/actionview/lib/action_view/helpers/tags/base.rb index fed908fcdb..f1eca2268a 100644 --- a/actionview/lib/action_view/helpers/tags/base.rb +++ b/actionview/lib/action_view/helpers/tags/base.rb @@ -170,7 +170,11 @@ module ActionView option_tags = tag_builder.content_tag_string("option", options[:include_blank].kind_of?(String) ? options[:include_blank] : nil, value: "") + "\n" + option_tags end if value.blank? && options[:prompt] - option_tags = tag_builder.content_tag_string("option", prompt_text(options[:prompt]), value: "") + "\n" + option_tags + tag_options = { value: "" }.tap do |prompt_opts| + prompt_opts[:disabled] = true if options[:disabled] == "" + prompt_opts[:selected] = true if options[:selected] == "" + end + option_tags = tag_builder.content_tag_string("option", prompt_text(options[:prompt]), tag_options) + "\n" + option_tags end option_tags end diff --git a/actionview/test/template/form_options_helper_test.rb b/actionview/test/template/form_options_helper_test.rb index f82eada869..8f796bdb83 100644 --- a/actionview/test/template/form_options_helper_test.rb +++ b/actionview/test/template/form_options_helper_test.rb @@ -511,6 +511,16 @@ class FormOptionsHelperTest < ActionView::TestCase ) end + def test_required_select_with_default_and_selected_placeholder + assert_dom_equal( + [''].join("\n"), + select(:post, :category, ["lifestyle", "programming", "spiritual"], { selected: "", disabled: "", prompt: "Choose one" }, { required: true }) + ) + end + def test_select_with_grouped_collection_as_nested_array @post = Post.new