Normalizing/sorting an embeds_many list while editing a form

I have an Item record that can have variable pricing over time. It uses has_many to contain a list of date/price combinations:

defmodule MyApp.Price do
  ...
  embedded_schema do
    field :start_date, :date
    field :price, :decimal
  end
  ...
end

In the LiveView, I add a blank price and use inputs_for to edit the prices. Before save and when a date is added, I want to “normalize” the prices: eliminate null/duplicate dates, and sort by date. That’s easy enough for any list but I don’t know where to apply this, because the changeset contains additions but I’m not sure how to update it to replace the entire list of prices.

I found One-to-Many LiveView form by @LostKobrakai, which is admirable in how it figured out how to do it and does a nice job explaining that, but if it’s this complex, I don’t think I want to go that route and I’d rather design around it.

Ordered one-to-many relationships in LiveView forms seems a common use-case, so am I missing something? Thank you for any thoughts, pointers or insights!

Not directly solving your question but maybe pointing you in a different direction for a bit;

AFAIK the article you linked from @LostKobrakai is superseded by updates in ecto described here How to Dynamically Add and Remove Embedded Item Inputs in a Form Using sort_param and drop_param (also available in the live view hexdocs here: Phoenix.Component — Phoenix LiveView v1.0.1 )

HTH

2 Likes

Yes and no – it’s not exactly superseeded. sort_params and drop_params solve a specific subset of what one might want to do based on events coming from the client on a form. But given that subset is all that’s needed it is indeed a easier to implement way to do that.