-
Notifications
You must be signed in to change notification settings - Fork 177
How To: Make a Custom Form Field
Nathan Colgate edited this page Jul 11, 2018
·
3 revisions
In this example, we'll be making a custom form field to capture price and currency values that could be used with the money-rails gem.
Create a new app/fields/monetize_field.rb
file and add the following contents:
class MonetizeField < Trestle::Form::Field
def field
content_tag :div, class: 'input-group' do
safe_join [
content_tag(:span, builder.object.send(name).currency.symbol, class: 'input-group-addon'),
builder.raw_text_field(name, {class: 'form-control'}),
builder.raw_select("#{name}_currency", ['USD','GBP'], {}, {class: 'form-control', style: '-webkit-appearance:none;'})
]
end
end
end
Then let trestle know about it in config/initializers/trestle.rb
:
Trestle.configure do |config|
# Register a form field type to be made available to the Trestle form builder.
# Field types should conform to the following method definition:
#
# class CustomFormField
# def initialize(builder, template, name, options={}, &block); end
# def render; end
# end
#
# config.form_field :custom, CustomFormField
config.form_field :monetize, MonetizeField
end
Restart your server and you can now use it in your resource config file (i.e. app/admin/blackmails.rb
)
Trestle.resource(:blackmails) do
form do |blackmail|
text_field :victim
text_field :dirt
monetize :price
end
end