Reputation: 25994
I have a form where I have a field for an application date. This value is optional, as it can be provided at a later time (i.e. it is not necessarily present when the form is saved).
Using date_select/3
, I'm unable to find a simple way to have this value be optional. Even if default: nil
is provided as an option, the current date is filled in the fields. This is not the desired behavior, as when the user saves the form the value would be updated also.
A field to enter a date, with the possibility of leaving it blank (which would be the default behavior).
You can get a date field for an optional value using the builder option and using empty prompts:
<%= date_select f, :applied_on, builder: fn b -> %>
Date: <%= b.(:day, [prompt: ""]) %>.<%= b.(:month, [prompt: ""]) %>.<%= b.(:year, [prompt: ""]) %>
<% end %>
Isn't there a better, more elegant way to handle optional dates?
Upvotes: 4
Views: 1899
Reputation: 1514
If the field is required or not should handled by your validating, default in model part by ecto
.
From Phoenix.HTML.Form.datetime_select/3:
:year
,:month
,:day
,:hour
,:minute
,:second
- options passed to the underlying select. See select/4 for more information. The available values can be given in :options.
From Phoenix.HTML.Form.select/4:
:prompt - an option to include at the top of the options with the given prompt text
You need only to set the prompt (or other select-specific options) to the field option (:year
, :month
, :day
, :hour
, :minute
and :second
) of date_select
. This should work:
<%= date_select f, :applied_on, year: [prompt: ""], month: [prompt: ""], day: [prompt: ""] %>
This will work for datetime_select/3, date_select/3 and time_select/3.
Hope this helps.
Upvotes: 3