Created
June 14, 2022 22:39
-
-
Save mplatts/d2cfcb8ef1b6a767449d9cfee2688452 to your computer and use it in GitHub Desktop.
Petal Components Checkbox Group Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule PetalBoilerplateWeb.CheckboxLive do | |
use PetalBoilerplateWeb, :live_view | |
alias PetalBoilerplateWeb.Components.Layouts.SidebarLayout | |
alias Ecto.Changeset | |
@impl true | |
def mount(_params, _session, socket) do | |
{:ok, assign(socket, changeset: build_suggestion_changeset())} | |
end | |
@impl true | |
def render(assigns) do | |
~H""" | |
<.form | |
let={f} | |
as={:form} | |
phx-submit="submit" | |
for={@changeset} | |
> | |
<.form_field | |
type="checkbox_group" | |
form={f} | |
field={:some_field} | |
label="Pick multiple" | |
options={[ | |
{"Option 1", "option_1"}, | |
{"Option 2", "option_2"}, | |
{"Option 3", "option_3"}, | |
{"Option 4", "option_4"} | |
]} | |
/> | |
<div class="flex justify-end"> | |
<.button label="Send" /> | |
</div> | |
</.form> | |
""" | |
end | |
@impl true | |
def handle_event("submit", %{"form" => params}, socket) do | |
IO.inspect(params) | |
changeset = build_suggestion_changeset(params) | |
case validate_suggestion_changeset(changeset) do | |
{:ok, _} -> | |
socket = | |
socket | |
|> put_flash(:info, "Submitted") | |
|> assign(changeset: build_suggestion_changeset()) | |
{:noreply, socket} | |
{:error, changeset} -> | |
{:noreply, assign(socket, changeset: changeset)} | |
end | |
end | |
def build_suggestion_changeset(params \\ %{}) do | |
data = %{ | |
some_field: "" | |
} | |
types = %{ | |
some_field: {:array, :string} | |
} | |
{data, types} | |
|> Changeset.cast(params, Map.keys(types)) | |
|> Changeset.validate_required(:some_field) | |
end | |
def validate_suggestion_changeset(changeset) do | |
Changeset.apply_action(changeset, :validate) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment