[英]Phoenix Framework - How to populate a map field through a form_for?
我正在嘗試填充一個字段 :params (來自模型/架構),它是一個地圖。 我有一個可用的 form_for,我想通過復選框填充這個 :params 映射,以便在提交表單時控制器將收到類似%{... params => %{"param1" => "true", "param2" => "false"}} ...
我看過inputs_for,但這似乎並沒有做我需要的,因為它依賴於嵌套模式和模型,這意味着我需要為每組新參數創建一個新模式(我需要一些通用的如果參數更改,則不需要更改源代碼)。
<%= form_for @changeset, audit_audit_path(@conn, :new_tool_request, @audit.id),
fn f -> %>
<%= render LayoutView, "changeset_error.html", conn: @conn, changeset: @changeset, f: f %>
<div class="form-group"><label>Tool</label>
<%= select f, :toolname, tools %>
</div>
<div class="form-group"><label>Parameter 1</label>
<%= checkbox f, :param1 %>
</div>
<div class="form-group"><label>Parameter 2</label>
<%= checkbox f, :param2 %>
</div>
<div class="form-group"><label>Date of Execution</label>
<%= datetime_select f, :date %>
</div>
<div class="form-group">
<%= hidden_input f, :audit_id, value: @audit.id %>
</div>
<%= submit "Request", class: "btn btn-primary" %>
<% end %>
因此,我不需要為param1
和param2
設置這些復選框,而是需要將所有這些參數放入映射中。 如果使用不同的參數復選框呈現另一個表單,則它必須在與架構沒有任何關系的情況下進行填充。
謝謝!
事實上,我認為,如果在這樣的情況下:
schema "checkmapss" do
field :name, :string
field :options, :map
timestamps()
end
我們只需要在form.html.eex中做:
<div class="form-group">
<%= label f, :options, class: "control-label" %>
<%= text_input f, :options_one, name: "checkmap[options][one]", class: "form-control" %>
<%= error_tag f, :options %>
</div>
<div class="form-group">
<%= label f, :options, class: "control-label" %>
<%= text_input f, :options_two, name: "checkmap[options][two]", class: "form-control" %>
<%= error_tag f, :options %>
</div>
然后 changeset 函數將幫助我們完成其他事情。
我遇到了同樣的問題,但使用簡單的 HTML 表單和長生不老葯,ecto 模式匹配讓它可以很好地輕松工作。
Ecto 架構定義
schema "stuff" do
field :name, :string
field :settings, :map
end
控制器或資源:edit
操作
changeset = StuffContext.change_stuff(stuff)
在您的模板/表單中
<%= form_for @changeset, Routes.stuff_path(@conn, :save, @stuff), fn f -> %>
...
<%= label f, :currency %>
<%= text_input f, :stuff_currency, name: "stuff[settings][currency]",
value: @stuff.settings["currency"], required: true %>
<%= error_tag f, :settings %> <-- Important errors come from ecto validation logic we put into changeset, not the made up currency
...
然后在您的控制器中:save
操作
def save(conn, %{"id" => id, "stuff" => stuff_params}) do
stuff = StuffContext.get(id)
...
IO.inspect(stuff_params) ->
%{"name" => "welcome", "settings" => %{"currency" => "USD"}}
...
StuffContext.update_stuff(stuff, stuff_params)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.