在Commerce 2中,如何加载当前用户的购物车?当前用户可以是匿名的,也可以是登录的。这个网站有多个商店,我不知道用户目前在哪个商店。
发布于 2018-02-08 22:40:41
这取决于你需要什么,真的。如果您只需要所有商店的所有手推车,那么购物车供应商服务可以为您提供:
$all_carts = \Drupal::service('commerce_cart.cart_provider')
->getCarts();如果您需要一辆基于上下文的特定商店的购物车,那么它就会变得更加棘手。通过当前存储服务可以找到对“当前”存储的引用:
$store = \Drupal::service('commerce_store.current_store')->getStore();而购物车通过购物车供应商与该商店相关:
$cart = \Drupal::service('commerce_cart.cart_provider')
->getCart('default', $store);(顺便说一句,在上述所有片段中,如果您可以将这些服务注入当前上下文,而不是使用静态方法,那就更好了)。
问题在于商务部对“当前”商店的定义。要么是在查看订单时来自order实体,要么是默认存储。根据您的描述,这两种方法都不会完成任务,因此您需要编写一个自定义存储解析器。
我不知道当您需要cart实体时有什么上下文可用,所以这里有一个基于产品页面的简单示例。因为一个产品可以在多个商店中,所以它只返回数组中的第一个。
namespace Drupal\MODULE\Resolver;
use Drupal\commerce_product\Entity\ProductInterface;
use Drupal\commerce_store\Resolver\StoreResolverInterface;
use Drupal\Core\Routing\RouteMatchInterface;
class ProductPageStoreResolver implements StoreResolverInterface {
protected $routeMatch;
public function __construct(RouteMatchInterface $route_match) {
$this->routeMatch = $route_match;
}
public function resolve() {
$product = $this->routeMatch->getParameter('commerce_product');
if ($product instanceof ProductInterface) {
$stores = $product->getStores();
return reset($stores);
}
return NULL;
}
}以及MODULE.services.yml的条目:
services:
MODULE.product_page_store_resolver:
class: Drupal\MODULE\Resolver\ProductPageStoreResolver
arguments: ['@current_route_match']
tags:
- { name: commerce_store.store_resolver, priority: 100 }清除缓存后,上面的第一个代码段将返回分配给产品的第一个存储区(查看它时)。
发布于 2018-10-12 12:42:41
只是想一想,这可能是有用的,从特定的用户按id加载(最后)购物车订单,使用这个。
$orders = \Drupal::entityTypeManager()
->getStorage('commerce_order')
->loadByProperties(['uid' => $user_id, 'cart' => '0']);但是要为登录用户和匿名用户加载购物车,您应该使用以下命令
$cart_provider = \Drupal::service('commerce_cart.cart_provider');
$carts = $cart_provider->getCarts();
$order = array_shift($carts);发布于 2020-01-27 17:38:49
要获得当前用户的购物车(如果您只有一个商店):
$store = \Drupal\commerce_store\Entity\Store::load(1);
$order_type = 'default';
$cart_provider = \Drupal::service('commerce_cart.cart_provider');
$cart = $cart_provider->getCart($order_type, $store);要获得特定用户的购物车:
$cart = $cart_provider->getCart($order_type, $store, $account);https://drupal.stackexchange.com/questions/255431
复制相似问题