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

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New

Other Trending Topics Top

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
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
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
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
webofbits
Aludel - LLM Evaluation Workbench Aludel is an embeddable Phoenix LiveView dashboard for evaluating and comparing LLM prompts across mult...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews