phx-nooby

phx-nooby

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!

Showing Posts 1 to 4

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? Top

Trending in Questions Top

katta
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
achenet
Hello, I’m trying to build a basic Phoenix web-app, and I’d like to use Tailwind. However, when I launch mix phx.server, I get an error...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
Cxx-mlr
I’m working on a small exercise involving update_in/3, and I came up with this solution: data = %{ name: "Periodic Table", category:...
New
ChrisAmelia
I’ve got trouble wrapping my head around the order in which functions are called in this snippet (from Phoenix’s authentication): toke...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
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
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews