neurodynamic

neurodynamic

Radio buttons using the CoreComponents module in Phoenix 1.7

I’m trying to make a radio button selector for a public/private setting in a Phoenix 1.7 app using LiveView, and I feel like I’m missing something probably really obvious.

Schema:

field(:visibility, Ecto.Enum, values: [:public, :private], default: :private)

Relevant form .heex code:

          <fieldset>
            <.input field={@form[:visibility]}
              id="visibility_public"
              type="radio"
              label="Public"
              value="public"
              />
            <.input field={@form[:visibility]}
              id="visibility_private"
              type="radio"
              label="Private"
              value="private"
              />
          </fieldset>

At the moment, nothing takes when I click on either button. I think I probably need to set the checked attribute somehow but I haven’t been able to work out the right way to do that.

Marked As Solved

codeanpeace

codeanpeace

After some digging, I got it working after realizing the checked attribute isn’t rendered by the default generic input function component and needs to be explicitly set which is what the default checkbox input function component does.
https://github.com/phoenixframework/phoenix/blob/3c5bae721a965e91c0fe61c79a6f4d78fbf3b22f/installer/templates/phx_web/components/core_components.ex#L312-L325

You can either update the generic catchall input function to render the checked attribute or preferably add a radio input function component that renders it.

While that did properly check the other radio buttons upon first click, I noticed that clicking back to the original radio button did not properly check it upon first click. This seems to be because the phx-change form validation handler compares the form params to the original resource assigned to the socket and doesn’t register that change in its response to the client.

I ended up working around this by basing the value of the checked attribute off of both the form field and form params. It needs to be both because the form params are originally empty.

checked={(@form[:visibility].value == :public) || (@form.params["visibility"] == "public")}

checked={(@form[:visibility].value == :private) || (@form.params["visibility"] == "private")}

https://github.com/codeanpeace/live_cal/commit/736b4e307391b68cd600446f30a112f9afeacab8

To clean it up a bit, I added a radio_fieldset function component that generates the necessary radio button inputs based off of the Ecto.Enum field values.

  <.radio_fieldset field={@form[:visibility]}
    options={Ecto.Enum.dump_values(Scheduling.Calendar, :visibility)}
    checked_value={@form.params["visibility"]}
  />

  def radio_fieldset(%{field: %Phoenix.HTML.FormField{}} = assigns) do
    ~H"""
    <div phx-feedback-for={@field.name}>
      <.input :for={option <- @options}
        field={@field}
        id={"#{@field.id}_#{option}"}
        type="radio"
        label={String.capitalize(option)}
        value={option}
        checked={(@checked_value == option) || (@field.value == String.to_atom(option))}
      />
    </div>
    """
  end

https://github.com/codeanpeace/live_cal/commit/11d246d11454a7a8e943685444e0b3d4cb9d3649

10
Post #5

Also Liked

neurodynamic

neurodynamic

omg thank you both of you; this would’ve taken me forever to figure out!

For people looking at this in the future, @codeanpeace’s commit with the fix for the radio input in CoreComponents is here, and that change needs to be made before the changes in this commit will completely work.

neurodynamic

neurodynamic

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
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
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
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: The documentation above suggests that while ...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New

Other popular topics Top

marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
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
johnnyicon
Hi all, I’ve just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I’m trying to use Postgres...
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a &gt; b) do {:ok, "a"} end if (a &lt; b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New

Latest on Elixir Forum

We're in Beta

About us Mission Statement