How to clear all produts from cart in PrestaShop

无人久伴 提交于 2019-12-04 17:58:49

Many things :

  • $this->getProducts() won't work in the order controler. Use get it with the context instead
  • getProducts() method doesn't return product object, but a collection of product array. You can't get informations with -> use [] instead

There is your correct function :

public function emptybag()
  {

    $products = $this->context->cart->getProducts();
    foreach ($products as $product) {
      $this->context->cart->deleteProduct($product["id_product"]);
    }
  }

To make it easier, add your function to your overrided file of the front controler, like that you will be able to call it from everywhere in the front. Then override the init function and add these line to the end of the function (not before because we need the cart attribute to be initialised) :

if (isset($_GET['emptybag'])){
      $this->emptybag();
    }

Then, add a link to your template where you want :

<a href="{$link->getPageLink('order', true, NULL, 'emptybag=1')}" class="button_large" title="{l s='Clear cart'}">{l s='Clear cart'}</a>

And this is it!

Rami Neifar

To have a clean url in your navigation you can add this line after your condition "emptybag"

Tools::redirect($this->context->link->getPageLink('order', true, NULL));

to redirect page on order.

$this->context->cart->delete();

Simple!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!