2
votes

I'm working on a add product by sku form for a e-commerce website I'm developing. I made the form which basically has 2 fields, "cod" and "qt".

I've passed that to this script (edited):

<?php
    $sku = $_POST['cod'];
    $qty = $_POST['qt'];
    $product = new Mage_Catalog_Model_Product();
    $cart = Mage::getSingleton('checkout/cart');

    $osids = array();

    foreach ($sku as $lol){
        $lolz = Mage::getModel('catalog/product')->loadByAttribute('sku',$lol)->getId();
        array_push($osids, $lolz);

    }
var_dump($osids);

$params = array(
    'qty' => 2,
);
$cart->addProductsByIds($osids, $params);
$cart->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);


?>

The var_dump displays the array correctly, ie. multiple skus when that's the case, but the foreach loop only adds the first sku in the array to the shopping cart.

Any idea why?

I wan't it to add all the sku's in the array.

1
I would suggest you to add the product by url it would be easy and u dont have write any code just have to pass the sku and quantity by querystring and magento would do the restchanz
That would be fine for one SKU, but it doesn't work for multiple SKU's does it?pedropeixoto

1 Answers

5
votes

Try the following code :

<?php
    $sku_list = $_POST['cod'];
    $qty = $_POST['qt'];
    $cart = Mage::getSingleton('checkout/cart');

    foreach ($sku_list as $sku){
        $product = Mage::getModel('catalog/product')->loadByAttribute('sku',$sku);
        $cart->addProduct($product, $qty);
    }
    $cart->save();
    Mage::getSingleton('checkout/session')->setCartWasUpdated(true);