Select Field in Phoenix Templates

9.2k views Asked by At

I know Phoenix provides some nice Railsy helpers that can be used in forms like:

  • text_input
  • number_input
  • date_select
  • and submit

but I can't find one for select fields. I've been searching the Phoenix Docs, but couldn't find anything.

So my question is, is there a Phoenix helper for select fields in forms?

2

There are 2 answers

5
Sheharyar On BEST ANSWER

I should've been searching the Phoenix.HTML Docs (Thanks to José for pointing this out!)

The helper for select is:

select(form, field, values, opts \\ [])


Examples:

# Assuming form contains a User model
select(form, :age, 0..120)
#=> <select id="user_age" name="user[age]">
#   <option value="0">0</option>
#   ...
#   <option value="120">120</option>
#   </select>

select(form, :role, ["Admin": "admin", "User": "user"])
#=> <select id="user_role" name="user[role]">
#   <option value="admin">Admin</option>
#   <option value="user">User</option>
#   </select>

select(form, :role, ["Admin": "admin", "User": "user"], prompt: "Choose your role")
#=> <select id="user_role" name="user[role]">
#   <option value="">Choose your role</option>
#   <option value="admin">Admin</option>
#   <option value="user">User</option>
#   </select>
0
José Valim On

It is there, the docs are in the Phoenix.HTML project: http://hexdocs.pm/phoenix_html/