Search code examples
ruby-on-railscssruby-on-rails-3ruby-on-rails-pluginsformtastic

Adding a background image or an image tag to Formtastic radio buttons with a collection


I have this formtastic field in a form where an user input his credit card data:

<%= form.input :credit_card_type, :as => :radio, :collection => User.credit_card_types %>

User.credit_card_types look like this:

  def self.credit_card_types
    {'Visa' => VISA, 'Master Card' => MASTER_CARD, 'American Express' => AMERICAN_EXPRESS}
  end

Which give me the following html:

<li id="user_credit_card_type_input" class="radio optional">
  <fieldset>
    <legend class="label">
      <label>Tipo de tarjeta</label>
    </legend>
    <ol>
      <li>
        <label for="user_credit_card_type_1">
          <input type="radio" value="1" name="user[credit_card_type]" id="user_credit_card_type_1"> Master Card
        </label>
      </li>
      <li>
        <label for="user_credit_card_type_0">
          <input type="radio" value="0" name="user[credit_card_type]" id="user_credit_card_type_0"> Visa</label>
      </li>

      <li>
        <label for="user_credit_card_type_2">
          <input type="radio" value="2" name="user[credit_card_type]" id="user_credit_card_type_2"> American Express</label>
      </li>
    </ol>
  </fieldset>
</li>

Given that, my question is, how can I add an specific background image to each radio button label? I can't do it with CSS because the labels have not any id and I can't (or I don't know how) put one to then. I tried to add an image_tag but it escapes the html. Any suggestion ?


Solution

  • Formtastic can be customized for your needs. You should be able to find Formtastic configuration file in config/initializers. Add a line like this:

    Formtastic::SemanticFormHelper.builder = SemanticCustomFormBuilder
    

    Then create in your lib directory a file named semantic_custom_form_builder.rb

    class SemanticCustomFormBuilder < Formtastic::SemanticFormBuilder
    
      def cicloon_special_radio_button_input
        #define your radiobuttons here
      end
    
    end
    

    You can use your custom definition like this in your forms:

    <%= form.input :credit_card_type, :as => :cicloon_special_radio_button %>