I have sub-classed the default form builder to add some additional methods. Sample code is below.
module ApplicationHelper
class AppFormBuilder < ActionView::Helpers::FormBuilder
def coordinates_field(method, options = {})
options[:readonly] = 'true'
....
@template.text_field(@object_name, method, objectify_options(options))
end
end
end
This works well, but to use it I have to change the view code for every form that uses the coordinates_field
method, i.e.,
<%= form_for @object, :builder => ApplicationHelper::AppFormBuilder do |f| %>
...
<% end %>
It sounds like it is theoretically possible to change the default form builder globally (config.action_view.default_form_builder
), but I can't seem to get this to work. This is what I have tried in /config/application.rb
:
module Web
class Application < Rails::Application
...
config.action_view.default_form_builder = "ApplicationHelper::AppFormBuilder"
end
end
Which results in error undefined method 'new' for "ApplicationHelper::AppFormBuilder":String when I hit a view that has a form.
If I instead try this
config.action_view.default_form_builder = ApplicationHelper::AppFormBuilder
I get the error *config.action_view.default_form_builder = ApplicationHelper::AppFormBuilder* when the application starts.
Can anyone provide guidance on how to get this to work?
As mentioned in the official docs, in Rails 5 the correct way is to specify it in a controller. To make it application wide, just set in your ApplicationController
:
class ApplicationController < ActionController::Base
default_form_builder AppFormBuilder
end
This makes much more sense. FormHelpers are part of the view layer and not the application config.
ApplicationHelper::AppFormBuilder
is not required yet at the time application.rb loads. You can try to put this in a separate initializer file (create one in config\initializers):
module Web
class Application
ActionView::Base.default_form_builder = AppFormBuilder
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With