north_celt

north_celt

Embedded maps in an Ecto schema (and the associated form in Phoenix)

Breaking off a new forum thread from this comment: https://forum.elixirforum.com/t/frustrated-with-the-flip-flops-between-atoms-and-strings-in-phoenix/58672/17 from @sodapopcan

I have a form that works like this:

Here’s a gist for the schema and form:

Apparently, there is a better way with embeds_many and fields_for? I’d really appreciate any guidance.

Most Liked

sodapopcan

sodapopcan

Not to pass the buck, but you would do well to read @LostKobrakai’s article One-to-Many LiveView Forms. It even uses an embedded schema for the (interactive) example!

Your template should end up looking something like this:

<.inputs_for :let={f_data} field={@form[:data]}>
  <.input field={f_data[:year]} label="Year" type="select" options={@year_options} />
  <.input field={f_data[:kind]} label="Year" type="select" options={@kind_options} />
  
  <.input
    field={f_data[:amount]}
    label="Amount"
    type="number"
    required={Ecto.Changeset.get_field(f_data.source, :amount) in [:income, :custom_payment]}
  />

  <.input field={f_data[:description]} label="Description" />
</.inputs_for>

Of course I’m leaving out some of the checks—I just threw in the required check as an example—but the main point is is that there should be no need to add and reference indices nor should you have to manually check for the “selected” option. All that is taken care of for you using an embedded schema with <.inputs_for />.

Some other small notes:

  • You’ll have to switch around how you’re building your year_options and kind_options. The options attribute for <.input type="select" /> takes them in the form of [{"label", :value}]

  • It’s better to pass structs to verified routes instead of the id explicitly:

    ~p"/cases/#{project}/participations/#{participation}"
    

    It probably doesn’t matter for your project but if you ever decide to use another field (like slug) for URL params, all you’d have to do is add @derive {Phoenix.Param, key: :slug} to your schema and everything else will be taken care of.

PS, there is a new way of making forms like this that I still haven’t tried since I haven’t felt the pain of this way yet.

north_celt

north_celt

I don’t see that as passing the buck at all, that’s very helpful. I only attached my existing stuff to illustrate what I was doing.

I didn’t know that about deriving params! Very helpful and something I’m used to from Django with defining get_absolute_url for every model.

Thanks for the in-depth response!

Where Next?

Popular in Questions Top

chokchit
** (DBConnection.ConnectionError) connection not available and request was dropped from queue after 2733ms. You can configure how long re...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
vac
Hi, I’m quite new in Elixir and I’m trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and I...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
JulienCorb
I am trying to implement my new.html.eex file to create new posts on my website. new.html.eex: &lt;h1&gt;Create Post&lt;/h1&gt; &lt;%= ...
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" =&gt; #BSON.ObjectId&lt;58eb1a7a9ad169198c3dXXXX&gt;, "email" =&gt; ...
New

Other popular topics Top

9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 43622 214
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement