我目前正在开发一个Shopware 6插件,旨在根据商店的默认国家/地区动态确定单个产品的运费。我想在不将产品添加到购物车的情况下获得产品的运费。我的插件目录中的自定义文件MyCustomShippingMethodRoute.php
如下所示:
<?php
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\Routing\Annotation\Entity;
use Shopware\Core\System\SalesChannel\SalesChannelContext;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Shopware\Core\Checkout\Shipping\SalesChannel\AbstractShippingMethodRoute;
use Shopware\Core\Checkout\Shipping\SalesChannel\ShippingMethodRouteResponse;
use SwagProductReview\Service\ShippingPriceService;
/**
* @Route(defaults={"_routeScope"={"store-api"}})
*/
class MyCustomShippingMethodRoute extends AbstractShippingMethodRoute
{
private AbstractShippingMethodRoute $decorated;
private ShippingPriceService $shippingPriceService;
public function __construct(AbstractShippingMethodRoute $decorated, ShippingPriceService $shippingPriceService)
{
$this->decorated = $decorated;
$this->shippingPriceService = $shippingPriceService;
}
public function getDecorated(): AbstractShippingMethodRoute
{
return $this->decorated;
}
/**
* @Entity("shipping_method")
* @Route("/store-api/shipping-method", name="store-api.shipping.method", methods={"GET", "POST"})
*/
public function load(Request $request, SalesChannelContext $context, Criteria $criteria): ShippingMethodRouteResponse { $criteria->addAssociation('prices');
$result = $this->decorated->load($request, $context, $criteria);
$originalResult = clone $result;
// $cart = $this->cartService->getCart($context->getToken(), $context);
$shippingMethods = $result->getShippingMethods()->filterByActiveRules($context);
/** @var ShippingMethodEntity $shippingMethod */
try {
foreach ($shippingMethods as $shippingMethod) {
$shippingPrices= $shippingMethod->getPrices();
// dd($shippingMethod->getPrices());
}
} catch (\Error $exception) {
return $originalResult;
}
return $result;
}
}
但是,我遇到了一个问题,我不知道如何在产品详细信息页面上显示$shippingPrices
的值。
1.它甚至可以显示运费的详细信息页面,而不添加到购物车?
1.如果是的话,请指导我该怎么做?
此致,
1条答案
按热度按时间9avjhtql1#
当你装饰产品详细路线时,你可以注入
CartService
,以获取当前购物车并将产品作为新的行项目添加到购物车。此外,你可以注入CartRuleLoader
并使用它来计算产品添加到购物车的运费。为了避免计算后购物车被持久化,你可以设置一个虚拟值作为购物车的标记,并订阅CartVerifyPersistEvent
。在监听器中,你检查该虚拟值的标记,并设置一个标志,使购物车在以后不会被持久化。设置CartBehavior
标志还应该防止在较新的版本,但无论哪种方式都可以进行回退检查。