Sherif Elkassaby
Sherif Elkassaby

Reputation: 171

how to add extra data to simple_form custom wrapper :icon

The bellow image shows what i have done with html without simple form .

This is the old code:

<%= f.input :name  %>
<i class="fa fa-question-circle" data-toggle="popover" data-placement="top" data-content="content of the popover" data-trigger="hover"></i>

the screen shot:

enter image description here

It is working perfectly but i want to enhance this code using simple form so i have created a custom wrapper but i failed to send the data like the toggle and trigger .etc to the icon in the wrapper

i have tried this but not working properly this is my form :

<%= simple_form_for(@product ,wrapper: :product_form) do |f| %>
  <div class="form-inputs">
    <%= f.input :name , icon: "fa fa-question-circle"  %>
    <%= f.input :wholesale_price %>
    <%= f.input :percentage %>
    <%= f.input :quantity %>
    <%= f.input :sell_price %>
  </div>    
<% end %>

and here is my custom wrapper :product_form

config.wrappers :product_form, tag: 'div', class: 'form-group row', error_class: 'has-error' do |b|
b.use :html5
b.use :placeholder
b.optional :maxlength
b.optional :pattern
b.optional :min_max
b.optional :readonly
b.use :label, class: 'control-label col-sm-3'
b.wrapper tag: 'div', class: 'input-icon col-sm-6' do |ba|
  ba.use :input, class: 'form-control'
  ba.use :error, wrap_with: { tag: 'span', class: 'help-block' }
  ba.use :hint,  wrap_with: { tag: 'p', class: 'help-block' }
end
b.use :icon , input_html: {  "data-toggle" => "popover", "data-placement" => "top", "data-content" => "adasdasdadsasd", "data-trigger" => "hover" }
end

what i got correctly from the above code after i inspect the input is on the class of the icon

<i class="fa fa-question-circle"></i>

any help will be appreciated and also how to make the data-content dynamic so that i can use it in many inputs with different data

Upvotes: 3

Views: 1146

Answers (1)

Petr Gazarov
Petr Gazarov

Reputation: 3811

What you are looking to do is create a custom component. Simple forms already has a component named icon, so you'll have to choose a different name. There are good docs about it here. Here is a base implementation:

module SimpleForm
  module Components
    module MyIcon
      def my_icon(wrapper_options = nil)
        @my_icon ||= begin
          content_tag :span, options[:my_icon_html] do
            options[:my_icon].to_s.html_safe if options[:my_icon].present?
          end
        end
      end

      def has_my_icon?
        my_icon.present?
      end
    end
  end
end

And include it in the code:

module SimpleForm
  module Inputs
    class Base
      include SimpleForm::Components::MyIcon
    end
  end
end

I passed options[:my_icon_html] directly to content_tag, so you can use it to dynamically pass attributes.

Upvotes: 3

Related Questions