petrus-jvrensburg

petrus-jvrensburg

JSON field input as part of a phoenix form

Just for anyone else running into the same thing: I have a JSON (actually JSONB) field in Postgres that’s defined as a map field on my ecto schema:

field :payload, :map

To make this editable, in form_component.ex I had to specify a textarea input field, e.g.

    <.input
      field={@form[:payload]}
      type="textarea"
      label="Payload"
      autocomplete="off"
      autocorrect="off"
      rows="8"
      value={@form[:payload].value |> Jason.encode!(pretty: true)}
    />

But then I also needed to update the schema’s changeset/2 function like:

  def changeset(event, attrs) do
    attrs =
      with true <- is_binary(attrs["payload"]),
           {:ok, decoded_value} <- Jason.decode(attrs["payload"]) do
        Map.put(attrs, "payload", decoded_value)
      else
        _ -> attrs
      end

    event
    |> cast(attrs, [
      ...
      :payload
    ])
    |> validate_required([
      ...
    ])
  end

What this does is to try converting the incoming text from the textarea field into a map.

If it succeeds, it passes the map along, but if it fails (e.g. while the user is still busy typing and the input doesn’t contain valid json), then the original string is passed along, which causes the cast function to trigger a validation error on the field, because it’s expecting a map.

I’m not sure if there’s a better way, but this is the simplest way that I could come up with that handles the happy path but also triggers a validation error when needed.

First Post!

andreaseriksson

andreaseriksson

Maybe skip (live) validation as you type or have a validation changeset that dosnt include the json field.

Where Next?

Popular in Questions Top

vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
Kurisu
For example for a current url like http://localhost:4000/cosmetic/products?_utf8=✓&amp;query=perfume&amp;page=2, I would like to get: ...
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
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
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
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
jaysoifer
Is there a way to rollback a specific migration and only that one (“skipping” all the other ones)? Would mix ecto.rollback -v 200809061...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New

Other popular topics Top

TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
274 41989 114
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
AngeloChecked
What learn first? Rust or Elixir Hi Elixir community! I’m here because i want learn a new language. I’m a junior developer and mainly i ...
New
gausby
I asked this very same question on twitter and got some interesting feedback, but I thought it would be a good question to ask here as we...
1207 39467 209
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New

Latest on Elixir Forum

We're in Beta

About us Mission Statement