简体   繁体   English

Elixir / Phoenix通过hidden_​​input传递当前日期

[英]Elixir/Phoenix passing current date through hidden_input

I need to pass the current date into the form in the HTML so then the controller will use that info. 我需要将当前日期传递到HTML中的表单中,然后控制器将使用该信息。

<%= form_for @changeset, statistic_path(@conn, :create), fn f -> %>
<%= hidden_input f, :date_from, value: @time_insert.year, class: "form-control" %>
<%= hidden_input f, :date_to, class: "form-control" %>
<%= submit "today", class: "btn btn-primary" %>
<% end %>

Here I have @time_insert, which is: 这里我有@time_insert,它是:

time = Ecto.DateTime.cast!(:calendar.local_time())
time_insert = Ecto.DateTime.cast!({{time.year, time.month, time.day}, {time.hour, time.min, time.sec, time.usec}})

and my controller for the form: 和我的控制器的形式:

def create(conn, %{"statistic" => %{"date_from" => %{"day" => day_from, "month" => month_from, "year" => year_from}, "date_to" => %{"day" => day_to, "month" => month_to, "year" => year_to}}}) do

  date_from = Ecto.DateTime.cast!({{year_from, month_from, day_from}, {0, 0, 0, 0}})
  date_to = Ecto.DateTime.cast!({{year_to, month_to, day_to}, {23, 59, 59, 0}})

I'm struggling with the syntax/way to push current date from @time_insert into the form to use in controller. 我正在努力使用语法/方法将当前日期从@time_insert推送到要在控制器中使用的表单中。 Appreciate any advice. 感谢任何建议。 I've checked the Phoenix.Html.Form but still can't make it work:( 我已经检查了Phoenix.Html.Form,但仍然无法使其工作:(

PS: I made map in controller that way, because I use following variables: date_from, date_to for further query. PS:我在控制器中制作地图,因为我使用以下变量:date_from,date_to进一步查询。

As you mentioned in your comment, if you want to set a "Today" option in the form, you still shouldn't have to set the date, especially on the client side. 正如您在评论中提到的,如果您想在表单中设置“今天”选项,您仍然不必设置日期,尤其是在客户端。

One way you can do this is to set a flag and look for it in the controller. 您可以这样做的一种方法是设置一个标志并在控制器中查找它。 If it's present, filter the search by today's date. 如果它存在,请按今天的日期过滤搜索。 Otherwise, fall back to the provided range or do not filter. 否则,回退到提供的范围或不过滤。

In pseudo-code: 在伪代码中:

def create(conn, %{ "foo_params" => foo_params } do
  case date_range = Map.get(foo_params, "today")
    {:ok, _today} ->
      # filter by today
  _ ->
    # handle other scenarios
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM