Last active
August 30, 2021 09:26
-
-
Save mavuio/add2d4a566829a877509a837116689f9 to your computer and use it in GitHub Desktop.
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
# sample mount | |
# @impl true | |
# def mount(params, _session, socket) do | |
# context = %{ | |
# params: params, | |
# lang: "en" | |
# } | |
# initial_form_state = get_initial_form_state(socket.assigns) | |
# {:ok, | |
# socket | |
# |> assign( | |
# context: context, | |
# form_state: initial_form_state, | |
# saved_form_state: nil, | |
# form_changeset: get_form_changeset(initial_form_state, %{}), | |
# )} | |
# end | |
def handle_event("save", %{"form_data" => incoming_data}, socket) do | |
get_form_changeset(socket.assigns.form_state, incoming_data) | |
|> Ecto.Changeset.apply_action(:update) | |
|> case do | |
{:ok, form_state_with_changes_applied} -> | |
form_state_with_changes_applied |> MavuUtils.log("form_state_with_changes_applied", :info) | |
form_state = get_initial_form_state(socket.assigns) | |
{:noreply, | |
Phoenix.LiveView.assign(socket, | |
saved_form_state: form_state_with_changes_applied, | |
form_state: form_state, | |
form_changeset: get_form_changeset(form_state, socket.assigns[:context]) | |
)} | |
{:error, %Ecto.Changeset{} = changeset_with_errors} -> | |
{:noreply, Phoenix.LiveView.assign(socket, form_changeset: changeset_with_errors)} | |
end | |
end | |
@impl true | |
def handle_event("validate", %{"form_data" => incoming_data} = _msg, socket) do | |
incoming_data |> MavuUtils.log("mwuits-debug 2021-08-30_10:16 ", :info) | |
validated_changeset = | |
get_form_changeset(socket.assigns.form_state, incoming_data) | |
|> Map.put(:action, :validate) | |
|> MavuUtils.log("mwuits-debug 2021-08-30_10:09 B ", :info) | |
{:noreply, assign(socket, form_changeset: validated_changeset)} | |
end | |
def get_form_changeset(initial_data, changes, _context \\ %{}) do | |
types = | |
~w(keyword)a | |
|> Enum.map(&{&1, :string}) | |
|> Map.new() | |
schemaless_rec = {initial_data, types} | |
Ecto.Changeset.cast(schemaless_rec, changes, Map.keys(types), empty_values: []) | |
|> Ecto.Changeset.validate_length(:keyword, max: 10) | |
|> Ecto.Changeset.validate_format(:keyword, ~r/^[a-z_ -.]*$/, | |
message: "only lowercase alpha allowed" | |
) | |
end | |
def get_initial_form_state(_assigns) do | |
%{ | |
keyword: "foo" | |
} | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment