Why does the second product dynamically added to the cart loose it's options in Magento2 - magento

I am dynamically adding products to the cart in Magento2 with some custom options. Every product has the same base product id with different options. Represent Product has been properly overridden so that all products added to the cart are separate. However with this code, the second product added will lose it's custom options:
$magento_product = $this->productRepository->get('simple-product-1');
$params = array(
'product' => $magento_product->getId(),
'qty' => intval(5),
'options' => array(
'cr_price' => 12.0,
'Product' => "Test P",
'cr_XML' => '<root></root>'
),
);
$this->cart->addProduct($magento_product, $params);
$params = array(
'product' => $magento_product->getId(),
'qty' => intval(10),
'options' => array(
'cr_price' => 14.0,
'Product' => "Test P2",
'cr_XML' => '<root></root>'
),
);
$this->cart->addProduct($magento_product, $params);
$this->cart->save();
Only the first product has an entry in the quote_item_option table.
Any thoughts on why or how to fix would be appreciated.

Force reloading the product between each add fixes this issue.
$this->productRepository->get('simple-product-1', false, null, true);
The last true parameter is forceReload.

Related

I want to add products in cart with custom labels on cart page

I have tried several methods to add products to cart programatically but i want to show the quote item labels as well one cart page. Can anyone help me to do this or any references?
You can use the below code in your observer.
$item = ( $item->getParentItem() ? $item->getParentItem() : $item);
$additionalOptions = array(array(
'code' => 'option_code',
'label' => 'Some_option_Label',
'value' => 'Option_Value'
));
$item->addOption(array(
'code' => 'additional_options',
'value' => serialize($additionalOptions),
));
// Enable super mode on the product.
$item->getProduct()->setIsSuperMode(true);
here is the code you are looking for;)
<?php
$loadProductData = Mage::getModel('catalog/product')->load($productId);
$quote = Mage::getSingleton('checkout/session')->getQuote();
$OrderquoteItem = Mage::getModel('sales/quote_item');
$quoteItem = $OrderquoteItem->setProduct($loadProductData);
//custom options to show user on cart page
$a_options = array(
'options' => array(
'label' => 'OptionLabel :',
'value' => "OptionaValue",
));
//add above options array to this cart item which is going to get added on cart
$quoteItem->addOption(array(
'code' => 'additional_options',
'value' => serialize($a_options),
));
// set price and quantity
$quoteItem->setQuote($quote)
->setQty($productOptions['qty'])
->setOriginalCustomPrice($productOptions['price'])
->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);

Magento, precomplete custom options while creating/editing a product in admin

I’m trying to precomplete custom options during the process of creating or editing a product in the Magento admin : after product type choice.
I add an event trigger on the Mage_Adminhtml_Block_Catalog_Product_Edit_Tabs _prepareLayout function. So basically when you open the edition or creation of a product, the event is triggered.
My aim is : when you start editing your new product, 3 custom options are already present in the “Custom Options” tab.
I can’t trigger it with the catalog_product_save_before event because one option is a dropdown type and have to be filled by the admin.
So i’ve coded my observer and succeeded to modify the product name with setName() function, but I can"t find how to precomplete/add custom options.
I tried with the code of the following blog : http://kamal250.wordpress.com/2012/10/22/create-custom-option-programatically-while-creating-product/#comments
But it doesn’t seems to work.
Anyone can help me with that ?
Here is my code in the observer :
$option_data = array(
'is_delete' => 0,
'is_require' => true,
'previous_group' => '',
'title' => 'Height',
'type' => 'field',
'price_type' => 'fixed',
'price' => '0',
'sort_order' => 1,
'values' => array()
);
$product->setHasOptions(1);
$product->setCanSaveCustomOptions(1);
$product->setOptions(array($option_data));
$product->setProductOptions(array($option_data));
$opt = Mage::getSingleton('catalog/product_option');
$opt->setProduct($product);
$opt->addOption($option_data);
$opt->saveOptions();
$product->setOption($opt);
Finally i have found the solution :
I modified the trigger to the action of opening the custom options tab.
And here is my code in the observer :
$product = $observer->getProduct();
$option_data = array(
'is_delete' => 0,
'is_require' => true,
'previous_group' => '',
'title' => 'Height',
'type' => 'field',
'price_type' => 'fixed',
'price' => '0',
'sort_order' => 1
);
$product->setHasOptions(1);
$option = Mage::getModel('catalog/product_option')->setProductId($product->getId())->setStoreId($product->getStoreId())->addData($option_data);
$option->save();
$product->addOption($option);
Hope it will help someone sooner or later.
See ya.

Add product with custom option to existing Order

$quoteItem = Mage::getModel('sales/quote_item')->setProduct($product)
->setQuote(Mage::getModel('sales/quote')->load($order->getQuoteId()));
$orderItem = Mage::getModel('sales/convert_quote')->itemToOrderItem($quoteItem)->setProduct($product);
this is the code i use to add a simple product to existing order , but i am having issues adding custom option product to the order.
$quoteItem->addOption(new Varien_Object(
array(
'product' => $quoteItem->getProduct(),
'code' => 'option_ids',
'value' => 1 // 45,46,55
)
));
$quoteItem->addOption(new Varien_Object(
array(
'product' => $quoteItem->getProduct(),
'code' => 'option_1', //45
'value' => 2 // ‘White’
)
));
after the first line , but no success.
Any help please.
Thanks
There is one method to change exitsting order:
http://prattski.com/2013/04/22/magento-adding-items-to-existing-orders/

Magento: How to create a product during a setup script?

I am creating a module that needs the presence of one special product.
Did anybody manage to create a new product during a module's setup script?
There are several problems arising, for example Mage_Core_Model_App::getStore() is returning the default store as updateMode is set to true.
I fixed the problem
Call to a member function getStoreIds() on a non-object in
Mage/Catalog/Model/Resource/Abstract.php on line ...
by adding the following code at the beginning of my data upgrade script where i create products:
Mage::app()->getStore(Mage_Core_Model_App::DISTRO_STORE_ID)->setWebsiteId(1);
It is a workaround, but i could not find any other solution.
I think it should work with a data update script (mysql4-data-upgrade-1.0.0-2.0.0.php). In the data Mage_Core_Model_Resource_Setup::applyAllDataUpdates() function the update mode is - in contrast to the normal update scripts - not set to true. The update mode causes problems with creating products.
Try the below script for creating a product using SQL setup resource file
// Create Default Products
$product = Mage::getModel('catalog/product');
$data = array(
'attribute_set_id' => $attributeSetId,
'type_id' => 'simple',
'store_id' => 0,
'category_ids' => array($category->getId()),
'website_ids' => array(0),
'sku' => 'sample-product',
'name' => 'Sample Product',
'description' => 'Sample Product',
'short_description' => 'Sample Product',
'status' => 1,
'visibility' => 4,
'weight' => 1,
'price' => 100.00,
'setcustomdefault' => 1,
'tax_class_id' => 0,
'rearimage' => 'rear.png',
'frontimage' => 'front.png',
'defaultimage' => 'thumb.jpg',
'stock_data' => array('is_in_stock' => 1,'qty' => 20),
'created_at' => strtotime('now')
);
$product->addData($data)
->setInitialSetupFlag(true)
->save();
Here is a piece of code to create a product programatically:
require_once 'app/Mage.php';
Varien_Profiler::enable();
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
umask(0);
Mage::app();
$product = new Mage_Catalog_Model_Product();
// Build the product
$product->setSku('some-sku-value-here');
$product->setAttributeSetId('some_int_value_of_some_attribute');
$product->setTypeId('simple');
$product->setName('Some cool product name');
$product->setCategoryIds(array(7)); # some cat id's, my is 7
$product->setWebsiteIDs(array(1)); # Website id, my is 1 (default frontend)
$product->setDescription('Full description here');
$product->setShortDescription('Short description here');
$product->setPrice(39.99); # Set some price
# Custom created and assigned attributes
$product->setHeight('my_custom_attribute1_val');
$product->setWidth('my_custom_attribute2_val');
$product->setDepth('my_custom_attribute3_val');
$product->setType('my_custom_attribute4_val');
//Default Magento attribute
$product->setWeight(4.0000);
$product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH);
$product->setStatus(1);
$product->setTaxClassId(0); # My default tax class
$product->setStockData(array(
'is_in_stock' => 1,
'qty' => 99999
));
Mage::helper('core')->p($product->getData());
After that to save it use $product->save();
Play with this code to get an ideea what it does.

magento: add attibute to product, but not show up when editing the product

As per bens comment and answer I updated my script, comments indicate changes
{Magento 1.4.0.1} currently i have an installer script:
$installer = $this;
$installer->startSetup();
//commented out to use factory method
//$setup = new Mage_Catalog_Model_Resource_Eav_Mysql4_Setup('core_setup');
$setup = Mage::getResourceModel('catalog/setup','core_setup');
if(!$setup->getAttribute('catalog_product','attribute_code')){
$newFields = array(
'attribute_code' => array(
'type' => 'text',
'label' => 'Attribute Label',
//added visible option
'visible' => false,
),
);
$entities = array(
'catalog_product',
);
foreach($newFields as $attributeName => $attributeDefs) {
foreach ($entities as $entity) {
$setup->addAttribute($entity, $attributeName, array(
'type' => $attributeDefs['type'],
'label' => $attributeDefs['label'],
//added visible option
'visible' => $attributeDefs['visible'],
'class' => '',
'required' => false,
));
}
}
}
$installer->endSetup();
It works wonderfully! Except the attribute shows up in the General attribute group when editing the product and I don't want it to show up at all (its a secret ninja attribute) is there something I'm doing wrong? or perhaps something I should be doing to let Magento know not its not supposed to show up?
Using addAttribute() you can set the 'visibleindex tofalse. UsingupdateAttribute()` you should do the following:
$setup->updateAttribute('catalog_product','attr_code','is_visible',false);
Let me know if I'm wrong.

Resources