Phoenix form: How to add 'selected' to an input field of type select

Probably I’m overlooking something very obvious…

How do I add selected to the option field depending on the value of type on rendering the form?

Was looking at the core_components.ex file for some further information but no luck

<.input field={{f, :type}} type="select">
    <:option value="meat"><%= gettext("Meat") %></:option>
    <:option value="vegan"><%= gettext("Vegan") %></:option>
    <:option value="vegetarian"><%= gettext("Vegetarian") %></:option>
</.input>

So lets say with type=“vegan” the HTML supposed to be:

    <:option value="vegan" selected><%= gettext("Vegan") %></:option>
1 Like

You can put selected on the option but you shouldn’t need to.

If you “prefill” your form with a value in type you’ll see that value will be selected.

Also, that’s old syntax for field, what version are you using?

1 Like

This may help you understand the behavior and some of the tricks … am using the new syntax and latest phoenix version …

      <.input field={f[:name]} type="text" label="Name" />
      <.input field={f[:name]} type="select" value={"Vegetarian"}
          options={[{"meat", "Meat"}, {"vegan", "Vegan"}, {"vegetarian", "Vegetarian"}]}>
      </.input>
2 Likes

This is still Phoenix 1.6.16.
I just added a select input to a modal dialog and to my surprise autoselect wasn’t working. This pushed me to use selected for the <option>

Normal text inputs are working flawlessly in that modal dialog.

I just noticed that type is an atom i.e. :vegan
Though even setting a value explicitly like value={"Vegetarian"} and therefore ignoring the actual value of ‘type’ does not select the proper entry.

I’ve got the feeling something else is wrong (or I might have to go the long way to update to the latest phoenix version)

Thanks for the head ups.

After replacing the old core_components.ex file with the latest one and after changing the form syntax as well all is working as expected!

<.input
  field={f[:type]}
  type="select"
  options={[
      {gettext("Salad"), "salad"},
      {gettext("Dessert"), "dessert"},
      [...]          
      {gettext("Vegan"), "vegan"},
      {gettext("Vegetarian"), "vegetarian"},
      {gettext("Info"), "info"},
  ]}
  >
</.input>