Skip to content

Commit

Permalink
add radio group
Browse files Browse the repository at this point in the history
  • Loading branch information
woylie committed Dec 10, 2023
1 parent 063d3aa commit a88d04b
Showing 1 changed file with 57 additions and 4 deletions.
61 changes: 57 additions & 4 deletions lib/doggo.ex
Original file line number Diff line number Diff line change
Expand Up @@ -929,8 +929,8 @@ defmodule Doggo do
attr :type, :string,
default: "text",
values: ~w(checkbox color date datetime-local email file hidden month number
password range radio search select switch tel text textarea time url
week)
password range radio radio-group search select switch tel text textarea
time url week)

attr :field, Phoenix.HTML.FormField,
doc: "A form field struct, for example: @form[:name]"
Expand All @@ -956,8 +956,9 @@ defmodule Doggo do

attr :options, :list,
doc: """
A list of options for a select element. See
`Phoenix.HTML.Form.options_for_select/2`.
A list of options for a select element or a radio group. See
`Phoenix.HTML.Form.options_for_select/2`. Note that the radio group does
not support nesting.
"""

attr :multiple, :boolean,
Expand Down Expand Up @@ -1017,6 +1018,29 @@ defmodule Doggo do
"""
end

def input(%{type: "radio-group"} = assigns) do
~H"""
<div class={["field", field_error_class(@errors)]} phx-feedback-for={@name}>
<fieldset class="radio-group">
<legend><%= @label %></legend>
<div>
<.radio
:for={option <- @options}
option={option}
name={@name}
id={@id}
value={@value}
errors={@errors}
description={@description}
/>
</div>
</fieldset>
<.field_errors for={@id} errors={@errors} />
<.field_description for={@id} description={@description} />
</div>
"""
end

def input(%{type: "switch"} = assigns) do
assigns =
assign_new(assigns, :checked, fn ->
Expand Down Expand Up @@ -1145,6 +1169,35 @@ defmodule Doggo do
defp field_error_class([]), do: nil
defp field_error_class(_), do: "has-errors"

defp radio(%{option: {option_label, option_value}} = assigns) do
assigns = assign(assigns, label: option_label, option_value: option_value)

~H"""
<.label>
<input
type="radio"
name={@name}
id={@id <> "_#{@option_value}"}
value={@option_value}
checked={checked?(@option_value, @value)}
aria-describedby={input_aria_describedby(@id, @errors, @description)}
/>
<%= @label %>
</.label>
"""
end

defp checked?(option, value) when is_list(value) do
Phoenix.HTML.html_escape(option) in Enum.map(
value,
&Phoenix.HTML.html_escape/1
)
end

defp checked?(option, value) do
Phoenix.HTML.html_escape(option) == Phoenix.HTML.html_escape(value)
end

@doc """
Renders the label for an input.
"""
Expand Down

0 comments on commit a88d04b

Please sign in to comment.