Magento добавляет несколько настраиваемых вариантов продукта, добавляя первый несколько раз

Я пытаюсь добавить в корзину сразу несколько вариантов настраиваемого продукта, и я собрал код вместе, но в настоящее время он добавляет нужное количество продуктов, но использует только первый вариант.

Другими словами, если я попытаюсь добавить 2 зеленые футболки и 4 белые футболки, я добавлю 6 зеленых футболок.

Вот код, который у меня есть:

public function indexAction ()   {
   $post = $this->getRequest()->getPost();
   $attr = array_keys($post['super_attribute']);
   $cart = Mage::getSingleton('checkout/cart');
    $product = Mage::getModel('catalog/product')->load($post['product']);
    foreach ($post['super_attribute'][$attr[0]] as $optId){

        if (abs($post['qty'][$optId]) > 0){

            $options = array(
                //"product"=>$post['product'], 
                "super_attribute"=>array(
                    $attr[0] => $optId
                ),                    
                "qty"=>$post['qty'][$optId]
            ); 

            echo "Add To Cart:";
            print_r($options);
            echo "<br /><br />";                
            $cart->addProduct($product, $options);
        }

    }

    $cart->save(); // save the cart
    Mage::getSingleton('checkout/session')->setCartWasUpdated(true); 

    die("??");
    $this->_redirect('checkout/cart/');    
}

И из этого print_r он подтверждает, что параметры верны:

 Add To Cart:Array ( [super_attribute] => Array ( [141] => 5 ) [qty] => 2 ) 

 Add To Cart:Array ( [super_attribute] => Array ( [141] => 4 ) [qty] => 4 ) 

Но в тележке я вижу 6 первых super_attribute.

Что мне нужно сделать, чтобы «сбросить» корзину после добавления каждого товара или чего-то еще?

Спасибо!


person Liam Wiltshire    schedule 14.05.2015    source источник
comment
ты получил ответ на этот вопрос?   -  person Nidheesh    schedule 05.07.2015


Ответы (2)


Я наткнулся на этот вопрос, и ответы мне не помогли. Я публикую здесь свою версию.

$parentProduct = Mage::getModel('catalog/product')->load($parentId)
    ->setStoreId(Mage::app()->getStore()->getId());

foreach($postData['super_attribute'] as $simpleProdId => $simpleProdConfig){

    //This cloning is important
    $product = clone $parentProduct;

    $cartParams = array();

    $cartParams = array(
        'super_attribute' => $simpleProdConfig['super_attribute'],
        'qty' => $simpleProdConfig['qty'],
    );

    $this->_getCart()->addProduct($product, $cartParams);

}

$this->_getCart()->save();

$this->_getSession()->setCartWasUpdated(true);

Или вместо передачи родительскому объекту продукта передайте его идентификатор, так как он, кажется, работает, хотя запрос становится медленным.

$parentProduct = Mage::getModel('catalog/product')->load($parentId)
    ->setStoreId(Mage::app()->getStore()->getId());

foreach($postData['super_attribute'] as $simpleProdId => $simpleProdConfig){

    $cartParams = array();

    $cartParams = array(
        'super_attribute' => $simpleProdConfig['super_attribute'],
        'qty' => $simpleProdConfig['qty'],
    );

    //Passing id instead of instance of the parent product here
    $this->_getCart()->addProduct($parentProduct->getId(), $cartParams);

}

$this->_getCart()->save();

$this->_getSession()->setCartWasUpdated(true);
person Diwaker Tripathi    schedule 10.05.2016
comment
Предлагаемое вами решение по передаче parentProductId тоже сработало для меня. Для получения дополнительной информации мы должны увидеть следующую общедоступную функцию app \ code \ core \ Mage \ Checkout \ Model \ Cart.php addProduct ($ productInfo, $ requestInfo = null) И защищенную функцию _getProduct ($ productInfo) - person Mukesh; 12.08.2016

создать собственный модуль в etc / config.xml добавить

<?xml version="1.0"?>
<config>
    <modules>
        <Package_Mymodule>
            <version>0.1.0</version>
        </Package_Mymodule>
    </modules>
    <global>
        <models>
            <checkout>
                <rewrite>
                    <cart>Package_Mymodule_Model_Checkout_Cart</cart>
                </rewrite>
            </checkout>
        </models>
    </global>
</config>

и создайте файл по следующему пути Package / Mymodule / model / Checkout / Cart.php

class Package_Mymodule_Model_Checkout_Cart extends Mage_Checkout_Model_Cart{
    public function addProduct($productInfo, $requestInfo=null){   
        $producstChildId = $requestInfo['product_child_id'];

        foreach ($producstChildId as $key => $value){
            $requestInfo['qty'] = current($value);

            if($requestInfo['qty']){    
                //It is the size of the product     
                $requestInfo['super_attribute'][133] = key($value);

                $product = Mage::getModel('catalog/product')
                    ->setStoreId(Mage::app()->getStore()->getId())
                    ->load($requestInfo['product'])
                    ->setConfiguredAttributes(array('super_attribute'=>$requestInfo['super_attribute']));           
                parent::addProduct($product,$requestInfo);
            }
        }
    }
}
person Davin anaya    schedule 13.03.2016