pholls
pholls

Reputation: 35

Adding multiple products to cart in Spree store (Rails 4.2.5.2 / Spree 3.1.0)

I'm trying to create a section on the Product show page that will display 3 products, with checkboxes beneath them, and a button to add the selected ones to the cart. As I have it now, only the last item is being added to the cart, I believe because the multiple variables with the same name are being used, and only the last one is selected (as discussed here).

The answer linked above is for Spree 2.0.4, and I'm using 3.1.0, so I can't quite use the answer as discussed there.

I have looked into the Spree API, as discussed in this question (and also using Rails 4 and Spree 3, so much closer to the versions I need). But there is no answer, just a comment saying "use the api" and no discussion on how to do so.

Another answer suggested using Spree Promotions, but I don't think that's what I need.

(This other answer was using Rails 3.2, and I couldn't find the model order_populate they referenced.)

Here is my code:

<%= form_for :order, url: populate_orders_path do |f| %>
  <!-- placeholder; select actual products later -->
  <% Spree::Product.all.take(3).each_with_index do |product, index| %>
    <% if product.can_supply? %>
      <%= render partial: 'spree/products/product', locals: { product: product } %>
      <%= hidden_field_tag "variant_id", product.master.can_supply? ? product.master.id : product.variants.find(&:can_supply?).id %>
      <!-- placeholder; replace with checkbox after hardcoded quantity working -->
      <%= hidden_field_tag :quantity, 1 %>
      <%#= check_box "quantity", product.master.id, { class: "similar-product-checkbox" } %>
    <% end %>
  <% end %>

  <span class="input-group-btn">
    <%= button_tag class: 'btn btn-success primary-cta', id: 'add-pairings-to-cart-button', type: :submit do %>
    <%= Spree.t(:add_items_to_cart) %>
    <% end %>
  </span>
<% end %>

Upvotes: 0

Views: 369

Answers (1)

pholls
pholls

Reputation: 35

So the solution I ended up going with was adding a hidden field with the id of the product. Then I bound a JS event handler to the form so when it's submitted, I prevent the default action and create an array of the product IDs for which the checkbox was selected. Then I iterate over that array and send a POST request to the Spree API at the url /api/v1/orders/${orderNumber}/line_items?line_item[variant_id]=${itemID}&line_item[quantity]=1, and redirect them to the cart page.

Upvotes: 1

Related Questions