Calculate shipping costs by weight outside of cart in Shopware 6

81 views Asked by At

I try to show the customer the possible shipping costs dynamically on PDP in Shopware 6. I tried already something like this:

    /**
     * @Route("/shipping-cost", name="frontend.example.shipping-cost", methods={"GET"}, defaults=   {"XmlHttpRequest"=true})
     */
    public function exampleAction(Request $request, SalesChannelContext $context): JsonResponse
    {
        $orderNumber = $request->query->get('orderNumber');
        $quantity = (int) $request->query->get('quantity');
        $productRepository = $this->container->get('product.repository');

        $productId = $this->findProductIdByOrderNumber($productRepository, $orderNumber);

        $cart = $this->cartService->getCart($context->getToken(), $context);
        $cart->setToken("dummy_token");

        $productLineItem = $this->createProductLineItem($productId, $quantity);
        $this->cartService->add($cart, $productLineItem, $context);
        $cart = $this->cartRuleLoader->loadByCart($context, $cart, new CartBehavior([], true, true))->getCart();

        $shippingCost = $cart->getShippingCosts()->getTotalPrice();

        return new JsonResponse(['shipping_cost' => $shippingCost]);
    }

This works fine for one rule for deliveries, but with more than one rule it’s not working probably. It just cannot change the shipping rule when a shipping method is blocked in cart.

The solution can be: calculate shipping together with the products in cart or just the product itself.

I would be happy to any information, help or advice.

0

There are 0 answers