0
votes

I am developing a shopify theme, i have created mini cart page as shown in this image, my website is: https://codeinspire-dev2.myshopify.com/cart enter image description here

I am using vue.js for controling this mini cart page data, i have called 

axios.get('/cart.js') for populating it with data, that call gives me cart object with all items on it, but there is no  inventory_quantity property there. User can change quantity on mini cart page, but  i can't check if the product quantity on mini cart page gets bigger then it's inventory_quantity. How can i do that. Any help is appreciated.

1

1 Answers

4
votes

You have two options.

Option 1.
As cart JSON object doesn't provide information about variant inventory quantity available, you need to create such an object manually in the theme template. See the code below that will give you an idea how to get inventory quantity available for the items in your cart:

{%- assign cart_items_count = cart.items | size -%}
var cartItemMaxQuantities = {
  {%- for item in cart.items -%}
  "{{ item.id }}": {{- item.variant.inventory_quantity -}}
  {%- unless forloop.index == cart_items_count -%},{%- endunless -%}
  {%- endfor -%}
};

This will create a JSON object that you can use in your JS logic on adjusting cart items quantity. The object would look like that:

{
  variant_id_1: max_available_quantity,
  variant_id_2: max_available_quantity,
  ...,
  variant_id_x: max_available_quantity
}

If you need to get updated object on adding/removing cart items using AJAX - create a new page template e.g. page.max-qtys.liquid to output this JSON object. Then on adding/removing items, you can get the updated object by requesting any page on your website and adding a ?view=max-qtys query param e.g. /pages/about?view=max-qtys. Don't forget to add {% layout none %} at the beginning of the template file to prevent load your site layout file and just output the object JSON. Below is the code for the page template.

{%- layout none -%}
{%- assign cart_items_count = cart.items | size -%}
{
  {%- for item in cart.items -%}
  "{{ item.id }}": {{- item.variant.inventory_quantity -}}
  {%- unless forloop.index == cart_items_count -%},{%- endunless -%}
  {%- endfor -%}
}

Option 2
Use /cart/add.json on adding new items to the cart instead of /cart.update.json or /cart/change.json. Shopify will respond with 422 status code and won't allow you to add more items than available if you use /cart/add.json endpoint.