Skip to content

Instantly share code, notes, and snippets.

@vlado
Last active December 27, 2015 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vlado/7336945 to your computer and use it in GitHub Desktop.
Save vlado/7336945 to your computer and use it in GitHub Desktop.
How to add options for tooltips and client side validations to Rails standard form helpers
class TooltipsAndClientSideValidationsFormBuilder > ActionView::Helpers::FormBuilder
def text_field(object_name, method, options = {})
# do nothing if raw option is present (same as rails standard text_field)
unless options[:raw]
extract_tooltip_options! options
extract_validation_options! options
end
super(object_name, method, options = {})
end
# Same for text_area, select, ...
private
def extract_tooltip_options!(options)
tooltip_options = options.delete(:tooltip)
if tooltip_options.is_a? String
options.merge!("data-tooltip-content" => tooltip_options)
elsif tooltip_options.is_a? Hash
options.merge!("data-tooltip-title" => tooltip_options[:title], "data-tooltip-content" => tooltip_options[:content])
end
end
def extract_validation_options!(options)
if options[:validation].is_a? Hash
validation_options = options.delete(:validation)
options.merge!(:required => "required") if validation_options[:required]
# ...
end
end
end
# We can add new view helper
class TooltipsAndClientSideValidationsFormBuilder::ViewHelper
def tooltips_and_csv_form_for(object, options = {}, &block)
options[:builder] = TooltipsAndClientSideValidationsFormBuilder
end
end
ActionView::Base.send(:include, TooltipsAndClientSideValidationsFormBuilder::ViewHelper)
# And it can be used like this
# <%= tooltips_and_csv_form_for @object do |f| %>
# <%= f.text_field :name, :tooltip => 'Some tooltip content' %>
# <%= f.text_field :email, :tooltip => { :title => 'Some tooltip title', :content => 'Some tooltip content' } %>
# <%= f.text_field :name, :validation => { :required => true } %>
# <%= f.submit %>
# <% end %>
# We can then use Javascript tooltip and validation libraries to display tooltips / errors from this attributes
# For tooltips I suggest http://qtip2.com
# For validations I suggest http://jqueryvalidation.org/documentation/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment