Hi friends,
Previously we talked about form helpers dealing with models in Form Helpers in Rails Part-2. Today we will continue with Form Builders Customizations.
As we already discussed that objects from form_for and fields_for are instance of FormBuilder class. In addition to that you can also subclass FormBuilder and add the helpers there. For example if previously you have written :
<%= form_for @blog do |f| %>
<%= text_field_with_label f, :title %>
<% end %>
You can write this as:
<%= form_for @blog, builder: LabelBuilder do |f| %>
<%= f.text_field :title %>
<% end %>
#Define Class LabelBuilder as:
class LabelBuilder < ActionView::Helpers::FormBuilder
def text_field(attribute, options={})
label(attribute) + super
end
end
If you require to use it again and again you can also define labeled_form_for that is related to builder: LabelBuilder. So now if you do
<%= render partial: f %>
It will render labelling_form, if 'f' is an instance of class LabelBuilder or FormBuilder will be rendered, if it is an instance of that.
Forms to External Resource:
So many times, we need to send the request to external resources like payment gateways etc. In that case we need to set authenticity_token to the form_tag. If the fields are limited by the third party, then you can set authenticity_token to false, for not generating it. Examples are given below:
<%= form_tag 'http://external-url/form', authenticity_token: 'external-token' do %>
Form contents
<% end %>
#Setting authenticity_token false
<%= form_tag 'http://external-url/form', authenticity_token: false do %>
Form contents
<% end %>
#Same can be used for form_for
<%= form_for @payment, url: external-url, authenticity_token: 'external-token' do |f| %>
Form contents
<% end %>
We will be dealing with complex forms in the next part. To go the next part. Click on the link below:
Form Helpers in Rails Part-4
0 Comment(s)