Magento: add configurable products to cart programmatically - magento

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();

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.

Getting error while Add to Cart programmatically with custom options

I am trying to Add Products to Cart with respect to customer (programmatically) but getting error "Invalid request for adding product to quote". I have both Simple products (with custom options) and configurable products. Below is my code. Please help. Many thanks in advance.
public function addtocartAction(){
try {
$cusId = $this->getRequest()->getParam('cusId');
$customer = Mage::getModel('customer/customer')->load($cusId);
$quote = Mage::getModel('sales/quote')->loadByCustomer($customer);
$quoteId = $quote->getId();
//$products = $this->getRequest()->getParam('products');
$products = json_decode('[{"proId": "906","proQty": "1", "options":{"17":"wq","16":"18"}}]');
foreach($products as $product) {
/*if (!$product->getId()) {
throw new Exception();
}*/
foreach ($product->options as $optKey => $optValue) {
$optAll[$optKey] = $optValue;
}
$mainProduct = Mage::getModel('catalog/product')->load($product->proId);
$params = array(
'product' => $product->proId,
'qty' => $product->proQty,
'options' => $optAll
);
echo "<pre />"; print_r($params);
$quote->addProduct($mainProduct, $params);
$quote->setIsActive(1);
$quote->collectTotals()->save();
}
$rslt['success'] = '1';
$rslt['message'] = 'Product has been succefully added to cart';
}
catch(Exception $e){
$rslt['success'] = '0';
$rslt['message'] = $e->getMessage();
}
print_r(json_encode($rslt));
}
Try using cart instead of quote.
This works for me:
$cart = Mage::getModel('checkout/cart');
$mainProduct = Mage::getModel('catalog/product')->load($product->proId);
$params = array(
'product' => $product->proId,
'qty' => $product->proQty,
'options' => $optAll
);
$cart->init();
$cart->addProduct($mainProduct, $params);
$cart->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);

Magento - add product to cart with custom option using PHP

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.

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());

Get Selected Custom option of a product in a custom page (Magento)

I am trying to show the products in shopping cart in a panel which is accessible in all pages(in menu). I have accomplished it by using below
$cartHelper = Mage::helper('checkout/cart');
$items = $cartHelper->getCart()->getItems();
but i am struggling with showing the Custom option selected for each product.
I tried using
$item->getOptionList()
but its not working for me..
Please give me a hand on this.
Thanks,
Balan
I found the answer, below code would print the custom option selected
$options = array();
if ($optionIds = $item->getOptionByCode('option_ids')) {
$options = array();
foreach (explode(',', $optionIds->getValue()) as $optionId) {
if ($option = $item->getProduct()->getOptionById($optionId)) {
$quoteItemOption = $item->getOptionByCode('option_' . $option->getId());
$group = $option->groupFactory($option->getType())
->setOption($option)
->setQuoteItemOption($quoteItemOption);
$options[] = array(
'label' => $option->getTitle(),
'value' => $group->getFormattedOptionValue($quoteItemOption->getValue()),
'print_value' => $group->getPrintableOptionValue($quoteItemOption->getValue()),
'option_id' => $option->getId(),
'option_type' => $option->getType(),
'custom_view' => $group->isCustomizedView()
);
}
}
}
if ($addOptions = $item->getOptionByCode('additional_options')) {
$options = array_merge($options, unserialize($addOptions->getValue()));
}
thanks goes to http://www.e-commercewebdesign.co.uk see
this link for reference.
$cart = Mage::getModel('checkout/cart')->getQuote();
foreach ($cart->getAllVisibleItems() as $item) {
$options = Mage::helper('catalog/product_configuration')->getCustomOptions($item);
}

Resources