2011-11-10 1 views
2

다음과 같은 formtastic 양식이 있습니다 :formtastic 형식으로 필드 유효성 검사 오류 메시지를 표시하려면 어떻게합니까? remote => true?

= semantic_form_for @record, :remote => true, :id => 'my_form', :url => ... 

사용하고 있습니다 : 원격 => 사실, 자바 스크립트에서 컨트롤러 응답을 처리합니다.

$('#my_form') 
    .bind("ajax:beforeSend", function(evt, xhr, settings){ 

    }) 
    .bind("ajax:success", function(evt, data, status, xhr){ 
     $('#response').append(xhr.responseText); 
    }) 
    .bind('ajax:complete', function(evt, xhr, status){ 

    }); 

With : remote => false, my form은 자동으로 필드 유효성 검사 오류를 표시합니다. 예를 들어, 다음과 같이 formtastic 필드 유효성 검사 오류를 표시하려면 어떻게해야합니까? 응답 자바 스크립트에서 자신을 처리?

답변

4

formtastic 폼을보기 만하면됩니다.

게시 된 양식을 처리하는 컨트롤러 작업에서 레코드 저장이 실패 할 때보기를 다시 렌더링 할 수 있습니다. 뷰가 렌더링되면 formtastic은 @record의 errors 필드를보고 유효성 검사 오류를 표시합니다. 저장이 성공하면 빈 문자열을 렌더링하여 성공을 나타낼 수 있습니다. (더 복잡한 응답 방식은 당신이 필요에 따라 수 있습니다.)

def save_record 
    if request.xhr?    # form submitted using remote => true 
     respond_with do |format| 
     format.html do 
      if @record.save 
      # record saved successfully 
      render :text => "" # indicate success with empty response 
      else     # error saving record; send back form with validation errors marked 
      render :template => '/path/to/record_form_view', :layout => false 
      end 
     end 
     end 
     return 
    end 
    #... 
    end 

그런 다음 클라이언트 측 자바 스크립트, 기록 저장에 실패 할 경우 렌더링 된 뷰가 다시 전달과 함께, 기존 양식을 대체 할 수 있습니다에 컨트롤러에서.

// reference: http://www.alfajango.com/blog/rails-3-remote-links-and-forms/ 
function setup_record_form_bindings() { 
    $('#record_form_id') 
    .bind("ajax:beforeSend", function(evt, xhr, settings){ 
    var $submitButton = $(this).find('input[name="commit"]'); 
    $submitButton.get(0).value = "Submitting..."; 
    }) 
    .bind("ajax:success", function(evt, data, status, xhr){  
     if (xhr.responseText === "") {    // successful save 
                // do somethign appropriate here 
     } else {         // error saving 
     $('#record_form_id').remove();   // remove old form, to replace with form in responseText 
     $('#record_form_parent_id').append(xhr.responseText); // should be the newly rendered form (with validation errors shown) 
     setup_record_form_bindings(); 
     } 
    }) 
    .bind('ajax:complete', function(evt, xhr, status){ 
    }); 
} 
setup_record_form_bindings(); 
2

양식을 게시하는 데 자바 스크립트를 사용하고 있기 때문에 데이터를 제출하기 전에 클라이언트 측에서 유효성 검사를 수행 할 것을 제안합니다. 체크 아웃 https://github.com/bcardarella/client_side_validations

+0

감사합니다. 멋진 보석을 언급 해 주셔서 감사합니다 .-) 매력 작품처럼 :-) +1 :-) –

0

오류를 추가하는 데 Formtastic을 사용하기 때문에 에드워즈의 대답이 가장 좋습니다. 필자 (나와 같은)가 필드를 채우는 동안 필드를 추가하고 사용자가 채우는 값을 기반으로 이미지와 데이터를 가져 오는 매우 동적 인 양식을 가진 경우에는 옵션이 아닙니다. 이 최적의 솔루션 결코 Formtastic에 포함 된 로직을 복제하는 것이 비록

https://gist.github.com/2083155/172ce92caa8d4ee738c32e72e27945e17c909428가주의 :

내가 멋지게 오류를 Formtastic이 추가 것 같은 방법을 추가하는 방법을 보여줍니다이 요점을 발견했다. 미래의 어떤 시점에서 오류를 표시하는 Formatic 방식이 변경되면이 코드를 수동으로 조정해야합니다.