7

I am trying to add a product to the cart programmatically with some custom options. The item gets added to the cart correctly but none of the options ever get added. My code is:

require_once '../../app/Mage.php';
umask(0);
/* not Mage::run(); */
Mage::app('default');

Mage::getSingleton("core/session", array("name" => "frontend"));

$product_id = 2364;
$id_opt_value = 6072;
$final_opt_value = 6074;

$product = Mage::getModel('catalog/product')->load($product_id);
$cart = Mage::getModel('checkout/cart');
$cart->init();
$params = array(
    'product' => $product_id,
    'qty'     => 1,
    'options' => array(         
        $id_opt_value => '123456',
        $final_opt_value => 'black gloss finish',
     )
);

$cart->addProduct($product, $params);
$cart->save();

I have double checked and the option values are correct. I am using magento ce-1.9.0.0

1

Creating a quote may help instead of using Checkout/Cart Model.

$quote = Mage::getModel('sales/quote')
            ->setStoreId(Mage::app()->getStore('default')->getId());

set your products $params here.

force the Varien_Object with your parameters to addProduct

$quote->addProduct($product, new Varien_Object($params));
$quote->save();
| improve this answer | |
0

I think that your option array has some incorrect formatting. I think the array should be in the following format.

$params = array(
    'product' => $product_id,
    'qty'     => 1,
    'options' => array(
        '123456' => 'black gloss finish',
     )
);

Where the key is the option id and the value is the option value.

The alternative to this would be to work directly with the quote and quote item and use the function addOption to the quote item.

| improve this answer | |
0

It will not work like this.

$params = array(
    'product' => $product_id,
    'qty'     => 1,
    'options' => array(
        '123456' => 'black gloss finish',
     )
);

on the place of 123456 you have to put the numeric number for that custom option's id. for example if the id is 'options_2_text' then pass '2' insted of '123456'. For more clearance use this code on cart.html page:

foreach($this->getItems() as $product) {
    $options = $product->getProduct()->getTypeInstance(true)->getOrderOptions($product->getProduct());
    if ($options)
    {
        if (isset($options['options']))
        {
            $result = $options['options'];
            echo '<pre>';
                print_r($result);
            echo '</pre>';    
        }
    }
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.