Is there a way that I can create a custom form helper so that instead of:
special_field_tag :object, :method
I can achieve something like:
form.special_field :method
Is there a way that I can create a custom form helper so that instead of:
special_field_tag :object, :method
I can achieve something like:
form.special_field :method
Yes, you can add to the FormBuilder class and get access to the object passed into the form_for. I've done this for a lot of things: dates, times, measurements, etc. Heres an example:
Which you can use like this:
There are some instance variables created by Rails that you can access in these helper methods:
I wrote the field_id and field_name methods to create these attributes on the HTML input elements the same way the regular helpers do, I'm sure there is a way to tie into the same methods that Rails uses, but I haven't found it yet.
The sky is the limit on what you can do with these helper methods, they simply return strings. You can create entire HTML tables or pages in one, but you better have a good reason to.
This file should be added in the app/helpers folder
@Tilendor, thanks so much for the pointers. Here is an example of an
enum_select
form tag helper that uses Rails 4.1 enums to automatically populate the options of a select tag:The trickiest construct is
@object.class.send(name.to_s.pluralize)
which produces a hash of available values (e.g.,Company.time_zones
). Putting it inhelpers/application_helper.rb
makes it automatically available. It is used like:Our app was displaying phone numbers in text fields, and we wanted to omit the country code for domestic numbers. I was using form helpers. After reading this and rails source a bit, i came to this solution:
I put this on app/helpers/application_helper.rb and use it like i use
text_field()
helper. Hope this helps someone.