Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Elixir 如何在Phoenix框架中显示字段下的错误消息_Elixir_Phoenix Framework - Fatal编程技术网

Elixir 如何在Phoenix框架中显示字段下的错误消息

Elixir 如何在Phoenix框架中显示字段下的错误消息,elixir,phoenix-framework,Elixir,Phoenix Framework,如何在字段下而不是表单顶部显示表单错误 我如何制作这样的东西: <%= text_input u, :username %> 要呈现类似的内容,如果此字段中有错误-> <div class="field-with-error"> <input type="text"> <span class="error">This username is already taken</span> </div> 此用户名已

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

我如何制作这样的东西:

<%= text_input u, :username %>

要呈现类似的内容,如果此字段中有错误->

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

此用户名已被使用

这些错误都在表单结构的errors字段中,因此您通常可以作为
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 %>