使用 RJS Rails 进行表单验证
我有一个使用remote_form_for 标签提交的表单。
视图
<% form_remote_tag(:url => { :action => 'create' }) do %>
a bunch of fields
<% end %>
控制器
def create
if @greeting.can_save?
respond_to do |format|
format.html {redirect_to board_link(@board)}
format.js #close the iframe and reload the parent
end
else
respond_to do |format|
format.html {redirect_to :action => 'new'}
format.js #show the errors on the form
end
end
end
create.rjs
page << "parent.$.fancybox.close();"
对于使用正确信息提交的表单,一切正常。但我需要显示无效提交的错误消息。
当表单未通过验证时,如何在表单上显示错误消息?
提前致谢。
I have a form that I submit using the remote_form_for tag.
View
<% form_remote_tag(:url => { :action => 'create' }) do %>
a bunch of fields
<% end %>
Controller
def create
if @greeting.can_save?
respond_to do |format|
format.html {redirect_to board_link(@board)}
format.js #close the iframe and reload the parent
end
else
respond_to do |format|
format.html {redirect_to :action => 'new'}
format.js #show the errors on the form
end
end
end
create.rjs
page << "parent.$.fancybox.close();"
All works ok for the form being submitted with correct information. But I need to show error messages for invalid submissions.
How do I show the error messages on the form when the form does not pass validation?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将表单拉出到它自己的部分中,在页面中呈现该部分,为表单提供唯一的 ID。
在表单标签中,您应该以任何您希望的方式呈现错误,无论是列出错误还是向受影响的字段添加类。
现在在 RJS 中执行类似以下操作:
如果出现错误,将重新呈现表单。确保您的 @greeting 实例变量传递到此表单,以便正确填写字段。
Pull the form out into it's own partial, render that partial in your page, giving the form a unique ID.
Within the form tags you should render the errors in any way you wish, whether this is listing them or adding classes to the affected fields.
Now do something like the following in your RJS:
That will re-render the form if there is an error. Make sure your @greeting instance variable is passed to this form so the fields are filled correctly.