Phoenix form helpers for json/map values


I’m relatively new to Phoenix and haven’t come across the proper way to use Phoenix form helpers to create fields that exist in a Postresql JSONB column.

In my table, I have a column called “details” that I want to store a serialized map of key-value pairs, like:

{"age": 22, "home_town": "Washington, DC"}

According to these docs, I should be doing something like:

<%= form_for @changeset, Routes.user_path(@conn, :create), fn f -> %>
  <%= text_input f, :details %>
<% end %>

How do I adjust the text_input f, :details (maybe like text_input f, :details[age] to specify an input that exists within the details map, that would produce some markup like:

<input type="text" name="user[details][age]" class="form-control border"></input>

I thought something like the “fields_for” helper would achieve this, but it seems to only be used to enter fields for associated resources like a has_many/belongs_to relationship:

<%= form_for @changeset, Routes.user_path(@conn, :create), fn f -> %>
  <%= text_input f, :name %>

  <%= inputs_for f, :permalink, fn fp -> %>
    <%= text_input fp, :url %>
  <% end %>
<% end %>

How should I use the Phoenix form helpers to achieve this? Thanks for any help!

Hello and welcome,

You can use embedded schema, to give some shape to these jsonb fields.

Aka create a embed schema for detail…

Then, You will get validations and form helpers for free.


Embedded schemas is a new concept to me.

I’ll look into that, thank you for the suggestion!

If this can be to any help, I would be happy :slightly_smiling_face:


Great writeup, thanks!