Magento – Add product to cart programmatically with file type custom options

custom-optionsmagento-1.9

I am trying to add products to cart programmatically having custom options of type file. Basically, there is a separate interface for some products in the shop where customer can customize the image being ordered. It's working with some external API which saves the final image on server and returns the path on the basis of which I'm going to add that into the custom option of product.

What I am trying to do is add that image into the custom option of product. Tried several methods but no success. Found this question but no answer there.

This is what I have tried so far, but it keeps giving me error that required options is missing.(That image option is required)

$path = Mage::getBaseDir();
$product_id = 1;
$product = Mage::getModel('catalog/product')->load($product_id);
$cart = Mage::getModel('checkout/cart');
$cart->init();
$params = array(
    'product' => $product_id,
    'qty' => 1,
    'options_1_file_action' => array(
    1 => array(
        'quote_path' => $image,
        'secret_key' => substr(md5(file_get_contents($path . DS . $image)), 0, 20)),
        )
    );
$cart->addProduct($product, $params);
$cart->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);

Also found this piece somewhere, but it depends upon FILES variable, so can't use it as there is no post from front.

$product_id = 1;
$product = Mage::getModel('catalog/product')->load($product_id);
$cart = Mage::getModel('checkout/cart');
$cart->init();
$params = array(
    'product' => $product_id,
    'qty' => 1,
    'options_1_file_action' => 'save_new',
    'options_1_file' => array(
        'name' => $image,
        'type' => 'application/octet-stream',
        'tmp_name' => $image
    )
);
$cart->addProduct($product, $params);
$cart->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);

Best Answer

You can follow:

$cart = Mage::getSingleton('checkout/cart');
$cart->init();

$product = Mage::getModel('catalog/product')->load(1112);

$paramater = array('product' => '1112',
                    'qty' => '12',
                    'form_key' => Mage::getSingleton('core/session')->getFormKey(),
                    'options' => array('option_id'=>'sub_option_id')
            );       

$request = new Varien_Object();
$request->setData($paramater);
$cart->addProduct($product, $request);
$cart->save();

If custom option is not required for this product that time this code will use. Otherwise, you change the base file of magento

Related Topic