Ad

How To Get One Product To Modify Information In The Cart In Shopify?

- 1 answer

If a customer clicks a certain button in my Shopify store, I'd like to be able to add information to my cart using Liquid (or whatever is needed). This information can be as simple as a string. The customer won't see this information, but it will be used to modify the look of the cart page. I can happily parse it/handle it as a string, if that's my only option, but so far I can't get any information to be sent. I have tried modifying cart.note using a {% capture %} block, but that never ended up modifying anything permanently. I also am not sure how to change line_item properties, but that might do it as well.

Ad

Answer

You can add input fields with the name properties[some-prop-name] to your product form, which would include the required linking data

For example, adding the following input to your product form would add a line-item property to your product as you add it:

<input type="checkbox" name="properties[_add_to_box]" value="{{ box_identifier }}" />

If you want to dynamically update line-item properties to add/rearrange items in boxes post-hoc you can do so using AJAX requests targeting the /cart/change.js endpoint

Here's an example of such a command, which you would run upon the user changing the appropriate input element:

/* Assuming we have a variable named cart (containing the cart JSON) and the the 0-based index for the item we want to update */

var line = index + 1;  //Shopify uses 1-based indexing for line-items
var qty = cart.items[index].quantity;

jQuery.ajax({
  url:'/cart/change.js',
  type:'post',
  dataType:'json',
  data:{
   line: line, /* Line to edit: REQUIRED */
   quantity: qty, /* 'New' quantity - If omitted, the line will change to quantity 1! */
   properties:{
     /*
      This properties object will replace any existing properties object on the line-item, so be sure to include everything, not just what you're changing!
      Properties with keys that are prepended with an underscore (_) are hidden in Shopify's checkout page.  
     */
     _box_id: 'box01',
     'Congratulatory Message':'Hooray! You did it!'
   }
  },
  success:function(cart){
    console.log('Success!', cart)
  },
  error:function(err){
    alert('Something went wrong!', err)
  }
 
})

Hopefully this helps you get your feature in!

Ad
source: stackoverflow.com
Ad