Skip to content

Create an "input" just for displaying custom content (e.g. a link)

Ian Vaughan edited this page May 15, 2014 · 3 revisions

Create an input just for displaying custom content

Purpose

Sometimes you might want to display some custom content (not the attribute value)

Why not use block input

Some might want to use this:

= f.input :password do
  = link_to edit_my_password_path do
    Change Password

But:

  • It's designed to just take the block as input, but the classes like required are still there
  • You still need custom styling (margin-top I think) to make the align look right

Limitation

Since simple form automatically switch to BlockInput when a block is given You need to capture the content you want to display first (capture/content_for/provide), then pass it into the options.

Code

# app/inputs/custom_content_input.rb
class CustomContentInput < SimpleForm::Inputs::Base
  disable :hint

  # You have to pass the content by capturing it as a block into a var, then pass it to the +content+ option
  # It's because simple_form automatically switch to BlockInput when you give a block, there is no way to override it
  def input
    # label code from https://github.com/plataformatec/simple_form/blob/master/lib/simple_form/components/labels.rb#28
    template.content_tag(:span, input_options.delete(:content))
  end

  def additional_classes
    @additional_classes ||= [input_type].compact # original is `[input_type, required_class, readonly_class, disabled_class].compact`
  end
end

Example

  1. Capture the content
  2. as: :custom_content and content: var_of_captured_content
- provide :change_password_link do
  = link_to edit_my_password_path do
    Change Password
= f.input :password, as: :custom_content, content: yield(:change_password_link)