1

Does anyone know a nice way to get the last lineItem(s) added to a cart in craft commerce via twig template? Example use case, an 'added to cart' confirmation page. I know for this you could query param a product/variant id but multiple could be submitted.

I attempted {cart.lineItems | last} but they do not seem to be in date order. I also checked the class models but didn't find any helpful methods or attributes.

Perhaps some kind of db query, as sql has date fields?

2

Since multiple line item can be updated or added to the cart at the same time, it would be hard to point to a specific line item that is newest.

The line items have a dateUpdate column you could sort and query on.

{% set result = craft.query()
    .select('*')
    .from('{{%commerce_lineitems}}')
    .where({
        'orderId': cart.id
    })
    .orderBy('dateUpdated ASC')
    .one()
%}

We could look to added a lastUpdateLineItem() method to the order element in future version of Craft Commerce. You can submit the idea here: https://github.com/craftcms/commerce/issues

|improve this answer|||||
  • Perfect, thanks Luke. And yes, I see how multiple lines could cause a problem, such as changing quantities etc, but as far as adding items to the cart, I expect the majority of sites add one item at a time (regardless of the qty). – Seraphim Jester Jul 11 '19 at 10:18
  • I've tried this out and it seems that .orderBy('...ASC') and ('..DESC') return the first lineItem added I believe because the cart updates all line items together. I tried using dateCreated but this doesn't work if I go back to add additional items to a previously added lineItem – Seraphim Jester Jul 12 '19 at 13:20
1

If your use-case is where you do only allow a single product at a time to be added to the cart, then one simple way I think you could do this is just take the first item in the lineItems array. I say this because it seems that whenever a product gets added to the cart, it becomes the first item in the array.

I can't find any documentation on this but I suspect this is how Commerce was designed as that would reflect most user's expectations that the most recent thing they add is typically shown first in a list of products in their cart.

|improve this answer|||||
  • Makes sense @Mike, but I have a feeling this may break with updated qty etc.. but I like the idea, and may well do the job! – Seraphim Jester Feb 4 at 11:47
  • Actually, I don't think it does break with a quantity update... though I haven't tested thoroughly it seems the order of item does not change. – Mike Feb 5 at 17:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.