Please bear with me, I'm new to Magento and PHP.
I've been looking for hours for this but unfortunately I cannot make it to work. All other questions made didn't explained where to get the variables.
Can someone explain to me how to get this working?
I don't know which parameters to pass to the code to add the product to the cart…
What I need to do is to include a custom product to the cart after a person chose it from different options on a form
. I have the form
working.
I guess I need to modify the code below with ID's and such, but I have no idea where to get the data I need to fill in…
// Add a product (simple); id:12, qty: 1
$cart->addProduct(12, 1);
// Add a product with custom options
$productInstance = Mage::getModel('catalog/product')->load($productId);
$param = array(
'product' => $productInstance->getId(),
'qty' => 1,
'options' => array(
234 => 'A value' // Custom option with id: 234
)
);
This is what I have:
require_once '../app/Mage.php';
umask(0);
Mage::init('default');
Mage::getSingleton('core/session', array('name' => 'frontend'));
// Get customer session
$session = Mage::getSingleton('customer/session');
// Get cart instance
$cart = Mage::getSingleton('checkout/cart');
$cart->init();
// Add a product (simple); id:12, qty: 1
$cart->addProduct(12, 1);
// Add a product with custom options
$productInstance = Mage::getModel('catalog/product')->load($productId);
$param = array(
'product' => $productInstance->getId(),
'qty' => 1,
'options' => array(
234 => 'A value' // Custom option with id: 234
)
);
$request = new Varien_Object();
$request->setData($param);
$cart->addProduct($productInstance, $request);
// Set shipping method
$quote = $cart->getQuote();
$shippingAddress = $quote->getShippingAddress();
$shippingAddress->setShippingMethod('flatrate_flatrate')->save();
// update session
$session->setCartWasUpdated(true);
// save the cart
$cart->save();
—Edit—
This is the message I get:
Fatal error: Uncaught exception 'Mage_Core_Exception' with message 'Please specify the product required option(s).' in C:\xampp\htdocs\inc\app\Mage.php:595 Stack trace: #0 C:\xampp\htdocs\inc\app\code\core\Mage\Checkout\Model\Cart.php(284): Mage::throwException('Please specify ...') #1 C:\xampp\htdocs\inc\mixform\form.php(71): Mage_Checkout_Model_Cart->addProduct(Object(Mage_Catalog_Model_Product), Array) #2 {main} thrown in C:\xampp\htdocs\inc\app\Mage.php on line 595
Best Answer
This is kind of difficult to answer without knowing what kind of custom options you've set up for this product. I suggest logging
$param
from the cart controller add action.Enable logging in system configuration, temporarily place this code in
Mage_Checkout_CartController::addAction
, and go add the product with the custom options to the cart on the frontend.Examine what
$params
looks like and build it accordingly in your script.