Phoenix Framework中如何在字段下显示错误信息

How to show error messages under the field in Phoenix Framework

如何在字段下方而不是在表单顶部显示表单错误?

我怎样才能做出这样的东西:

<%= text_input u, :username %>

渲染这样的东西,如果这个字段有错误 ->

<div class="field-with-error">
  <input type="text">
  <span class="error">This username is already taken</span>
</div>

错误都在表单结构的错误字段中,因此您通常可以通过 f.errors 访问它们。这是一个例子:

<%= if message = f.errors[:username] do %>
  <span><%= translate_error(message) %></span>
<% end %>

解决这个问题的简单辅助方法->

def render_form_field(type, form, field, options \ []) do
  form_field = apply(Phoenix.HTML.Form, type, [form, field, options]) 

  if form.errors[field] do
   wrapper_class = "input field-with-errors"
   error = content_tag(:span, form.errors[field], class: "error")
   content_tag(:div, [form_field, error], class: wrapper_class)
  else
   wrapper_class = "input"
   content_tag(:div, form_field, class: wrapper_class)
  end
end

我显然在这里硬编码了一些东西,但这只是一个例子

然后在模板中简单地执行以下操作 ->

<%= render_form_field :text_input, u, :username, placeholder: "blah blah" %>

现在您可以使用:

<%= error_tag f, :firstname %>