SimpleForm utilizes i18n files to manage labels, hints, and defaults. The following code customizes the simple_form builder object to examine i18n files for tooltips.

The main goal was to create a uniform method for incorporating content resembling documentation.

This allows the labels to be more concise, and the form field can automatically display a popover when the form-field block is in focus.

One of the significant advantages is that adding text to the translation files will automatically include the tooltip in the form, streamlining the process.

Tooltips act as supplementary documentation for your application, so centralizing all the content simplifies maintenance.

The subsequent code modifies the standard input method in Simple Form, introducing a tooltip to the input wrapper. The tooltip’s text is extracted from the simple_form.yml translation files, with the translation key being the attribute name situated under a tooltip key.

class SimpleForm::FormBuilder
  def input(attribute_name, options = {}, &block)
    options = @defaults.deep_dup.deep_merge(options) if @defaults
    options[:wrapper_html] = (options.dig(:wrapper_html) || {}).deep_merge(tooltip_data(attribute_name, options))

    input = find_input(attribute_name, options, &block)
    wrapper = find_wrapper(input.input_type, options)

    wrapper.render input
  end

  private

  def tooltip_data(attribute_name, options)
    column = find_attribute_column(attribute_name)
    input_type = default_input_type(attribute_name, column, options)
    tooltip_text = SimpleForm::Inputs::Base.new(self, attribute_name, column, input_type, options).send(:translate_from_namespace, :tooltips)

    return {} unless tooltip_text.present?

    {
      data: {
        "bs-trigger" => "hover focus",
        "bs-placement" => "right",
        "bs-toggle" => "popover",
        "bs-content" => tooltip_text
      }
    }
  end
end
en:
  simple_form:
    labels: 
      user: 
        first_name: "Customer First Name"
      company: 
        name: "Company Name"
    hints: 
      user: 
        first_name: "This is the hint text for the first name field."
      company: 
        name: "This is the hint text for the company name field."
    tooltips:
      user: 
        first_name: "This is the tooltip text for the first name field."
      company:
          name: "This is the tooltip text for the company name field."