diff --git a/spec/lucky/input_helpers_spec.cr b/spec/lucky/input_helpers_spec.cr index 5ad3d3552..05f3a524e 100644 --- a/spec/lucky/input_helpers_spec.cr +++ b/spec/lucky/input_helpers_spec.cr @@ -91,6 +91,9 @@ describe Lucky::InputHelpers do view.checkbox(false_field).to_s.should contain <<-HTML HTML + view.checkbox(false_field, attrs: [:checked]).to_s.should contain <<-HTML + + HTML true_field = form.admin(true) view.checkbox(true_field).to_s.should contain <<-HTML @@ -99,6 +102,9 @@ describe Lucky::InputHelpers do view.checkbox(true_field).to_s.should contain <<-HTML HTML + view.checkbox(true_field, attrs: [:required]).to_s.should contain <<-HTML + + HTML end end @@ -232,6 +238,10 @@ describe Lucky::InputHelpers do view.textarea(form.first_name, rows: 5, cols: 15).to_s.should contain <<-HTML HTML + + view.textarea(form.first_name, attrs: [:required]).to_s.should contain <<-HTML + + HTML end it "renders time inputs" do diff --git a/src/lucky/tags/input_helpers.cr b/src/lucky/tags/input_helpers.cr index af21cf88b..00e7b4d91 100644 --- a/src/lucky/tags/input_helpers.cr +++ b/src/lucky/tags/input_helpers.cr @@ -29,7 +29,13 @@ module Lucky::InputHelpers end generate_helpful_error_for textarea - + + # Returns a textarea field. + # + # ``` + # textarea(attribute) + # # => + # ``` def textarea(field : Avram::PermittedAttribute, **html_options) textarea field.param.to_s, merge_options(html_options, { "id" => input_id(field), @@ -37,7 +43,21 @@ module Lucky::InputHelpers }) end - def checkbox(field : Avram::PermittedAttribute(T), + # Similar to textarea; this allows for Boolean attributes + # through `attrs`. + # + # ``` + # textarea(attribute, attrs: [:required]) + # # => + # ``` + def textarea(field : Avram::PermittedAttribute, attrs : Array(Symbol), **html_options) + textarea field.param.to_s, merge_options(html_options, { + "id" => input_id(field), + "name" => input_name(field), + }), attrs: attrs + end + + def checkbox(field : Avram::PermittedAttribute(T), unchecked_value : String, checked_value : String, **html_options) forall T @@ -59,7 +79,17 @@ module Lucky::InputHelpers generate_input(field, "checkbox", html_options) end - generate_helpful_error_for checkbox + def checkbox(field : Avram::PermittedAttribute(Bool?), attrs : Array(Symbol), **html_options) + unchecked_value = "false" + if field.value + html_options = merge_options(html_options, {"checked" => "true"}) + end + html_options = merge_options(html_options, {"value" => "true"}) + generate_input(field, "hidden", {"id" => ""}, {"value" => unchecked_value}) + generate_input(field, "checkbox", html_options, attrs: attrs) + end + + generate_helpful_error_for checkbox {% for input_type in ["text", "email", "file", "color", "hidden", "number", "url", "search", "range"] %} generate_helpful_error_for {{input_type.id}}_input