I have three buttons that call a handle_event
in my liveview. I want to set a custom value to the changeset in the socket.assigns
and it works. However the changeset.changes
value only has valid values, which means the form is wiped of invalid values making a jarring experience for the end user.
def handle_event("change-listing-type", %{"listing-type-id" => listing_type_id}, socket) do
changes =
socket.assigns.listing_changeset.changes
|> Map.put(:listing_type_id, listing_type_id)
socket =
socket
|> assign(:listing_changeset, Listings.change_listing(%Listing{}, changes))
{:noreply, socket}
end
Can I set this custom value on click without wiping away the invalid values?
Here’s my heex template if it helps.
<.form_hidden_input form={f} field={:listing_type_id} />
<div class="form-group">
<label for="propertyType" class="form-label mb-2">Tipo de listado</label>
<div class="grid grid-cols-3 gap-6">
<%= for listing_type <- @listing_types do %>
<div
id={"listing-type-#{listing_type.id}"}
phx-click="change-listing-type"
phx-value-listing-type-id={listing_type.id}
phx-data
class={
"cursor-pointer bg-gray-100 rounded-lg font-medium text-center py-4 #{if @listing_changeset.changes.listing_type_id == listing_type.id, do: "ring-inset ring-2 ring-gray-800"}"
}
>
<%= listing_type.name %>
</div>
<% end %>
</div>
</div>