How to update custom options programatically in magento? - php

I have lot of products with custom options, now I have requirement to update only custom options through csv file. so how we can do this programatically?

i found one solution for updating custom options programatically here is the solution
$product = Mage::getModel('catalog/product')->load($product_id);
$values = array();
foreach ($product->getOptions() as $o) {
$p = $o->getValues();
}
}
foreach($p as $v)
{
$values[$v->getId()]['option_type_id']= $v->getId();
$values[$v->getId()]['title']= 'test';
$values[$v->getId()]['price']= 23;
$values[$v->getId()]['price_type']= 'fixed';
$values[$v->getId()]['sku']= $value1;
}
$v->setValues($values);
$v->saveValues();
$product->save();
hope this help someone
this only update custom options value

I think this is also useful...
If you are customize the products .
<?php
$magePath = 'app/Mage.php';
require_once $magePath;
Varien_Profiler::enable();
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
umask(0);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$product_ids = array(1,2,167);
$productmodel = Mage::getModel('catalog/product');
foreach ($product_ids as $product_id) {
/**i use this two arrays for collecte value because i uses inside setData of
current option*/
$cos=array();
$co=array();
$product = $productmodel->load($product_id);
$options = $product->getProductOptionsCollection();
if (isset($options)) {
foreach ($options as $o) {
$title = $o->getTitle();
/**
this block is for changing information of specific option from collection options inside
current product
the save method for this option in end of code
*/
if ($title == "Line 1/Front") {
$o->setProduct($product);
$o->setTitle("Line 1/Ftont");
$o->setType("drop_down");
$o->setIsRequire(1);
$o->setSortOrder(0);
}
/**
this block for update or add information of specific value inside current option
*/
$optionType = $o->getType();
//test type
if ($optionType == "drop_down") {
//getting collection of value related to current option
$values = $o->getValuesCollection();
$found = false;
foreach ($values as $k => $v) {
//test existing of value for update
if (1 == preg_match("/said$/i", $v->getTitle())) {
//update and save
$v->setTitle("morad")
->setSku("kk")
->setPriceType("fixed")
->setSortOrder(0)
->setPrice(floatval(13.0000));
$v->setOption($o)->save();
/**
this ligne is important i collecte all value required for normalize save function
related to current option
*/
$cos[]=$v->toArray($co);
}
}
/**
create new value object you can use $option->getValueInstance() for working with
getSingleton
*/
$value = Mage::getModel('catalog/product_option_value');
$value->setOption($o)
->setTitle('valueiwant')
->setSku("nn")
->setPriceType("fixed")
->setSortOrder(1)
->setPrice(12)
/**
this ligne is important (relation forigien key) for related this new value
to specific option
*/
->setOptionId($o->getId());
$value->save();
/**
this ligne is important i collecte all value required for normalize save function
related to current option
*/
$cos[]=$value->toArray($co);
}
$o->setData("values",$cos)->save();
//var_dump($cos);
}
}
}

Do you create a module to do that ? If you do, you must use the cron system of Magento and call a method of a custom model :
<config>
<!--...-->
<crontab>
<jobs>
<company_test>
<schedule>
<cron_expr>0,15,30,45 * * * *</cron_expr>
</schedule>
<run>
<model>test/testmodel::testMethod</model>
</run>
</company_module>
</jobs>
</crontab>
</config>
When this is done, you can update the option of a specific product by using the model Mage_Catalog_Model_Product_Option. I don't know how the CSV is made, but the algorithm can be something like that :
// foreach option
/** #var $opt Mage_Catalog_Model_Product_Option */
$opt = Mage::getModel('catalog/product_option');
$opt->setProduct($product);
$optionArray = array(
'is_delete' => 0,
'title' => 'Blabla',
'previous_group' => '',
'previous_type' => '',
'type' => 'field', //can be radio, drop_down, file, area...
'is_require' => 0,
'sort_order' => 42,
'values' => array()
);
$opt->addOption($optionArray);
$opt->saveOptions();
// end foreach
Also check this link : http://subesh.com.np/2009/12/adding-custom-options-product-magento/

Related

One product page has different cookie from others

I want to save product id in an array when user opens a product page, and then save that array in a cookie. This is my code:
if(is_product()) {
if(isset($_COOKIE['recent'])) {
$data = unserialize($_COOKIE['recent']);
$product_id = get_the_ID();
if(!in_array($product_id, $data)) {
array_unshift($data, $product_id);
if(count($data) > 8) {
array_pop($data);
}
setcookie('recent', serialize($data), time()+(3600*24*7), "/");
}
echo "SET";
}else{
$data = array();
$product_id = get_the_ID();
array_unshift($data, $product_id);
setcookie('recent', serialize($data), time()+(3600*24*7), "/");
echo "DIDNT SET";
}
print_r($data);
}
Those echos and print_r is for debugging purposes. So if it is a product page, I check whether cookie is already set, if yes, then I just want to add product ID to the array if it is already there and update the value. And if cookie is not set, I'm creating a new array and then printing content of $data.
The problem is, that all, except one product page works fine. For example I can browse through products and see that it prints out the same array over and over again, but one product page has its own array of IDs, which is array of one element - that product element. That product page has no different URL from others. same pattern: website.com/product/productname/
It seems like it has its own scope. Even tough I used "/" for the domain, so I guess it should be the same across all the website?
What is wrong here?
I tested this locally and had similar results. The reason you were getting the output errors in your header was because you were trying to set the initial cookie with an integer instead of a string. That and the WP headers were initialized but the query had not fully processed.
I made a plugin that will run on the template_redirect hook which will allow you to debug much easier. There's also a [recently_viewed] shortcode that'll let you do something with your actual result.
You can drop this in your theme or create a recently_viewed.php in your plugins folder:
https://gist.github.com/simplethemes/4f9b6f969bcc0a0a6668aeed75491a15
/*
Plugin Name: Set Shop Cookie
Description: Adds a cookie for most recently viewed products
Version: 0.1
Author: Casey Lee
Author URL: https://simplethemes.com
*/
class SetWpShopCookie {
/**
* #var string API URL
*/
public static $instance;
public $recent_cookie;
public $cookie_name = 'recent';
public $recent_products;
/** Hook WordPress
* #return void
*/
public function __construct()
{
self::$instance = $this;
add_action( 'template_redirect', array( $this, 'get_recent_cookie') );
add_action( 'template_redirect', array( $this, 'set_post_cookie') );
add_shortcode( 'recently_viewed', array( $this, 'recent_products') );
}
/**
* Gets the 'recent' cookie
* #return array or null
*/
public function get_recent_cookie()
{
$recent_cookie = null;
$cookies = array();
foreach ( $_COOKIE as $name => $value ) {
$cookies[] = new WP_Http_Cookie( array( 'name' => $name, 'value' => $value ) );
}
foreach($cookies as $cookie) {
if ($this->cookie_name == $cookie->name) {
$recent_cookie = $cookie;
break;
}
}
$this->recent_cookie = $recent_cookie;
}
/**
* Load scripts when plugin is executed
* #see https://developer.wordpress.org/reference/classes/wp_http_cookie/
*/
public function set_post_cookie()
{
global $post;
$product_id = $post->ID;
$cookie_time = time() + 60 * 60 * 24 * 7;
// nothing to do here if we're not in a product single
if (!is_product())
return;
// create the cookie
if(!$this->recent_cookie) {
$data = array();
array_unshift($data, $product_id);
setcookie($this->cookie_name, serialize($data), $cookie_time, COOKIEPATH, COOKIE_DOMAIN);
// update existing cookie
} else {
$data = unserialize($this->recent_cookie->value);
if(!in_array($product_id, $data)) {
array_unshift($data, $product_id);
if(count($data) > 8) {
array_pop($data);
}
// Use WP globals for portable cookie settings
setcookie($this->cookie_name, serialize($data), $cookie_time, COOKIEPATH, COOKIE_DOMAIN);
}
}
// Debug
// var_dump($this->recent_cookie);
}
// Recently viewed products shortcode
function recent_products( $atts ) {
// Attributes
$atts = shortcode_atts(
array(
'count' => '5',
),
$atts,
'recently_viewed'
);
$product_data = unserialize($this->recent_cookie->value);
$str = '';
if ($product_data) {
foreach ($product_data as $products_viewed) {
$str .= $products_viewed .' ,';
}
return 'You recently viewed these products: ' . rtrim($str,',');
} else {
return 'Why don\'t you visit our shop?';
}
}
}
new SetWpShopCookie;
It's difficult to say without seeing your output. Try posting a dump of your $data in the context you mention. get_the_ID() is a proxy through get_post(), so you might try setting the ID more reliably with the below. At least then you'll see an error if you don't have a proper object.
global $product;
$product_id = $product->id;

Remove unwanted states from dropdown list in Magento

I am new to magento and I am not able to make out how one can remove the unwanted states from dropdown list in magento. I tried to edit my below function as per this link http://doejo.com/blog/magento-how-to-remove-certain-states-from-state-region-list-at-checkout-or-registration/ but it did not work. Below i sthe code for removing unwanted states but when I add to my class in local folder, not getting any results.
$excludeRegions = array('AE','AA');
foreach ($collection as $region) {
if (!$region->getRegionId()) {
continue;
}
***//Here is the code from the link given
//BOF Custom Logic Here***
$regionCode = $region->getCode();
$this->_select->from(array('region'=>$this->_regionTable),
array('region_id'=>'region_id', 'country_id'=>'country_id', 'code'=>'code', 'default_name'=>'default_name')
)->where('code NOT IN (?)', $exclude_regions);
_getRegions function edited as per above code and link respectively.
protected function _getRegions($storeId)
{
$countryIds = array();
$countryCollection = $this->getCountryCollection()->loadByStore($storeId);
foreach ($countryCollection as $country) {
$countryIds[] = $country->getCountryId();
}
/** #var $regionModel Mage_Directory_Model_Region */
$regionModel = $this->_factory->getModel('directory/region');
/** #var $collection Mage_Directory_Model_Resource_Region_Collection */
$collection = $regionModel->getResourceCollection()
->addCountryFilter($countryIds)
->load();
$regions = array(
'config' => array(
'show_all_regions' => $this->getShowNonRequiredState(),
'regions_required' => $this->getCountriesWithStatesRequired()
)
);
$excludeRegions = array('AE','AA');
foreach ($collection as $region) {
if (!$region->getRegionId()) {
continue;
}
***//Here is the code from the link given
//BOF Custom Logic Here***
$regionCode = $region->getCode();
$this->_select->from(array('region'=>$this->_regionTable),
array('region_id'=>'region_id', 'country_id'=>'country_id', 'code'=>'code', 'default_name'=>'default_name')
)->where('code NOT IN (?)', $exclude_regions);
//EOF Custom Logic Here
$regions[$region->getCountryId()][$region->getRegionId()] = array(
'code' => $region->getCode(),
'name' => $this->__($region->getName())
);
}
return $regions;
}
After making the above changes, I tried below steps as my code is in /app/code/core/Mage/Directory/Helper/Data.php
Create a module Vids_Directory in pool local like app/code/local/Vids/Directory
Create app/etc/modules/Vids_Directory.xml
Create app/code/local/Vids/Directory/etc/config.xml
create app/code/local/Vids/Helper/Data.php

How to create magento helper class?

I have the following magento helper class.
class CommissionJunction extends Mage_Core_Helper_Data
{
/**
* Get SKU, quantity, price and discount amount for each product in a given order
* #param object $order
* #return array
*/
private function _getOrderProductsList($order) {
$orderItems = $order->getAllItems();
$purchasedSkus = array();
$count_orderItems = count($orderItems);
for($i = 0; $i < $count_orderItems; $i++) {
$purchasedSkus[$i] = array(
'ITEM' => $orderItems[$i]['sku'],
'QTY' => number_format($orderItems[$i]['qty_ordered'],0), // no decimals
'AMT' => number_format($orderItems[$i]['price'],2) // 2 decimal places
'DCNT' => number_format(abs($orderItems[$i]['discount_amount']),2) */
);
}
return $purchasedSkus;
}
/**
* Get the Universal Data (JSON) Object for Commission Junction.
* This object contains the order details passed on to Commission Junction for reporting purposes
* on the Checkout Success / Order Confirmation page.
* Notes:
* - CID, TYPE AND CURRENCY are hard coded
* #param string $orderId
* #return JSON object Universal Data Object for Commission Junction $json_masterTmsUdp
*/
public function getCommissionJunctionUdo($orderId) {
$order = Mage::getModel('sales/order')->loadByIncrementId($orderId);
$udo = array();
$udo['CID'] = 'XXXX';
$udo['TYPE'] = 'XXXX';
$udo['CURRENCY'] = 'USD';
$udo['OID'] = $orderId;
$udo['DISCOUNT'] = number_format(abs($order->discount_amount),2);
$order_coupon_code = $order->coupon_code;
if(!is_null($order_coupon_code) && !empty($order_coupon_code)) {
$udo['COUPON'] = $order_coupon_code;
}
$udo['PRODUCTLIST'] = self::_getOrderProductsList($order);
if(Mage::getModel('core/cookie')->get('aff_commissionjunction') == 'cjafflx') {
$udo['FIRECJ'] = "TRUE";
}
else {
$udo['FIRECJ'] = "FALSE";
}
$masterTmsUdo['CJ'] = $udo;
$json_masterTmsUdo = json_encode($masterTmsUdo);
return $json_masterTmsUdo;
}
}
And I found this site where they explain how to register a helper class
http://codegento.com/2011/02/creating-a-helper-class/
The only thing I dont know its:
Where in the magento structure should I add this php class?
Where is the config.xml I should edit?
User created classes should be placed in this folder:
app/code/community
Another issue, you should use the same naming convention for your class as Magento uses i.e.
MOduleNameSpace_ComissionJunction_Helper_Data
Also the config XML should be placed in your app/code/community/ MOduleNameSpace/ComissionJunction/etc folder

Magento get available attribute set id's and names from external script

I have tried all sorts of things and I'm not getting anywhere. Please would someone show me how to get the name and id of all available product attribute sets? One will be 'Default'...
I'm building a custom quoting system and need to pull in the attribute sets so that users can select that first then load up the products that are assigned to that set.
Many thanks for your help.
You can load the attribute sets with:
$attributeSetCollection = Mage::getResourceModel('eav/entity_attribute_set_collection') ->load();
Iterate:
foreach ($attributeSetCollection as $id=>$attributeSet) {
$entityTypeId = $attributeSet->getEntityTypeId();
$name = $attributeSet->getAttributeSetName();
Mage::log("ATTRIBUTE SET :".$name." - ".$id);
}
You can then load your collection by attribute set.
So As you are trying to get the attributeSets which are showing in manage attribute set section of admin you can follow the below coding:
<?php
require_once('app/Mage.php');
umask(0);
Mage::app();//->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$entityType = Mage::getModel('catalog/product')->getResource()->getTypeId();
$collection = Mage::getResourceModel('eav/entity_attribute_set_collection')->setEntityTypeFilter($entityType);
$allSet = array();
foreach($collection as $coll){
$attributeSet['name'] = $coll->getAttributeSetName();
$attributeSet['id'] = $coll->getAttributeSetId();
$allSet[] = $attributeSet;
}
echo "<pre>";
print_r($allSet);
echo "</pre>";
?>
Click here! For more reference.
If you want to get an Attribute set selector in your Magento Admin System > Configuration this class will be useful:
class CompanyName_ModuleName_Model_System_Config_Source_Catalog_Product_Attributeset
{
protected $_options = array();
public function toOptionArray()
{
if (!count($this->_options)) {
$entityTypeId = Mage::getResourceModel('catalog/product')->getTypeId();
$attributeSetCollection = Mage::getResourceModel('eav/entity_attribute_set_collection')
->setEntityTypeFilter($entityTypeId);
foreach ($attributeSetCollection as $_attributeSet) {
$this->_options[] = array(
'value' => $_attributeSet->getId(),
'label' => $_attributeSet->getAttributeSetName()
);
}
}
return $this->_options;
}
}
These attribute sets are limited by catalog_product entity type.
Indeed you will need the field in your system.xml like this:
<select_attribute_set translate="label">
<label>Default Attribute Set for new importing products</label>
<frontend_type>select</frontend_type>
<source_model>companyname_modulename/system_config_source_catalog_product_attributeset</source_model>
<sort_order>30</sort_order>
<show_in_default>1</show_in_default>
</select_attribute_set>

Magento: Adding simple products from a bundle to separate lines in the cart

My client is requesting that each simple product within a bundled product they are selling (Clothing Top and Bottom) be added as a separate line item in the cart whenever a user adds it. Can anyone direct me in how to accomplish this? I am fairly good with MVC and the Zend Framework, but I need a bit of help finding the exact files that control adding bundled products to the cart, or an alternate method for getting these items added separately. Please assume that the only possible product type for this clothing is the Bundled product type.
You will need an observer:
<checkout_cart_product_add_after>
<observers>
<reporting>
<type>singleton</type>
<class>Yourcompany_yourmodelname_Model_Observer</class>
<method>onCartProductAdd</method>
</reporting>
</observers>
</checkout_cart_product_add_after>
Then do the observer:
class ourcompany_yourmodelname_Model_Observer extends Mage_Core_Model_Abstract
{
/**
* Binds to the checkout_cart_product_add_after Event and passes control to the helper function to process the quote
*
* #param Varien_Event_Observer $observer
* #return void
*/
public function onCartProductAdd($observer){
$product = $observer->getProduct();
$isProductBundle = ($product->getTypeId() == 'bundle');
$items_to_add = array();
$oTypeInstance = $oProduct->getTypeInstance(true);
$aSelections = $oTypeInstance->getSelectionsCollection($aOptionIds, $product );
$aOptions = $oTypeInstance->getOptionsByIds($aOptionIds, $product);
$bundleOptions = $aOptions->appendSelections($aSelections, true);
foreach ($bundleOptions as $bundleOption) {
if ($bundleOption->getSelections()) {
$bundleSelections = $bundleOption->getSelections();
foreach ($bundleSelections as $bundleSelection) {
$items_to_add[] = $bundleSelection.getID();
}
}
}
insertExtractedProducts($items_to_add);
}
/**
* Add extracted products into quote
*
* #param array $items_to_add
*/
public function insertExtractedProducts($items_to_add){
/**#var $cart Mage_Checkout_Model_Cart**/
$cart = Mage::helper('checkout/cart')->getCart();
$ids_to_add = array();
foreach($items_to_add as $item_to_be_added){
$ids_to_add[] = $item_to_be_added->getProductId();
}
$cart->addProductsByIDs($ids_to_add);
$cart->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
}
}
Just a simple sample, but it might help.
Bundled products can be complicated to understand, when working with it via code:
Here is a sample image:
Each Bundled product, have one to many options, which in the end will be links to products to be added to the bundle in the Shopping Cart.
Each Option consists of one to many Selections, which will be the linked products that will end up in the Shopping cart, under this bundled product. One Selection, can typically be set as the default, and will already be selected on the product page. More information can be found at this link on how to create and configure bundled products, because in this document, we will only discuss the programming side of it.
The bundled product’s display page, will look like this:
It could look like this in the shopping cart, once you clicked on “Add to Cart”:
Bundle Sample
Sample Shampoo
1 x Moisturiser-125ml $29.95
Default Conditioner
1 x Moisturiser-60g $99.95
When interrogating this product through code, you load it like any normal product:
$oProduct->load($vProductId);
Once it is loaded, you need to get a product type instance, so that you can load the options for this product type.
$oTypeInstance = $oProduct->getTypeInstance(true);
Now we can get the list of option ID’s for this product in this manner:
$oTypeInstance = $oProduct->getTypeInstance(true);
To interrogate the Selections, we will add the list of options to a collection, then get the Options collection, as well as their respective Selections:
$aSelections = $oTypeInstance->getSelectionsCollection($aOptionIds, $oProduct );
$aOptions = $oTypeInstance->getOptionsByIds($aOptionIds, $oProduct);
$bundleOptions = $aOptions->appendSelections($aSelections, true);
Now we have a Collection of Options, and each Option will have a collection of Selections. We can now loop through the options, and look at their Selctions.
foreach ($bundleOptions as $bundleOption) {
if ($bundleOption->getSelections()) {
$bundleSelections = $bundleOption->getSelections();
foreach ($bundleSelections as $bundleSelection) {
// get some data here
$vName = $bundleOption->getTitle();
}
}
}
To get a list of the Required Selection Products for the Bundled product, you can use the following code:
$requiredChildren = $this->getChildrenIds($product->getId(),$required=true);
You can then loop through the array of ID’s and load the products by their ID’s to get more information regarding those products.
Bundled products in the shopping cart
In order to loop through the selected options of a Bundled product in the shopping card, you can use something like this:
/**
* #var Mage_Bundle_Model_Product_Type
*/
$typeInstance = $this->getProduct()->getTypeInstance(true);
// get bundle options
$optionsQuoteItemOption = $this->getItem()->getOptionByCode('bundle_option_ids');
$bundleOptionsIds = unserialize($optionsQuoteItemOption->getValue());
if ($bundleOptionsIds) {
/**
* #var Mage_Bundle_Model_Mysql4_Option_Collection
*/
$optionsCollection = $typeInstance->getOptionsByIds($bundleOptionsIds, $this->getProduct());
// get and add bundle selections collection
$selectionsQuoteItemOption = $this->getItem()->getOptionByCode('bundle_selection_ids');
$selectionsCollection = $typeInstance->getSelectionsByIds(
unserialize($selectionsQuoteItemOption->getValue()),
$this->getProduct()
);
$bundleOptions = $optionsCollection->appendSelections($selectionsCollection, true);
foreach ($bundleOptions as $bundleOption) {
if ($bundleOption->getSelections()) {
$label = $bundleOption->getTitle()
$bundleSelections = $bundleOption->getSelections();
foreach ($bundleSelections as $bundleSelection) {
$sName = $bundleSelection->getName();
}
// some more code here to do stuff
}
}
}
This code gets the Options from the Quote Item Bundled Product, and then gets the Options for that product in a collection, and then finds the “Selected” Option Selection.
hth,
Shaun
Here's how you can do this in Magento 2.3 via an "around" plugin (interceptor) for the Magento\Checkout\Model\Cart->addProduct() method.
The addProduct() method is called when the customer adds a product to the cart. By adding code to this method via a plugin, you can alter the way the bundle product is added to the cart.
Define the plugin in Vendor/Module/etc/frontend/di.xml:
<?xml version="1.0"?>
<!--
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="\Magento\Checkout\Model\Cart">
<plugin name="add-bundle-products-separate" type="Vendor\Module\Plugin\Checkout\Model\CartPlugin" sortOrder="1"/>
</type>
</config>
This is what tells Magento a plugin exists for this particular method.
Reference:
https://devdocs.magento.com/guides/v2.3/extension-dev-guide/plugins.html
Create the plugin's class.
In Vendor/Module/Plugin/Checkout/Model/CartPlugin.php:
<?php
namespace Vendor\Module\Plugin\Checkout\Model;
use \Magento\Catalog\Model\Product;
use \Magento\Framework\DataObject;
use \Magento\Checkout\Model\Cart;
/**
* Class CartPlugin
*
* #package Ppwd\CrossSell\Plugin\Checkout\Model
*
*/
class CartPlugin {
/**
* #param Cart $subject
* #param \Closure $proceed
* #param Product $productInfo
* #param DataObject|int|array $requestInfo
* #return Cart $subject
* #SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
public function aroundAddProduct(
$subject,
$proceed,
$productInfo,
$requestInfo = null
) {
// Detect if we are adding a bundle product to cart
if (!is_numeric($productInfo) && $productInfo->getTypeId() == 'bundle') {
$buyRequest = new DataObject($requestInfo);
// List of products selected as part of the bundle
$cartCandidates = $productInfo->getTypeInstance()->prepareForCartAdvanced($buyRequest, $productInfo);
$productIds = [];
// Add each item in bundle as if it were separately added to cart
/** #var Product $cartCandidate */
foreach ($cartCandidates as $cartCandidate) {
if ($cartCandidate->getTypeId() != 'bundle') {
for ($i = 0; $i < $cartCandidate->getCartQty(); $i++) {
$productIds[] = $cartCandidate->getId();
}
}
}
$subject->addProductsByIds($productIds);
return $subject;
}
// Return original result from addProduct() as if plugin didn't exist
$result = $proceed($productInfo, $requestInfo);
return $result;
}
}
When done, if you add the bundle to the cart the line items will appear separately instead of grouped together like a bundle product normally is.
I did this to solve the customer request to add bundle content as separate items in the cart. Just replace
$cart->addProduct($product, $params)
with
if ($product->getTypeId() == 'bundle') {
$request = new Varien_Object($params);
$cartCandidates = $product->getTypeInstance(true)->prepareForCartAdvanced($request, $product, Mage_Catalog_Model_Product_Type_Abstract::PROCESS_MODE_FULL);
$idstoadd = array();
foreach ($cartCandidates as $cartCandidate) {
if ($cartCandidate->getTypeId() == 'simple') {
for ($i = 0; $i < $cartCandidate->getCartQty(); $i++) {
$idstoadd[] = $cartCandidate->getId();
}
}
}
$cart->addProductsByIds($idstoadd);
} else {
$cart->addProduct($product, $params);
}
in the file cartController.

Categories