我正在使用令人惊叹的Phoenix Web Framework,并试图弄清楚如何为具有数组字段的模型创建表单字段。

这是模型中的示例字段:field :grateful, {:array, :string}
我试过生成这样的字段:
<%= inputs_for f, :grateful, fn fp -> %> <%= text_input fp, :grateful %><% end %>
但是我得到了这个错误:无法从Motivation.DailyPost为:grateful生成输入。检查该字段是否存在,并且该字段是embeds_one,embeds_many,has_one,has_many,belongs_to或many_to_many之一

如果我生成这样的字段:<%= text_input fp, :grateful %>,它将生成一个名称为:daily_post[grateful]的表单字段,该字段实际上不起作用。我需要daily_post[grateful][]

下面的代码有效,但是保存后加载数据无效。所有数组值都合并到一个输入字段中。
<div class="form-group" id="grateful-group"> <%= label f, :grateful, class: "control-label" %> <%= text_input f, :grateful, name: "daily_post[grateful][]" %> <%= error_tag f, :grateful %> <input type="button" class="btn btn-success" id="add-grateful" value="add" /> <script> window.onload = () => { $('#add-grateful').click((e) => { $('<input type="text" name="daily_post[grateful][]" />').appendTo("#grateful-group"); }) } </script> </div>
如何在phoenix中正确使用数组数据类型?

谢谢!

最佳答案

好吧,我想我现在明白了。这是我所做的:

defmodule Motivation.InputHelpers do
  use Phoenix.HTML

  def array_input(form, field, attr \\ []) do
    values = Phoenix.HTML.Form.input_value(form, field) || [""]
    id = Phoenix.HTML.Form.input_id(form,field)
    content_tag :ul, id: container_id(id), data: [index: Enum.count(values) ] do
      values
      |> Enum.with_index()
      |> Enum.map(fn {k, v} ->
        form_elements(form, field, k, v)
      end)
    end
  end

  def array_add_button(form, field) do
    id = Phoenix.HTML.Form.input_id(form,field)
    # {:safe, content}
    content = form_elements(form,field,"","__name__")
      |> safe_to_string
      # |> html_escape
    data = [
      prototype: content,
      container: container_id(id)
    ];
    link("Add", to: "#",data: data, class: "add-form-field")
  end

  defp form_elements(form, field, k ,v) do
    type = Phoenix.HTML.Form.input_type(form, field)
    id = Phoenix.HTML.Form.input_id(form,field)
    new_id = id <> "_#{v}"
    input_opts = [
      name: new_field_name(form,field),
      value: k,
      id: new_id
    ]
    content_tag :li do
      [
        apply(Phoenix.HTML.Form, type, [form, field, input_opts]),
        link("Remove", to: "#", data: [id: new_id], class: "remove-form-field")
      ]
    end
  end

  defp container_id(id), do: id <> "_container"

  defp new_field_name(form, field) do
    Phoenix.HTML.Form.input_name(form, field) <> "[]"
  end

end

我将该文件导入到web.ex中,然后可以打印如下数组字段:
<%= array_input f, :grateful %>
我也可以为该字段打印一个添加按钮,如下所示:
<%= array_add_button f, :grateful %>
为了方便添加和删除字段,我编写了以下javascript:
window.onload = () => {
  const removeElement = ({target}) => {
    let el = document.getElementById(target.dataset.id);
    let li = el.parentNode;
    li.parentNode.removeChild(li);
  }
  Array.from(document.querySelectorAll(".remove-form-field"))
    .forEach(el => {
      el.onclick = (e) => {
        removeElement(e);
      }
    });
  Array.from(document.querySelectorAll(".add-form-field"))
    .forEach(el => {
      el.onclick = ({target}) => {
        let container = document.getElementById(target.dataset.container);
        let index = container.dataset.index;
        let newRow = target.dataset.prototype;
        container.insertAdjacentHTML('beforeend', newRow.replace(/__name__/g, index));
        container.dataset.index = parseInt(container.dataset.index) + 1;
        container.querySelectorAll('a.remove-form-field').forEach(el => {
          el.onclick = (e) => {
            removeElement(e);
          }
        })
      }
    });
}

关于elixir - 数组模型数据类型的Phoenix表单字段,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41404526/

10-13 01:15