如何在模态/弹出窗口中显示表单错误?

时间:2015-12-14 04:33:00

标签: javascript jquery ruby-on-rails ajax ruby-on-rails-4

我在 form.html.erb

里面
<%= form_for([@customer, @error], remote:true) do |f| %>
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
    <h4 class="modal-title" id="myModalLabel">Add New Error</h4>
  </div>
  <div class="modal-body">
    <% if @error.errors.any? %>
      <% @error.errors.full_messages.each do |msg| %>
        <div class="alert alert-danger" role="alert">
          <%= msg %>
        </div>
      <% end %>
    <% end %>

    <label>Note</label>
    <%= f.text_field :note %>

    <br>

    <label>Delay</label>
    <%= f.check_box :is_delay_error %>

    <br>

    <label>Delivery</label>
    <%= f.check_box :is_delivery_error %>

  </div>
  <div class="modal-footer">
    <%= f.submit %>
  </div>
<% end %>

当我使用此AJAX( admin_errors.js.erb )点击视图中的按钮时,我设法显示模态:

$(document).on('click', '.new_error_btn', function(event){
  var customer_id = $(this).attr('data-customer-id');

  $.ajax({
    url: location.origin + '/customers/' + customer_id + '/errors/popup',
    type: "POST" 
  });
});

我的 routes.rb 文件:

resources :customers do
    resources :admin_errors, path: 'errors' do
      post 'popup', on: :collection # to show popup inside errors index
      # example: /customers/:customer_id/errors/popup
    end
end

我的 admin_errors_controller.rb 文件:

    before_action :set_customer, only: [:new, :create, :edit, :popup]

    def create
        @error          = AdminError.new(error_params)
        @error.customer = @customer

        if @error.save
            @saved = true
        else
            @saved = false
            # here I need to show the errors inside form modal
        end
        respond_to :js
    end

    def popup
        @error      = AdminError.new
        respond_to :js
    end

    def set_customer
        @customer = Customer.find(params[:customer_id])
    end

我的 popup.js.erb 文件:

$(".modal-content", "#add_new_error_modal").html("<%= j render('admin_errors/form') %>");
$("#add_new_error_modal").modal("toggle");

最后,我的 create.js.erb 文件:

var saved = <%= @saved %>;

if (saved == true) {
    $("#add_new_error_modal").modal("toggle");
} else {
    console.log("can't save");
}

我有问题在表单模式中显示错误。错误在普通HTML表单中正确显示(使用new操作,在其中部分呈现form

因为我在AdminError模型中有一些验证规则,所以我真的希望在无法保存记录时在表单模式中显示错误消息。

我现在应该怎么做才能显示错误消息?

1 个答案:

答案 0 :(得分:0)

这是我最终如何做到的:

控制器:

def create
        @error          = AdminError.new(error_params)
        @error.customer = @customer

        if @error.save
            # i do something here
            respond_to :js # create.js.erb
        else
            @errors_messages = @error.errors[:base]
            respond_to do |format|
                format.js {
                    render  :template   => "admin_errors/create_failed.js.erb",
                            :layout     => false,
                            :locals     => {:errors_messages => @errors_messages}
                }
            end
        end

    end

<强> create_failed.js.erb

// grab locals from the create action and convert to valid JS object
var errors = <%= errors_messages.to_json.html_safe %>;

// clear #form_errors div 
// very useful for second submit attemps when there are already error alerts 
// inside the div
$("#form_errors").empty();

// loop the error message
for (var i = 0; i < errors.length; i++) {
    $("#form_errors").append("<div class='alert alert-danger'>" + errors[i] + "</div>");
};

// now the #form_errors div
$("#form_errors").show();

模型( admin_error.rb

class AdminError < ActiveRecord::Base
    belongs_to :customer

    validate :has_note
    validate :at_least_one_type

    def at_least_one_type
      if self.is_delay_error == false && self.is_delivery_error == false
        errors[:base] << ("Please choose at least one error type")
      end
    end

    def has_note
        if self.note.blank?
            errors[:base] << ("Note can't be blank")
        end
    end
end

我填写错误消息的表单:

<div class="modal-body">
    <div id="form_errors" style="display:none;">
        <!-- will be populated by the create_failed.js.erb file -->
    </div>
</div>