I have a checkbox defined in my html.heex as follows:
<.input
type="checkbox"
label="Don't use contributor rank icon"
name="disable_contributor_rank"
value="disable_contributor_rank"
phx-change="toggle-disable-contributor-rank"
/>
I have a handler defined as follows:
@impl true
def handle_event("toggle-disable-contributor-rank", event, socket) do
IO.inspect("TEST", label: "test", charlists: :as_lists)
[key] = event["_target"]
_value = event[key]
{:noreply, socket}
end
It doesn’t get called. Also how do I get the checked value in my handler?
Is the input nested within a form?
1 Like
I tried to wrap in form and still nothing logged in handler
<form method="post" class="">
<h4>Contributor Rank Icon</h4>
<.input
type="checkbox"
label="Hide contributor rank icon"
name="disable_contributor_rank"
value="disable_contributor_rank"
checked={@hide_contributor_rank}
phx-change="toggle-disable-contributor-rank"
/>
</form>
OK Looking at core_components I see this
def input(%{type: "checkbox", value: value} = assigns) do
assigns =
assign_new(assigns, :checked, fn -> Phoenix.HTML.Form.normalize_value("checkbox", value) end)
~H"""
<div class="form-check">
<input name={@name} type="hidden" value="false" />
<input
name={@name}
id={@id}
class="form-check-input"
type="checkbox"
value="true"
checked={@checked}
/>
<label class="form-check-label" for={@id}>
<strong><%= @label %></strong><%= assigns[:text] %>
<%= if assigns[:description] do %>
<%= assigns[:description] %>
<% end %>
</label>
</div>
"""
end
I don’t see that it actually handles phx-change
Is disable_contributor_rank
an assign? You’re currently passing it in just as a string.
value={@disable_contributor_rank}
Also I think you don’t want that form method.You’re wanting your handler called right away, not to do this as an eventual POST.
Ah yeah, you’re using a <.input
component. You’ll either need to modify your core_components to pass on phx-change
, or just use a regular input
component.
Also you could put the phx-change
on the form instead.
From what I’ve read about checkboxes, value is supposed to be a string:
Source
It looks like core_components sets value to be “true”
You are probably right that I don’t need the form wrapper as I’m handling straight away and not on submit.
EDIT: Tested without form wrapper and it doesn’t work. So I do need it.
Tested using regular <input
and it works
Ah yep, you’re right. I was thinking of the <.input
that coerces value over to checked
.