Magento 2:在推车中添加多种可配置的产品变体
-
29-09-2020 - |
题
我正试图立即向购物车添加一个可配置产品的多种变体,我将代码放在一起,但目前它正在增加产品的正确性,但仅使用第一个变异。
换句话说,如果我试图加入2件绿色T恤和4个白色T恤,它可以将6个绿色T恤添加到购物车中。这是我在内部添加控制器的代码:
public function execute()
{
$paramsData = $this->getRequest()->getParams();
try {
$msg = array();
$errorMsg = array();
foreach($paramsData['qty'] as $pId=>$param){
if (isset($param)) {
$filter = new \Zend_Filter_LocalizedToNormalized(
['locale' => $this->_objectManager->get('Magento\Framework\Locale\ResolverInterface')->getLocale()]
);
$params['qty'] = $filter->filter($param);
}
$params['product'] = $paramsData['product'][$pId];
$product = $this->initProduct($params['product']);
$params['super_attribute'] = $paramsData['super'][$pId];
/**
* Check product availability
*/
if (!$product) {
return $this->goBack();
}
$this->cart->addProduct($product, $params);
$msg[] = $product->getName();
}
$this->cart->save();
}
$resultRedirect->setPath('checkout/cart');
return $resultRedirect;
}
.
从该打印机中,它确认选项是正确的:
Array ( [super_attribute] => Array ( [90] => 5 ) [qty] => 2 )
Array ( [super_attribute] => Array ( [90] => 7 ) [qty] => 4 )
.
但我在购物车中,我看到了第一个super_attribute(6恤而不是2个绿色和4个白色T恤)。
在添加每个项目或其他物品后,我需要做的东西'重置'购物车?
谢谢。
解决方案
我有回答, 问题是产品对象覆盖下一个循环, 在控制器中,
我们必须每次创建新产品对象,现在在下面发生更改后的工作。
而不是$product = $this->initProduct($params['product']);
wode设置为下线,
$storeId = $this->_objectManager->get('Magento\Store\Model\StoreManagerInterface')->getStore()->getId();
$product = $this->_objectManager->create('Magento\Catalog\Model\Product')->setStoreId($storeId)->load($params['product']);
.
它的作品。
其他提示
旧问题,只是为了报告更好的方法来做同样的事情。而不是使用 objectmanager ...
$product = $this->_objectManager->create('Magento\Catalog\Model\Product')->setStoreId($storeId)->load($params['product']);
.
使用 \ magento \ catalog \ model \ produceFactory (您需要添加对类构造函数的新依赖项)将产生相同的结果...
$product = $this->_productFactory->create()->setStoreId($storeId)->load($params['product']);
.