Phoenix Framework - 如何通过 form_for 填充地图字段?

Sas*_*eca 6 elixir ecto phoenix-framework

我正在尝试填充一个字段 :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 %>
Run Code Online (Sandbox Code Playgroud)

因此,我需要将所有这些参数放入地图中,而不是为param1和设置这些复选框param2。如果使用不同的参数复选框呈现另一个表单,则它必须在与架构没有任何关系的情况下进行填充。

谢谢!

Bin*_*abs 3

其实我觉得,如果是这样的情况:

  schema "checkmapss" do
    field :name, :string
    field :options, :map

    timestamps()
  end
Run Code Online (Sandbox Code Playgroud)

我们只需要做的是在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>
Run Code Online (Sandbox Code Playgroud)

然后changeset函数将帮助我们完成其他事情。