How to Copy cart into another cart in order to change the id_cart?

Objectives of the blog

After reading this blog we will be able to copy the cart into another cart in order to change the Cart Id.

Requirement

We need to modify the below file to fix the same. We will be making changes in the Core file for the same.

Root dir\classes\PaymentModule.php

Procedure

We need to modify the validate order function in the PaymentModule class file. As this function is called only once while completing the order. So we have added the code in the same to avoid multiple cart creation.

 

if (self::DEBUG_MODE) {
PrestaShopLogger::addLog('PaymentModule::validateOrder - Function called', 1, null, 'Cart', (int)$id_cart, true);
}
if (!isset($this->context)) {
$this->context = Context::getContext();
}
$this->context->cart = new Cart((int)$id_cart);

 

Below code needs to be added in the validate order function after above lines.

// changes started
// To save the secure key of current cart id and reassign the same to new cart
$old_cart_secure_key = $this->context->cart->secure_key;
// To save the customer id of current cart id and reassign the same to new cart
$old_cart_customer_id = (int)$this->context->cart->id_customer;
// To unmap the customer from old cart
$this->context->cart->id_customer = 0;
// To update the cart
$this->context->cart->save();
// To fetch the current cart products
$cart_products = $this->context->cart->getProducts();
// Creating new cart object
$this->context->cart = new Cart();
$this->context->cart->id_lang = $this->context->language->id;
$this->context->cart->id_currency = $this->context->currency->id;
// to add new cart
$this->context->cart->add();
// to update the new cart
foreach ($cart_products as $product) {
$this->context->cart->updateQty((int) $product['quantity'], (int) $product['id_product'], (int) $product['id_product_attribute']);
}
if ($this->context->cookie->id_guest) {
$guest = new Guest($this->context->cookie->id_guest);
$this->context->cart->mobile_theme = $guest->mobile_theme;
}
// to map the new cart with the customer
$this->context->cart->id_customer = $old_cart_customer_id;
// to save the new cart
$this->context->cart->save();
if ($this->context->cart->id) {
$this->context->cookie->id_cart = (int) $this->context->cart->id;
$this->context->cookie->write();
}
// to update the $id_cart with that of new cart
$id_cart = (int) $this->context->cart->id;
$this->context->cart->secure_key = $old_cart_secure_key;
// changes over

 

After following the above procedure, the shopping cart list will look like this i.e having a duplicate cart with the same details as of the cart with which the order is placed.
shopping-cart-list

Summary

After following the above procedure, You will be able to copy the cart into another cart in order to change the id_cart.

Leave a Reply

Your email address will not be published. Required fields are marked *