Last active
March 30, 2020 20:17
-
-
Save vmcilwain/86c4e2479e40d847322f19e08216898f to your computer and use it in GitHub Desktop.
Starting a custom form builder in rails 6
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module SomeApp | |
class Application < Rails::Application | |
... | |
config.paths.add Rails.root.join('lib').to_s, autoload: true | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ApplicationController < ActionController::Base | |
default_form_builder ApplicationFormBuilder | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Starting a custom form builder (place in /lib) | |
# based on the rails view book (http://therailsview.com) | |
class ApplicationFormBuilder < ActionView::Helpers::FormBuilder | |
def field_item(attribute, text=nil, &block) | |
@template.content_tag :div, class: 'form-group' do | |
@template.concat @template.label(attribute, (text.blank? ? attribute : text)) | |
yield | |
@template.concat errors_on(attribute) | |
end | |
end | |
def errors_on(attribute) | |
if @object.errors[attribute].any? | |
@template.content_tag(:span, | |
object.errors[:attribute].to_sentence, | |
class: 'error') | |
end | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# place in config/initializers | |
ActionView::Base.field_error_proc = ->(field, instance) {field} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment