How to create, load and delete the cart in Hybris
Creating and Loading cart
Whenever we need to create a cart, first thing we need to check is whether cart is already exist or not.
Since this is a basic requirement of any eCommerce site, Hybris has already written a method in that way.
So, we should use Hybris provided method getSessionCart() defined in DefaultCartFacade to serve this purpose.
Yes, getSessionCart() method will make sure that cart is created if there is no cart exist, or it will load the existing cart if it exists already
We have to use it as below
- final CartData cartData = cartFacade.getSessionCart();
final CartData cartData = cartFacade.getSessionCart();
Make sure cartFacade is injected in the required class.
Above line execution makes sure that, you always have cart in the system
we can use the above code wherever we need to make sure that cart is mandatory and without which we can’t proceed further.
Deleting the cart
There are many ways to delete the cart based on which cart we need to delete
We can load the current session cart and delete it as below
- final CartModel cartModel = cartService().getSessionCart();
- modelService.remove(cartModel);
- sessionService.removeAttribute(“cart”);
final CartModel cartModel = cartService().getSessionCart(); modelService.remove(cartModel); sessionService.removeAttribute(“cart”);
Make sure cartService,modelService and sessionService are injected in the required class.
We can directly call façade method which does all the above things
- cartFacade().removeSessionCart();
cartFacade().removeSessionCart();
Make sure cartFacade is injected in the required class.
Creating cart, loading cart and Removing cart operations are very crucial operations in any eCommerce site.
We need to purge old carts after specific number of days as we don’t need to keep it in our DB
We can load old carts based the requirement using flexible search query and can delete the cart using above code.
We can check the same in Hybris OOTB logic for removing old carts.
Note :
Whenever we get requirement related to Cart, it is very important to look at OOTB methods provided by hybris before jumping to write our own methods