ruby-on-railsactiveadminformtastic

Add an image next to a checkbox label in activeadmin form


I am using gem 'activeadmin', '~> 1.3' in a rails app. I have these relationships between two models :

class Offer < ApplicationRecord
  has_many :products
end
class Product < ApplicationRecord
  belongs_to :offer, required: false
  has_attachments :photos, maximum: 4, dependent: :destroy
end

I can access a product's first photo this way : @product.photos[0] or @product.photos[0].path

In admin/offer.rb, the checkboxes to select products belonging to the offer are built with :

f.input :products, as: :check_boxes

This renders a checkbox list with product names as labels. Now I want to enrich this label with a thumbnail of one product's photos next to it.

I failed to iterate over the ":products" when the checkboxes are built. I wanted to add an html tag like this : span img(src: "product_image_path"), as I do when I display the product page in activeadmin.

I checked formtastic documentation and only found this customization option : :collection => Product.pluck(:name, :id). This lets me change only the text in label but do not provide me a way to add an image.

How can I display a thumbnail of one of the product's photos next to product name in activeadmin form ?


Solution

  • As stated in : formtastic documentation, you can customize existing inputs. Thus, I created a checkbox_image input in a app/inputs/checkbox_image_input.rb :

    class CheckboxImageInput < Formtastic::Inputs::CheckBoxesInput
      include CloudinaryHelper
    
      def choice_html(choice)
        template.content_tag(
        :label,
        img_tag(choice) + checkbox_input(choice) + choice_label(choice),
        label_html_options.merge(:for => choice_input_dom_id(choice), :class => 
        "input_with_thumbnail"))
     end
    
      def img_tag(choice)
        cl_image_tag(Product.find(choice[1]).photos[0].path, :width=>30, 
        :crop=>"scale")
      end
    end
    

    I use cloudinary as an image storage service, you can update img_tag(choice) according to yours. Then you can use the new input in admin/model.rb, in form :

    f.input :products, as: :checkbox_image, :collection => product_selection
    

    Enventually I styled the new label tag in my active_admin_custom_css.css file, using input_with_thumbnail class.