danubiolima

danubiolima

How to use Liveview Forms with nested schemas

I’m new in Phoenix Liveview and I’m trying to create a quiz app to studying and pratice that framework.

My app currently have three simple ecto schemas (using postgres as database):

Form schema:

schema "form" do
    field :name, :string

    has_many :questions, Question

    timestamps(type: :utc_datetime)
 end

Question schema:

schema "question" do
    field :type, :string, default: "text"
    field :title, :string

    belongs_to :form, Form
    has_many :item, Item

    timestamps(type: :utc_datetime)
 end

Item schema:

schema "item" do
    field :type, :string, default: "text"
    field :title, :string

    belongs_to :question, Question

    timestamps(type: :utc_datetime)
 end

My idea with that schemas is build a simple app where students can acess forms and respond to questions to pratice they knowledgments in web development and related fields.

I have a LiveView questions.ex that lists the questions of a form:

defmodule QuizAppWeb.QuizLive.Questions do
  use QuizAppWeb, :live_view

  alias QuizApp.Quiz
  alias QuizApp.Quiz.Form

  alias QuizApp.Repo

  def render(assigns) do
    ~H"""
    <div class="grid grid-cols-1 gap-10">
      <%= for question <- @form.questions do %>
        <div class="bg-blue-200 rounded-2xl shadow-md p-4">
          <h1 class="text-lg font-bold mb-2"><%= question.title %></h1>
          <div class="bg-gray-300 shadow-md p-4">
            <%= for item <- question.item do %>
              <div class="p-2">
                <input type="radio" id="{item.id}" name="#{item.id}-item" value="{item.id}" />
                <label for="{item.id}"><%= item.title %></label>
              </div>
            <% end %>
          </div>
        </div>
      <% end %>

      <.button phx-click="submit_answers">Enviar</.button>
    </div>
    """
  end

  def mount(%{"form_id" => form_id} = _params, _session, socket) do
    questions = Quiz.get_questions(form_id)
    form = Repo.get(Form, form_id) |> Repo.preload(questions: :item)
    changeset = Form.changeset(form, %{})
    {:ok, assign(socket, questions: questions, form: form, changeset: changeset)}
  end

  def handle_event("submit_answers", %{"form_id" => _form_id} = _params, socket) do
    {:noreply, socket}
  end
end

The interface is like this:

I know, the design is not beautiful, but I’ll improve it soon :joy:

The liveview above does not work and I can’t receive the item that user choices. When I click in a item of second question, the items in firsts question unmark automatically.

What is a simple and efficient way to render and store the user answers of the form?

Thank you!

Most Liked

windexoriginal

windexoriginal

I think the first step would be to get things setup within a form component: phoenix form bindings

Right now it looks like when you click the Enviar button to trigger “submit_answers” you will not be getting the values in your inputs because they are not wrapped in a form. You can confirm this by inspecting the params passed in to your handle_event function.

If you are having issues fitting your form around your schema you should consider making a separate changeset that represents your form. That way you don’t have to marry your UI to your schema.

Last Post!

LostKobrakai

LostKobrakai

The changeset of the form should be based on the schema of the submitted data, not on the details about of the form. Most offen those are dynamic though, which can be problematic with changesets, which use atoms for fields - and you generally want to avoid creating atoms from user input in a system.

Where Next?

Trending in Questions Top

jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
silverdr
Using Phoenix.LiveView.TagEngine as an EEx.Engine is deprecated! To compile HEEx, use Phoenix.LiveView.TagEngine.compile/2 instead. Sta...
New
saveman71
Hello ! We want new/edit form pages to POST/PUT to their own URL rather than the resources REST defaults (post /things, put /things/:id)...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
bottlenecked
Hi all, I wanted to ask how the community is dealing with post-release steps. Today we have Ecto migrations, which make sure that the db...
New
michallepicki
I am using Oban and occasionally, shortly after a deployment, a handful of jobs can fail because of dependency on other parts of the syst...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
type1fool
I just stumbled on a newly redesigned elixir-lang.org. :tada: It looks like @Software_Mansion did the work, and I think it is generally a...
New
akoutmos
@hugobarauna and I (Alex Koutmos) have been hard at work on writing a book on Nerves that takes you from simply blinking LEDs to building...
New

We're in Beta

About us Mission Statement