At checkout page (chekout/cart
) I want to edit the checkout button url destination based on cart items (link.phtml
).
How can I get all items in cart? I want to do this without using the API. Thanks.
cartcheckoutitemsmagento2session
At checkout page (chekout/cart
) I want to edit the checkout button url destination based on cart items (link.phtml
).
How can I get all items in cart? I want to do this without using the API. Thanks.
Best Answer
I'll answer the question in two parts:
I. Where should you change the checkout URL?
The destination in
link.phtml
is$block->getCheckoutUrl()
. You should not change the template to change functionality, but change the blockMagento\Checkout\Block\Onepage\Link
instead. To do so create a plugin for it with a methodafterGetCheckoutUrl()
to change the return value.II. How to get all items in the cart?
As of magento-2.0 the service contracts in Magento_Checkout and Magento_Quote do not provide the necessary methods yet, so we use the cart model. In your plugin inject it like this:
Now that you have access to the cart, you can retrieve the items in several ways, which is basically the same as in Magento 1:
Returns a quote item collection with all items associated to the current quote.
This is a shortcut for the method above, but if there is no quote it returns an empty array, so you cannot rely on getting a collection instance.
Loads the item collection, then returns an array of all items which are not marked as deleted (i.e. have been removed in the current request).
Loads the item collection, then returns an array of all items which are not marked as deleted AND do not have a parent (i.e. you get items for bundled and configurable products but not their associated children). Each array item corresponds to a displayed row in the cart page.
Choose what fits your needs best. In most cases the last method is what you need.