From 2ca38cd278608e359c07e9c1d65bb32d7a5a7517 Mon Sep 17 00:00:00 2001 From: Mantas Date: Sun, 26 Jan 2014 15:09:19 +0200 Subject: [PATCH] Allows custom errors #761 --- lib/simple_form/components/errors.rb | 8 ++++++-- lib/simple_form/inputs/base.rb | 2 +- test/form_builder/error_test.rb | 13 +++++++++++++ 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/lib/simple_form/components/errors.rb b/lib/simple_form/components/errors.rb index aad48335..697c30b2 100644 --- a/lib/simple_form/components/errors.rb +++ b/lib/simple_form/components/errors.rb @@ -5,8 +5,12 @@ module SimpleForm error_text if has_errors? end + def has_error_in_options? + options[:error] && !options[:error].nil? + end + def has_errors? - object && object.respond_to?(:errors) && errors.present? + (object && object.respond_to?(:errors) && errors.present?) || has_error_in_options? end protected @@ -24,7 +28,7 @@ module SimpleForm end def errors_on_attribute - object.errors[attribute_name] + has_error_in_options? ? [options[:error]] : object.errors[attribute_name] end def errors_on_association diff --git a/lib/simple_form/inputs/base.rb b/lib/simple_form/inputs/base.rb index e9eb3def..99795033 100644 --- a/lib/simple_form/inputs/base.rb +++ b/lib/simple_form/inputs/base.rb @@ -45,7 +45,7 @@ module SimpleForm end # Always enabled. - enable :hint + enable :hint, :error # Usually disabled, needs to be enabled explicitly passing true as option. disable :maxlength, :placeholder, :pattern, :min_max diff --git a/test/form_builder/error_test.rb b/test/form_builder/error_test.rb index 06a024a7..f25606f2 100644 --- a/test/form_builder/error_test.rb +++ b/test/form_builder/error_test.rb @@ -14,6 +14,10 @@ class ErrorTest < ActionView::TestCase end end + def with_custom_error_for(object, *args) + with_form_for(object, *args) + end + test 'error should not generate content for attribute without errors' do with_error_for @user, :active assert_no_select 'span.error' @@ -123,4 +127,13 @@ class ErrorTest < ActionView::TestCase assert_select 'span.omg_error', "can't be blank" end end + + # CUSTOM ERRORS + + test 'input with custom error works' do + error_text = "Super User Name! can't be blank" + with_custom_error_for(@user, :name, error: error_text) + + assert_select 'span.error', "#{error_text}" + end end