Hello!
There is a fundamental question related to LiveView forms that I’ve been struggling with. In all the simple form tutorials, the form fields map one-to-one to the fields of the underlying data structure. But in my experience, that’s rarely the case.
Here’s a practical example I’m working on now. I am creating a database of books that also includes audiobooks. The length of a book is specified in the number of pages; the length of an audiobook is specified as hours and minutes, e.g. 12:37.
In the database, I store this as two fields: Integer
that represents the number of pages or minutes, and an atom that specifies which unit is used (:pages
or :minutes
).
But on my form, I want to have a single text input where the user can type “256” or “12:37”.
This means that the structure backing my form must include a string field for the book length, but my DB data structure contains two fields: an integer and an atom.
In turn, this means that I must:
- Translate structures loaded from the database to match what the form expects; and
- Translate data entered by the user in the form to the form expected by the database.
Where should such translation take place? In the Context? In the form component?
More importantly, because forms are always backed by a struct
, do I have to create a separate struct
data type for my form (a struct that will contain length
of type String
)? Is this the expected solution? Or should I do something else, like create a custom type or a Phoenix component?
Thank you in advance,
Michal