数组模型数据类型

时间:2016-12-31 01:01:58

标签: elixir phoenix-framework

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

以下是模型中的示例字段: field :grateful, {:array, :string}

我尝试过生成这样的字段:

<%= inputs_for f, :grateful, fn fp -> %> <%= text_input fp, :grateful %> <% end %>

但是我得到了这个错误:无法生成输入:感激来自Motivation.DailyPost。检查该字段是否存在,它是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中的数组数据类型?

谢谢!

2 个答案:

答案 0 :(得分:7)

好的,我想我现在知道了。这就是我所做的:

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 %>

方便添加&amp;删除字段我写了这个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);
          }
        })
      }
    });
}

答案 1 :(得分:0)

也许这会为某人节省几个小时或更长时间。您可以将 inputs_for 用于数组类型,如下所示:

<%= f = form_for @changeset, Routes.user_path(@conn, :create), opts %>
  Name: <%= text_input f, :name %>

  <%= for friend_form <- inputs_for(f, :friends) do %>
    # for generating hidden inputs.
    <%= hidden_inputs_for(friend_form) %>
    <%= text_input friend_form, :name %>
  <% end %>
</form>

https://hexdocs.pm/phoenix_html/Phoenix.HTML.Form.html?#inputs_for/2