Phoenix select input default value

Is there a way to load a Phoenix select input with default value selected?

<%= form_for @conn, page_path(@conn, :index), [method: :post, as: :company], fn f -> %>

  <div class="form-group">
    <%= label f, :company, class: "control-label" %>
    <%= select f, :url,
      key_value_list,
      value: @conn.assigns.desired_value, class: "form-control" %>
    <%= error_tag f, :company %>
  </div>

  <div class="form-group">
    <%= submit "Go", class: "btn btn-primary" %>
  </div>

<% end %>

Yep, it’s in the docs at: https://hexdocs.pm/phoenix_html/Phoenix.HTML.Form.html#select/4

Basically just add a selected: <value> for whichever of the value’s should be default chosen. :slight_smile:

2 Likes

Thanks.
value: also worked.

1 Like

Actually value: will override what is set to always specify this. default: will only specify what you put if the user has not already chosen one (like via params).

I.E:
On first page load then default and value do the same.
If refreshing the page (like submitting but an error happened or something) then default will not be set and whatever the user had set will remain, but if value is set then it will always override the user’s choice so they have to re-select. :slight_smile:

4 Likes