Phoenix.HTML.Form不会从变更集中获取错误

时间:2017-04-17 13:21:10

标签: elixir phoenix-framework

我的模板代码如下所示:

<%= form_for @changeset, @action, fn f -> %>
  <%= if Enum.any?(f.errors) do %>
    <%= for {attr, message} <- f.errors do %>
      <li><%= humanize(attr) %> <%= message %></li>
    <% end %>
  <% end %>
<% end %>

但即使变更集包含错误,也不会打印错误。这是检查的表单结构。请注意,即使错误列表是根据变更集构建的,但错误列表仍为空。

%Phoenix.HTML.Form{data: %BlogPhoenix.Comment{__meta__: #Ecto.Schema.Metadata<:built, "comments">,
  content: nil, id: nil, inserted_at: nil, name: nil, post_id: nil,
  posts: #Ecto.Association.NotLoaded<association :posts is not loaded>,
  updated_at: nil}, errors: [], hidden: [], id: "comment",
 impl: Phoenix.HTML.FormData.Ecto.Changeset, index: nil, name: "comment",
 options: [method: "post"],
 params: %{"content" => nil, "name" => nil, "post_id" => "1"},
 source: #Ecto.Changeset<action: nil, changes: %{},
  errors: [name: {"can't be blank", [validation: :required]},
   content: {"can't be blank", [validation: :required]}],
  data: #BlogPhoenix.Comment<>, valid?: false>}

这里发生了什么?不应该填充此错误列表吗?

1 个答案:

答案 0 :(得分:7)

你的变更集:行动是零,这是隐藏错误的结果(see source)。

Ecto.Changeset docs(在“更改集操作”标题下)声明:

  

例如,像Phoenix这样的框架使用changeset.action的值来决定是否应该在给定表单上显示错误。

上述文档提出了这种方法:

changeset = User.changeset(%User{}, %{age: 42, email: "mary@example.com"})

# Since we don't plan to call Repo.insert/2 or similar, we
# need to mimic part of its behaviour, which is to check if
# the changeset is valid and set its action accordingly if not.
if changeset.valid? do
  ... success case ...
else
  changeset = %{changeset | action: :insert} # action can be anything
  ... failure case ...
end