Tom Prats
Tom Prats

Reputation: 7911

Rails form submit custom image or use a default image based on radio buttons

I have a form with a radio select. When the user selects the first option, I'd like to pass the default url as the logo_image param (on submit). If the user selects the second option and puts in a url, I want to pass that as the logo_image param.

Right now my code (seen below) submits the second option every time. How can I make it submit based on the selected option? I think I could figure it out with javascript but is there a pure html/css way? I still accept the best answer, even if it uses javascript

<%= form_for(:organization, html: { class: "form-horizontal" }) do |f| %>
  ...
  <div class="form-group">
    <%= f.label :logo, class: "col-md-5 control-label" %>
    <div class="col-md-7">
      <div class="radio">
        <label>
          <%= radio_button_tag :logo_image, :default, @organization.has_default_logo? %>
          Default Logo<br>
          <%= image_tag @organization.default_logo, class: "org-logo border" %>
          <%= f.hidden_field :logo_image, value: @organization.default_logo %>
        </label>
      </div>
      <div class="radio">
        <label>
          <%= radio_button_tag :logo_image, :custom, [email protected]_default_logo? %>
          Custom Logo
          <%= image_tag @organization.logo_image, class: "org-logo" if @organization.logo_image %>
          <%= f.text_field :logo_image, { class: "form-control" } %>
        </label>
      </div>
    </div>
  </div>
  ...
<% end %>

Upvotes: 0

Views: 171

Answers (1)

bloy
bloy

Reputation: 251

the way HTML submit works, logo_image is being 'overwritten' by the later fields, something like this:

  1. radio button tag ("default", if checked)
  2. hidden field value
  3. radio button tag ("custom", if checked)
  4. text field value

which results in the value returned to your controller always being the text field value.

If I'm reading your intent right, you'll need to have different names for the radio button field and for the custom url field, and use the value of the radio button field in your controller or model to decide which image url to use. You probably don't need the hidden field, since the code will already have that value as the default url anyway.

Upvotes: 1

Related Questions