Search code examples
ruby-on-railssimple-form

Is it possible to override the base "class" of SimpleForm generated form fields?


This is my simple_form.rb :

  config.wrappers :select_form, tag: "div", class: "control" do |b|
    b.use :html5
    b.use :placeholder
    b.optional :pattern
    b.optional :readonly
    b.use :label, class: "label"
    b.use :input, wrap_with: { tag: "div", class: "select" }
    b.use :full_error, wrap_with: { tag: "div", class: "help is-danger" }
    b.use :hint, wrap_with: { tag: "small", class: "form-text text-muted" }
  end

Which generates this :

<div class="control select required user_role"><label class="label select required" for="user_role">User Role</label>
    <div class="select"><select class="select required" required="required" aria-required="true" name="user[role]" id="user_role">

The problem is the class .select is both being used by SimpleForm to determine the type of element as well as by my CSS class Bulma causing a graphical conflict.

Is there anyway to remove the class select from the parent <div> since it's not necessary?


Solution

  • Added this to my initializers/simple_form.rb :

    class SimpleForm::Wrappers::Many
      def wrap(input, options, content)
        return content if options[namespace] == false
        return if defaults[:unless_blank] && content.empty?
    
        tag = (namespace && options[:"#{namespace}_tag"]) || @defaults[:tag]
        return content unless tag
    
        klass = html_classes(input, options)
    
        opts  = html_options(options)
    
        # Removes the conflict class ".select" from the wrapper
        klass.delete(:select) if options[:wrapper] == :select_form && klass.length > 1
        opts[:class] = (klass << opts[:class]).join(' ').strip unless klass.empty?
        input.template.content_tag(tag, content, opts)
      end
    end