Skip to content

Instantly share code, notes, and snippets.

@bummzack
Last active July 20, 2016 08:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bummzack/0a574b861228d945478416b9d6cea3e1 to your computer and use it in GitHub Desktop.
Save bummzack/0a574b861228d945478416b9d6cea3e1 to your computer and use it in GitHub Desktop.
Explanation how to set up quantity fields for "add to cart" on project-lists.

Setting up JavaScript enabled add-to-cart functionality with quantity-field

Requirements

PHP

The shop-ajax module:

composer require markguinn/silverstripe-shop-ajax

JavaScript

jQuery and the jsUri JavaScript library (used for URL manipulation).

Install using NPM:

npm install --save-dev jsuri

Or using Bower:

bower install --save jsUri

… or just grab the sources from GitHub.

Making it work

In your ProductGroupItem.ss add the ajax and add-to-cart classes to your add-to-cart Link. Example:

<% if $canPurchase %>
    <a href="$addLink" title="<%t Product.AddToCart "Add to Cart" %>" class="ajax add-to-cart">
        <%t Product.AddToCart "Add to Cart" %>
    </a>
<% end_if %>

Then add the following JavaScript:

$("a.add-to-cart").each(function(){
	var $this = $(this);
	var stepper = $('<input type="number" min="1" max="99" step="1" value="1" name="quantity"/>');

	stepper.data("target", $this).on("change", function(evt){
		var qtty = parseInt($(this).val());
		var maxQtty = parseInt($(this).attr("max"));
		qtty = Math.min(maxQtty, qtty);
		var tgt = $(this).data("target");
		var uri = new Uri(tgt.attr("href"));

		if(uri.hasQueryParam("quantity")) {
			uri.replaceQueryParam("quantity", qtty);
		} else {
			uri.addQueryParam("quantity", qtty);
		}

		tgt.attr("href", uri.toString());
	});

	$this.before(stepper);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment