Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails 4, change default form builder globally

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?

like image 857
Mike Avatar asked Mar 28 '14 11:03

Mike


2 Answers

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.

like image 179
Vedant Agarwala Avatar answered Jan 04 '23 05:01

Vedant Agarwala


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
like image 26
Max Al Farakh Avatar answered Jan 04 '23 05:01

Max Al Farakh