Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Issues getting data assigned in changeset
defmodule FhForm.Form do
use FhForm.Web, :model
@required_fields ~w(name)a
@optional_fields ~w(redirect_location success_message)a
schema "forms" do
field :name, :string
field :redirect_location, :string
field :success_message, :string
field :url_iden, Ecto.UUID
has_many :form_responses, FhForm.FormResponse
timestamps()
end
@doc """
Builds a changeset based on the `struct` and `params`.
"""
def changeset(struct, params \\ %{}) do
struct
|> cast(params, @required_fields, @optional_fields)
|> validate_required(@required_fields)
end
def create_changeset(struct, params \\ %{}) do
struct
|> changeset(params)
|> put_random_form_identifier()
end
defp put_random_form_identifier(changeset) do
case changeset do
%Ecto.Changeset{valid?: true} ->
put_change(changeset, :url_iden, Ecto.UUID.generate())
_ ->
changeset
end
end
end
defmodule FhForm.FormResponse do
use FhForm.Web, :model
@required_fields ~w{data}a
@optional_fields ~w{ip_address referrer}a
schema "form_responses" do
field :ip_address, :string
field :referrer, :string
field :data, :map
belongs_to :form, FhForm.Form
timestamps()
end
@doc """
Builds a changeset for forms submitted through the HTML form-data API
"""
def api_html_changeset(struct, params \\ %{}) do
struct
|> assign_params_to_data(params)
|> cast(params, @required_fields, @optional_fields)
|> validate_required(@required_fields)
end
defp assign_params_to_data(%Ecto.Changeset{} = cs, params) do
put_change(cs, :data, params)
end
defp assign_params_to_data(cs, _params), do: cs
end
defmodule FhForm.API.HTML.FormResponseController do
use FhForm.Web, :controller
alias FhForm.Form
alias FhForm.FormResponse
def create(conn, params) do
IO.inspect params
form = Repo.get_by(Form, url_iden: params["url_identifier"])
changeset =
form
|> build_assoc(:form_responses)
|> FormResponse.api_html_changeset(params)
case Repo.insert(changeset) do
{:ok, _form_response} ->
conn
|> redirect(to: form_response_path(conn, :success, params["url_identifier"]))
{:error, changeset} ->
IO.inspect changeset
conn
|> send_resp(500, "Oops, something went wrong!")
end
end
def success(conn, _) do
render(conn, "success.html")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.