phx-nooby

phx-nooby

why does @form[:field].value changes from atom to string when other form fields change

At work we started a project and it’s the first time we use elixir phoenix (Live View) for backend and front-end. We have used Elixir Phoenix before but only as backend (json api) with a separate react front-end.

Mostly it’s going well, but we have some “issues” on they way. One of them is the following:

When you have a form (see below for some example code snippets) with a select and the options come from an enum with atoms ([:default, :admin]). We wanted to do some conditional rendering based on the select value.

So for example we have the following html form:

    <div>
      <.header>
        <%= @title %>
        <:subtitle>Use this form to manage user records in your database.</:subtitle>
      </.header>

      <.simple_form
        for={@form}
        id="user-form"
        phx-target={@myself}
        phx-change="validate"
        phx-submit="save"
      >
        <.input field={@form[:name]} type="text" label="Name" />
        <.input field={@form[:age]} type="number" label="Age" />
        <.input
          field={@form[:role]}
          type="select"
          label="Type"
          prompt="choose role"
          options={Ecto.Enum.values(User, :role)}
        />
        <p :if={@form[:role].value === :admin}>Only admins can see this</p>
        <:actions>
          <.button phx-disable-with="Saving...">Save User</.button>
        </:actions>
      </.simple_form>
    </div>

We are checking the form value role, when it’s admin we show some the <p>.
When creating an user above will just work fine.

When you have created an user and want to edit it, that’s where the if statement above will stop working. When changing another field than role or change role and and after that change it back to the initial value it the check will break. Because the following happens:
the role value (@form[:role].value) will change from atom to string (:admin will become “admin”).

I know you can easily change the options to strings and do change the role to a string and that is what we are currently doing. But I don’t understand why it behaves like this. I tried to find my answers in the documentation (Phoenix, Live View, Phoenix.HTML, Ecto docs) but could not find out why it behaves like this and if this is intendent behavior.

So my questions are:

  • Should we handle conditional rendering differently than this approach (like using assign or something else)?
  • Why does it behave like this?

ps

This is my first post, so sorry if it’s not conform the guidelines.
Let me know if it isn’t so I can change it accordingly!

First 4 of 4 Posts Switch mode

tiagorodrigues

tiagorodrigues

I ran into the same issue recently, but instead of atom : string I had integer : string.

What I noticed was that the initial value is coming from the query, which is the value on the database, but if there are changes on the form the value will become an string since all params are strings coming from an HTML form

For example, you might have a field <.input type="float" field={@form[:my_float]>
The initial value if you render from the database would be a float like:

2.49
but if any changes are made to the form then the new value is the changed value, which is “2.49” (it will be converted again when saving).

A simple approach is to verify if any values matches, for example, in your case you could have

<% if @form[:role] in [:admin, "admin"], do: something() %>

you could also assign the value to a new assign and change the assign value in the validation handle_event to ensure you’ll always have an atom

it would be like

def handle_event("validate" params, socket) do
params_role = params["role"]
role = String.to_atom(params_role)

{:noreply, 
socket
|> assing(:role, role)
}
end
LostKobrakai

LostKobrakai

This is because inputs don’t submit native elixir terms and the abstraction needs to support invalid inputs as well.

For changeset based forms the :value key returns in order:

  1. changeset.changes[field] – elixir term, when the form submitted a valid value for the field
  2. changeset.params[field] – raw value as submitted, when the form submitted a invalid value for the field
  3. changeset.data[field] - initial elixir term, when there’s no change submitted (yet)

So at least in the second case you by definition need to deal with the shape the form inputs submit. In case of html forms strings. Also the other directions the abstraction doesn’t know how to convert an elixir value to what would be a “raw value submitted by an input” causing the eventual elixir term to be casted – at least it doesn’t explicitly do so.

phx-nooby

phx-nooby OP

Thanks for the suggestions!

phx-nooby

phx-nooby OP

I do indeed see the following when I do a to_form on the changeset, after the name is changed (validation):

params: %{"name" => "test2", "role" => "admin"},

I understand the behavior now, thanks for the explanation!

— All posts loaded —

Where Next?

Trending in Questions Top

jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
silverdr
Using Phoenix.LiveView.TagEngine as an EEx.Engine is deprecated! To compile HEEx, use Phoenix.LiveView.TagEngine.compile/2 instead. Sta...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
bottlenecked
Hi all, I wanted to ask how the community is dealing with post-release steps. Today we have Ecto migrations, which make sure that the db...
New
michallepicki
I am using Oban and occasionally, shortly after a deployment, a handful of jobs can fail because of dependency on other parts of the syst...
New
rahultumpala
Hello, I have an Elixir backend that implements a custom protocol over TCP. I want to load test the backend and assess the performance o...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
type1fool
I just stumbled on a newly redesigned elixir-lang.org. :tada: It looks like @Software_Mansion did the work, and I think it is generally a...
New
akoutmos
@hugobarauna and I (Alex Koutmos) have been hard at work on writing a book on Nerves that takes you from simply blinking LEDs to building...
New

We're in Beta

About us Mission Statement