将drupal commerce产品添加到购物车,无需以编程方式重新加载页面

问题描述 投票:0回答:2

如何实施以下任务: -

我有2个div,在第一个div我有产品名称和添加链接,如果用户点击添加链接相关产品应该添加在第二个div。

在底部的第二个div我已经添加到购物车按钮所以点击购物车按钮所有添加的产品应该添加在drupal commerce添加到购物车页面。

仅供参考,请查看以下链接: -

http://buildabagpartyfavours.ca/pages/build-your-own-goodie-bag

drupal drupal-7 drupal-modules drupal-views drupal-commerce
2个回答
1
投票

如果有人使用Drupal 8,想要解决这个问题,可以这样:

如果您有产品变体ID $ var_id,则可以使用“use-ajax”类创建“a”标记:

<a href="/add/product/'.$var_id.'" class="use-ajax -add-to-cart">Add to cart</a>

在routing.yml中,您必须使用控制器添加以下路径:

path: '/add/product/{pid}'
_controller: Drupal\MY_MODULE\Controller\ShopProductController::addToCart

您必须使用ajax响应创建控制器:

    namespace Drupal\MY_MODULE\Controller;

    use Drupal\commerce_order\Entity\OrderInterface;
    use Drupal\commerce_order\Entity\OrderItem;
    use Drupal\commerce_order\Entity\Order;
    use Drupal\Core\Ajax\AjaxResponse;
    use Drupal\Core\Ajax\HtmlCommand;
    use Drupal\Core\Ajax\CssCommand;

class ShopProductController {
    public function addToCart($pid) {

        $ajax_response = new AjaxResponse();
        #### ADD TO CART ####
        // variation_id of product.

        if (isset($pid) && !empty($pid)) {

            $store_id = 1;
            $order_type = 'default';
            $variation_id = $pid;

            $entity_manager = \Drupal::entityManager();
            $cart_manager = \Drupal::service('commerce_cart.cart_manager');
            $cart_provider = \Drupal::service('commerce_cart.cart_provider');

            // Drupal\commerce_store\Entity\Store::load($store_id);
            $store = $entity_manager->getStorage('commerce_store')->load($store_id); 
            $product_variation = $entity_manager->getStorage('commerce_product_variation')->load($variation_id);

            // order type and store
            $cart = $cart_provider->getCart($order_type, $store);
            if (!$cart) {
                $cart = $cart_provider->createCart($order_type, $store);
            }

            //Create new order item 
            $order_item = $entity_manager->getStorage('commerce_order_item')->create(array(
                'type' => 'default',
                'purchased_entity' => (string) $variation_id,
                'quantity' => 1,
                'unit_price' => $product_variation->getPrice(),
            ));

            $order_item->save();
            $cart_manager->addOrderItem($cart, $order_item);

            $ajax_response->addCommand(new HtmlCommand('.-add-to-cart', '<span class="-added">Added</span>'));

            }

            return $ajax_response;

        }
}

0
投票

让你的按钮触发一些AJAX调用,传递产品ID,然后在你的AJAX回调脚本中收集产品ID,从中创建订单项并将其添加到购物车(https://www.drupal.org/node/1288414)。

当AJAX调用完成后,您将不得不再调用另一个,以更新购物车块。

© www.soinside.com 2019 - 2024. All rights reserved.