首页 > 解决方案 > Prestashop 1.6 - 我的产品如何从我的模块的 php 页面购物

问题描述

我有一个带有自定义模块的 php 代码。如何通过代码将产品添加到购物车。我有 id_number(产品 id)和 id_customer(客户 id)

<?php

$product id = 1167;

// how to proceed to add information to cart

需要将此产品(id_number)更新到我的购物车(登录用户)

标签: prestashopprestashop-1.6

解决方案


我在我的模块中使用此代码段将产品添加到购物车,但您可以在覆盖的控制器中使用它:

public function add2cart(){
        $id = 1167;
        $qty = 1;

        if($id!=''){


            $this->createCart();
            $this->context->cart->updateQty($qte, $id, null, '');
            $this->context->cart->save();
            $this->context->cookie->__set('id_cart', $this->context->cart->id);         


            echo 'Product added to cart!';
            exit;


        }

    }



    private function createCart()
    {
        if (is_null($this->context->cart)) {

            $this->context->cart = 
            new Cart($this->context->cookie->id_cart);
        }

        if (is_null($this->context->cart->id_lang)) {
            $this->context->cart->id_lang = $this->context->cookie->id_lang;
        }

        if (is_null($this->context->cart->id_currency)) {
            $this->context->cart->id_currency = $this->context->cookie->id_currency;
        }

        if (is_null($this->context->cart->id_customer)) {
            $this->context->cart->id_customer = $this->context->cookie->id_customer;
        }

        if (is_null($this->context->cart->id_guest)) {

            if (empty($this->context->cookie->id_guest)){
                $this->context->cookie->__set(
                'id_guest', 
                Guest::getFromCustomer($this->context->cookie->id_customer)
                );
            }
            $this->context->cart->id_guest = $this->context->cookie->id_guest;
        }

        if (is_null($this->context->cart->id)) {

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

            $this->context->cookie->__set('id_cart', $this->context->cart->id);
        }
    }

在我的 initContent 函数中,我调用了函数 add2cart() :

$this->add2cart();

推荐阅读