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

New grouped_checkbox method for use with Array attributes #863

Merged
merged 1 commit into from
Aug 1, 2022
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
30 changes: 30 additions & 0 deletions spec/lucky/ext/input_helpers_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,17 @@ class InputTestForm
end
end

class ComplexInputTestForm
def names(value : Array(String))
Avram::PermittedAttribute(Array(String)).new(
name: :names,
param: nil,
value: value,
param_key: "bucket"
)
end
end

private class TestPage
include Lucky::HTMLPage

Expand Down Expand Up @@ -106,6 +117,21 @@ describe Lucky::InputHelpers do
end
end

describe "grouped checkboxes" do
it "renders the grouped checkboxes" do
array_field = complex_form.names(["Green", "Sky Blue", "Gold"])
view(&.grouped_checkbox(array_field, "WiggleBrown")).should contain <<-HTML
<input type="checkbox" id="bucket_names_0" name="bucket:names[]" value="WiggleBrown">
HTML
view(&.grouped_checkbox(array_field, "Sky Blue")).should contain <<-HTML
<input type="checkbox" id="bucket_names_0" name="bucket:names[]" value="Sky Blue" checked>
HTML
view(&.grouped_checkbox(array_field, "Sky Blue", attrs: [:required], class: "inline")).should contain <<-HTML
<input type="checkbox" id="bucket_names_0" name="bucket:names[]" value="Sky Blue" class="inline" required checked>
HTML
end
end

describe "radio inputs" do
it "renders radio inputs" do
radio_field = form.status("approved")
Expand Down Expand Up @@ -325,6 +351,10 @@ private def form
InputTestForm.new
end

private def complex_form
ComplexInputTestForm.new
end

private def array_attribute
Avram::PermittedAttribute.new(name: :group, param: nil, value: ["one", "two"], param_key: "key")
end
Expand Down
15 changes: 15 additions & 0 deletions src/lucky/ext/input_helpers.cr
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,21 @@ module Lucky::InputHelpers

generate_helpful_error_for checkbox

def grouped_checkbox(
field : Avram::PermittedAttribute(Array),
checked_value : String,
attrs : Array(Symbol) = [] of Symbol,
**html_options
) : Nil
if field.value.try(&.includes?(checked_value))
attrs = attrs | [:checked]
end
html_options = merge_options(html_options, {"value" => checked_value})
generate_input(field, "checkbox", html_options, attrs: attrs)
end

generate_helpful_error_for grouped_checkbox

# Returns a radio input field.
#
# ```
Expand Down