Dear community
I have an Ash resource with money attributes using ash_money
, a thin wrapper around ex_money
. I’ve been looking into the question of Phoenix inputs for money attributes and I think that there may be an opportunity for value to the community in large here.
The “tricky” part here is that the Money
type is a composite of:
- amount and
- currency.
I have managed to dig up a Discord message between @zachdaniel and another user regarding this very issue and that was immensely useful (usually is ), see the code (completely) inspired by Zach’s response in the mentioned exchange below.
I’m looking into the issue of showing validation errors currently. However, I would think that this is an issue that could be generalised by better skilled people. This should be a really common use case since… everything comes down to money in the end
The resource
attributes do
# yada yada
attribute :amount, :money, allow_nil?: false, public?: true
end
The inputs
There are two inputs for the attribute, one for the amount and another for the currency.
Note how the value
attribute is extracted with helper functions.
<.input
id={@form.id <> "_amount_amount"}
name={@form.name <> "[amount][amount]"}
value={amount(@form[:amount].value)}
type="number"
label={gettext("Amount")}
/>
<.input
id={@form.id <> "_amount_currency"}
name={@form.name <> "[amount][currency]"}
value={currency(@form[:amount].value)}
type="select"
options={Money.Currency.known_current_currencies()}
value="EUR"
label={gettext("Currency")}
/>
The code
The amount and currency values are extracted using the helper functions amount/1
and currency/1
respectively.
defp currency(%{currency: currency}), do: currency
defp currency(%{"currency" => currency}), do: currency
defp currency(_value), do: nil
defp amount(%{amount: amount}), do: amount
defp amount(%{"amount" => amount}), do: amount
defp amount(_), do: nil
A general solution to a general problem?
@zachdaniel mentioned this in the subsequent message in the exchange I linked to above:
I think we need to improve the story for this kind of thing in
AshPhoenix
, will need to do some thinking on it. But the above will work thoughThere are other ways to work around these kinds of limitations, so if you get in a pickle what you can do is basically modify the params before they get into your form, and assign some values to correspond to the value.
How would you go about showing errors?
While the big brains ponder the elegant and general solutions to this, I – and I like think others as well – would be very happy to hear any thoughts on how you would handle showing the validation errors for :amount
and :currency
in the example above
Thank you in advance and have a nice day