Recently, while creating a subscription checkout form using Stripe Elements, I wanted to list the plans along wth their pricing and details.
The form uses a collection input to list the plans as radio buttons, but the methods in this guide should work for checkboxes and selects.
Here is the input statement that we are working with for starters:
<%= f.input :plan_id,
collection: Plan.published,
as: :radio_buttons %>
Currently, this will display the following label and radio buttons (Note that this label is provided using I18n):
Please select your plan:
○ plan 1
○ plan 2
I already have text with instructions on my form, so I don't want to display the label. Let's remove it by adding label:false.
<%= f.input :plan_id,
collection: Plan.published,
as: :radio_buttons,
label: false %>
Now only display the radio buttons should be displaying:
○ plan 1
○ plan 2
Adding a to_
label
is the easiest and most consistent method as Simple_Form will look for this method before defaulting to using the field name as the label. Adding the to_
label
to your model will reduce the amount of code because you do not need to add any additional options to your input. In this case, the following code was added to plan.rb. For clarity, formatting specific code has been removed:
def to_label
#{self.name} ( #{self.amount}/ #{self.interval}) - #{self.description}
end
Tester ($30/month) - This is a monthly test plan
Passing a block to the label_method helps when you need to override the previous "to_label" method or otherwise need to change the label for a single instance.
Let's do this now using the same snippet that we created at the beginning of the article:
<%= f.input :plan_id,
collection: Plan.published,
as: :radio_buttons,
label: false,
label_method:
lambda {
|plan| "#{plan.name} ( #{plan.amount}/ #{plan.interval}) - #{plan.description}"
} %>
Tester ($30/month) - This is a monthly test plan
As you can see, that's a lot more code to get the same result. Typically its best to just add it to the model, but this method has its use cases as described at the start of this section.
When you use the to_label
method described previously, Simple Form passes the to_label
to the label_method
behind the scenes for you. That's why using this method overrides the to_label
method.