oatsan

oatsan

Mapping/transforming user input from a form that does not directly map to a schema?

Hi,

I’m new to Phoenix/Ecto and was wondering how to map/transform user input that does not directly map to a schema.

Let’s say I have a schema that represents a Product that is persisted in the database. In that schema is a field that contains the price for that product stored as an integer of the smallest unit of currency, say cents.

When adding a new product, or updating an existing one, it would be better if the user could enter the price in two separate fields as dollars and cents. Instead of total cents.

What is the best/proper way of handling the transformation from dollars and cents to total cents that can be assigned to a Product before inserting it into the database? And then the total cents → dollars + cents when updating an existing Product?

I’ve been reading about creating an embedded schema for this purpose. Or adding virtual fields to the Product schema. Maybe adding a custom Ecto.Type + creating Phoenix form input helpers?

How are these kinds of problems usually solved?

Thanks

Most Liked

feliperenan

feliperenan

Hi :wave:

Ecto Type looks like a good fit for this case. The advantage of it is that is pluggable so you use it on similar fields if you need.

defmodule PriceType do
  use Ecto.Type

  def type, do: :integer

  def cast(%{unit: unit, cents: cents}) do
    {:ok, to_price(unit, cents)}
  end

  # This handle params that comes directly from Phoenix controllers or LiveView.
  def cast(%{"unit" => unit, "cents" => cents}) do
    {:ok, to_price(unit, cents)}
  end

  def cast(price) when is_integer(price) do
    {:ok, price}
  end

  def cast(_), do: :error

  # You might need to handle more cases when unit and cents are not binary.
  defp to_price(unit, cents) when is_binary(unit) and is_binary(cents) do
    String.to_integer(unit <> cents)
  end

  defp to_price(unit, cents) do
    raise "#{unit} and #{cents} are not Strings"
  end

  def load(price) when is_integer(price), do: {:ok, price}

  def dump(price), do: {:ok, price}
end

Other options would be doing it on the changeset level or even on the controller/Live view layer. It really depends on how you want/prefer this data to passed around in your application.

People also like to use Decimal — Decimal v3.1.1 to handle it and there is also this library that you can take some inspiration GitHub - elixirmoney/money: Elixir library for working with Money safer, easier, and fun... Is an interpretation of the Fowler's Money pattern in fun.prog. · GitHub.

It also common to use Money masks on User inputs so that the value comes to your back-end as: $1000,20. This is doable in the same Ecto Type above just adding a new clause to cast/1

Where Next?

Popular in Questions Top

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
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
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
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
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New

Other popular topics Top

electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" =&gt; #BSON.ObjectId&lt;58eb1a7a9ad169198c3dXXXX&gt;, "email" =&gt; ...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
985 44778 311
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
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

We're in Beta

About us Mission Statement