Magento:以编程方式将可配置产品添加到购物车

时间:2014-11-29 08:38:04

标签: magento

如何以编程方式将子产品添加到购物车?

我有一个儿童产品SKU,我想

  1. 获取超级属性,例如 sizecolor id以及产品中的值,
  2. 然后获取父product id
  3. 将param上的超级属性传递给数量,以添加到function cart
  4. //$cart->addProduct($product1, $options);

    这里,如何在$option变量上传递supper属性?请帮帮我!!!!

2 个答案:

答案 0 :(得分:4)

试试这个。我认为它可能需要一些改进,但在简单的情况下效果很好。

$_product = $this->getProduct();
$parentIds = Mage::getResourceSingleton('catalog/product_type_configurable')->getParentIdsByChild($_product->getId());
// check if something is returned
if (!empty(array_filter($parentIds))) {
    $pid = $parentIds[0];

    // Collect options applicable to the configurable product
    $configurableProduct = Mage::getModel('catalog/product')->load($pid);
    $productAttributeOptions = $configurableProduct->getTypeInstance(true)->getConfigurableAttributesAsArray($configurableProduct);
    $options = array();

    foreach ($productAttributeOptions as $productAttribute) {
        $allValues = array_column($productAttribute['values'], 'value_index');
        $currentProductValue = $_product->getData($productAttribute['attribute_code']);
        if (in_array($currentProductValue, $allValues)) {
            $options[$productAttribute['attribute_id']] = $currentProductValue;
        }
    }

    // Get cart instance
    $cart = Mage::getSingleton('checkout/cart'); 
    $cart->init();
    // Add a product with custom options
    $params = array(
        'product' => $configurableProduct->getId(),
        'qty' => 1,
        'super_attribute' => $options
    );
    $request = new Varien_Object();
    $request->setData($params);
    $cart->addProduct($configurableProduct, $request);
    $session = Mage::getSingleton('customer/session');
    $session->setCartWasUpdated(true);
    $cart->save();
}

答案 1 :(得分:0)

你可以试试。

    $cart = Mage::getModel('checkout/cart');
    $cart->init();
    $productCollection = Mage::getModel('catalog/product')->load($productId);

    $cart->addProduct($productCollection , 
                                        array( 'product_id' => $productId,
                                                 'qty' => 1,
                                                 'options' => array( $optionId => $optionValue));
    $cart->save();