Magento – Add Virtual products to cart with custom options programmatically

cartcustom-optionsvirtual

I am working on the virtual products add to cart. I had written my custom code for add to cart and called the function on ajax call.Below is the code for the addtocart

$_product = Mage::getModel('catalog/product')->load($proid);
$_product->setIsRecurring('1');
$_product->setRecurringProfile(array(
    'start_date_is_editable' => 0,
    'schedule_description' => "Test",
    'suspension_threshold' => 1,
    'bill_failed_later' => 1,
    'period_unit' => day,
    'period_frequency' => 12,
    'period_max_cycles' => 1
));

$_product->save();
    $params = array(
        'product' => $proid, // This would be $product->getId()
        'qty' => 1,
);

$cart = Mage::getModel('checkout/cart');
$cart->init();
$cart->addProduct($_product,$params);
$cart->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);

Now when i am adding this product to cart i am getting following error.

a:5:{i:0;s:46:"Please specify the product required option(s).";i:1;s:1227:"#0

when i had looked why this is happening i had found that i had specified custom options for the products and it is specified as Required.Please See Below Image.

enter image description here

see the product page.this is not the default product page of magento. the product page is as follow

enter image description here

how can i set the selected custom option value to cart.which is required.

Please Help Me.

I tried many solutions but not worked.

Thanks

Best Answer

To add product with required custom option to cart you need your $params array to be like this

$params = array(
    'product' => $proid, // This would be $product->getId()
    'qty' => 1,
    'options' => array(
        'option_id' => 'option_value'
    )
);

Where

option_id - custom option id

option_value - selected custom option value

This will help you to get all product custom options data

foreach ($product->getOptions() as $option) {
    print_r($option);
    $values = $option->getValues();
    foreach ($values as $value) {
        print_r($value);
    }
}
Related Topic