Magento - add product to cart with custom option using PHP - magento

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

Try to use Varien Object:
$request = new Varien_Object();
$request->setData($param);
$cart->addProduct($productInstance, $request);
Should work as well.

Related

Set Product Custom Options From Observer Magento 1.9

I am trying to add custom options to products on save. I want to add or update custom options (not additional options) on before_product save. I am able to access the observer and it is working on save as well but unable to update the custom options. Create option code is working if run from standalone script but not from observer only.
This is my observer code
`class Company_Module_Model_Observer{
public function updateOptions($observer){
$product = $observer->getEvent()->getProduct();
$categories= $product->getCategoryIds();
$currentCategory = '';
foreach ($categories as $cat_id){
$cat = Mage::getModel('catalog/category')->load($cat_id);
$currentCategory = $cat->getName();
}
$skuList =['LAPTOP_','DESKTOP_'];
$upgrades = $optionValues = [];
if($currentCategory=='Laptops'){
$_productCollection = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToFilter('sku', array('like' => 'LAPTOP_%'));
$upgrades = $_productCollection;
}
$meta = "6 this is product meta with custom plugin ".$product->getName();
foreach ($upgrades as $products) {
$_product = Mage::getModel('catalog/product')->load($products->getId());
$optionValues = array(
'title' => $_product->getName(),
'price' => $_product->getPrice(),
'price_type' => 'fixed',
'sku' => $_product->getSku(),
'sort_order' => 0,
);
}
$options = array(
'title' => 'Upgrades',
'type' => 'drop_down',
'is_required' => 0,
'sort_order' => 0,
'values' => $optionValues
);
$product->setMetaDescription($meta);
$product->setProductOptions(array($options));
$product->setCanSaveCustomOptions(true);
//if uncomment this then save loop continues and site hangs
//$product->save();
}
}`
No error in logs or anything else. Please guide me how I can achieve this.
You are in an infinite loop because the observer relaunches the same function each time, so when you run the save product function ( $product->save(); ), your function is rerun, and so on.
If you use the event catalog_product_save_before observer, you don't have to run the save function.
otherwise here:
foreach ($categories as $cat_id){
$cat = Mage::getModel('catalog/category')->load($cat_id);
$currentCategory = $cat->getName();
}
You get the last category in the collection, is that correct?
I know this is a bit late, but I had a similar issue like this a while back...
You are calling $product->setProductOptions() which without knowing your code I can only guess is setting it on the $product's _data array, which is probably not what you want. You need to stick it on the $product's option instance which will be used during the $product->_afterSave() call (You can see where the custom options are being saved in Mage_Catalog_Model_Product _afterSave() (~line 554 as of 1.9.4.5)). You can get the option instance like this: $optionInstance = $product->getOptionInstance() and set your options like this: $optionInstance->addOption($options). After you do that you should be able to allow the save to continue and your custom options should be created.

Magento - add to cart a product with advanced custom options setting option QTY

I am running Magento 1.9 with Advanced Custom Options by MageWorx. I am creating a module that needs to add a product with custom options to the cart. With the code below I can add the product to the cart with 1 option. Yet I can't figure out how to add a certain quantity for the custom option.
$product = $this->getProduct();
$product_id = $product->getId();
$product = Mage::getModel('catalog/product')->load($product_id);
$cart = Mage::getModel('checkout/cart');
$cart->init();
$params = array(
'product' => $product_id,
'qty' => 1,
'options' => array(
'1' => 1,
)
);
try {
$cart->addProduct($product, $params);
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
$cart->save();
echo '<div class="shiptext">Your order has been add to your cart.</div><br clear="all">';
}
catch (Exception $ex) {
echo $ex->getMessage();
}
Maybe I can't increase the QTY this way as Magento core doesn't support QTY for custom options? Which case I am guessing I may need to use some class inside of the Advanced Custom Options module but I am not sure how I would do that. If anyone has experience with Advanced Custom Options, it would be greatly appreciated as to how one might do this.
Found the answer. You need to add the to the prams options_groupid_qty.
$params = array(
'product' => $product_id,
'qty' => 1,
'options' => array(
'1' => 1,
),
'options_1_qty' => 30
);

Magento: add configurable products to cart programmatically

How to add the child product to cart programmatically?
I've a child product SKU, I want to
Fetch the supper attributes like size and color id and values from the products,
Then fetch the parent product id,
Pass the super attributes on param with quantity, to add to function cart.
//$cart->addProduct($product1, $options);
Here, how to pass the supper attributes on the $option variable? Please help me!!!!
Try this. I think it may need some improvements but it works good in simple cases.
$_product = $this->getProduct();
$parentIds = Mage::getResourceSingleton('catalog/product_type_configurable')->getParentIdsByChild($_product->getId());
// check if something is returned
if (!empty(array_filter($parentIds))) {
$pid = $parentIds[0];
// Collect options applicable to the configurable product
$configurableProduct = Mage::getModel('catalog/product')->load($pid);
$productAttributeOptions = $configurableProduct->getTypeInstance(true)->getConfigurableAttributesAsArray($configurableProduct);
$options = array();
foreach ($productAttributeOptions as $productAttribute) {
$allValues = array_column($productAttribute['values'], 'value_index');
$currentProductValue = $_product->getData($productAttribute['attribute_code']);
if (in_array($currentProductValue, $allValues)) {
$options[$productAttribute['attribute_id']] = $currentProductValue;
}
}
// Get cart instance
$cart = Mage::getSingleton('checkout/cart');
$cart->init();
// Add a product with custom options
$params = array(
'product' => $configurableProduct->getId(),
'qty' => 1,
'super_attribute' => $options
);
$request = new Varien_Object();
$request->setData($params);
$cart->addProduct($configurableProduct, $request);
$session = Mage::getSingleton('customer/session');
$session->setCartWasUpdated(true);
$cart->save();
}
U can try.
$cart = Mage::getModel('checkout/cart');
$cart->init();
$productCollection = Mage::getModel('catalog/product')->load($productId);
$cart->addProduct($productCollection ,
array( 'product_id' => $productId,
'qty' => 1,
'options' => array( $optionId => $optionValue));
$cart->save();

Magento create order programmatically with downloadable product

I have been successful creating orders with a Custom controller and all works well. My issue is i need to add the ability to create orders with downloadable product. I would just like to be pointed on where to start.
Controller is handling all the set up and the order save. Is there a Action or something I need to hit for the customer to be able to access his/her downloads?
Try the below Code, please go threw comments.
<?php
require_once 'app/Mage.php';
Mage::app();
$customer = Mage::getModel("customer/customer")
->setWebsiteId(Mage::app()->getStore()->getWebsiteId())
->loadByEmail($data['email']);
if(!$customer->getId()) {
$customer->setEmail($email); //enter Email here
$customer->setFirstname($fname); //enter Lirstname here
$customer->setLastname($lname); //enter Lastnamre here
$customer->setPassword(password); //enter password here
$customer->save();
}
$storeId = $customer->getStoreId();
$quote = Mage::getModel('sales/quote')
->setStoreId($storeId);
$quote->assignCustomer($customer);
// add product(s)
$product = Mage::getModel('catalog/product')->load(186); //product id
/*$buyInfo = array(
'qty' => 1,
'price'=>0
// custom option id => value id
// or
// configurable attribute id => value id
);*/
$params = array();
$links = Mage::getModel('downloadable/product_type')->getLinks( $product );
$linkId = 0;
foreach ($links as $link) {
$linkId = $link->getId();
}
//$params['product'] = $product;
$params['qty'] = 1;
$params['links'] = array($linkId);
$request = new Varien_Object();
$request->setData($params);
//$quoteObj->addProduct($productObj , $request);
/* Bundled product options would look like this:
$buyInfo = array(
"qty" => 1,
"bundle_option" = array(
"123" => array(456), //optionid => array( selectionid )
"124" => array(235)
)
); */
//$class_name = get_class($quote);
//Zend_Debug::dump($class_name);
$quote->addProduct($product, $request);
$addressData = array(
'firstname' => 'Vagelis', //you can also give variables here
'lastname' => 'Bakas',
'street' => 'Sample Street 10',
'city' => 'Somewhere',
'postcode' => '123456',
'telephone' => '123456',
'country_id' => 'US',
'region_id' => 12, // id from directory_country_region table if it Country ID is IN (India) region id is not required
);
$billingAddress = $quote->getBillingAddress()->addData($addressData);
$shippingAddress = $quote->getShippingAddress()->addData($addressData);
/*$shippingAddress->setCollectShippingRates(true)->collectShippingRates()
->setShippingMethod('flatrate_flatrate')
->setPaymentMethod('checkmo');*/
/* Free shipping would look like this: */
$shippingAddress->setFreeShipping( true )
->setCollectShippingRates(true)->collectShippingRates()
->setShippingMethod('freeshipping_freeshipping')
->setPaymentMethod('checkmo'); /* shipping details is not required for downloadable product */
$quote->setCouponCode('ABCD'); // if required
/* Make Sure Your Check Money Order Method Is Enable */
/*if the product value is zero i mean free product then the payment method is free array('method' => 'free')*/
$quote->getPayment()->importData(array('method' => 'checkmo'));
$quote->collectTotals()->save();
$service = Mage::getModel('sales/service_quote', $quote);
$service->submitAll();
$order = $service->getOrder();
printf("Order Created Successfully %s\n", $order->getIncrementId());

Custom Add to Cart With Products Custom Atribute In Magento

I have tried to add the products to cart using custom module. Below is the code i used
$product_id = $this->getRequest()->getParam('product');
$product = Mage::getModel('catalog/product')->load($product_id);
$param = array( 'product' => $product->getId(), 'qty' => 2,'options["'.$option_id.'"]' => $option_type_id );
$cart = Mage::getModel('checkout/cart')->init();
$cart->addProduct($product, new Varien_Object($param));
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
$cart->save();
I can add the products name, quantity to cart using product id, But i cannot able to add the products custom options in cart.
Please give me a hand on this.
Thanks,
Prakash
You're so close! The main thing that you need to change is your $param, as it is not structured the way Magento would like. This should do the trick:
$param = array(
'product' => $product->getId(),
'qty' => 2,
'options' => array(
$option_id => $option_value,
$option_id2 => $option_value2,
),
);
Note that any required custom options on your product will need to have values to avoid a fatal error whilst adding to the cart. Also, no need to cast $param as a Varien_Object - Magento understands the array just fine.

Resources