Creating a bundled product with Magento - magento

I've been following along with this example: Magento programmaticaly create bundle Product
and the code is working when I create a new product, however, I can't get it to work when I load a product either bundled or simple. [EDIT] I can load a bundled product that I created programmatically through the code below and add products to the bundle. A bundled product I created through the GUI I cannot add products too.
Any idea how I can load a product up then bundle it with another a product?
Here is my current code:
$items = array();
$items[] = array(
'title' => 'Bundle Option',
'option_id' => '',
'delete' => '',
'type' => 'radio',
'required' => 1,
'position' => 0,
);
$selectionRawData = array();
$selectionRawData[0] = array();
$selectionRawData[0][] = array(
'selection_id' => '',
'option_id' => '',
'product_id' => 3,
'delete' => '',
'selection_price_value' => 0,
'selection_price_type' => 0,
'selection_qty' => 1,
'selection_can_change_qty' => 0,
'position' => 0,
'is_default' => 1,
);
$selections = $selectionRawData;
$websiteIDs = array(1);
$cats = array(4);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
// load product
// NOT WORKING
$product = Mage::getModel('catalog/product');
$product->load(127);
// new product
/******
* THIS WORKS
$p = array(
'sku_type' => 1,
'sku' => '123321',
'name' => "BarProduct",
'description' => 'Foo',
'short_description' => 'Bar',
'type_id' => 'bundle',
'attribute_set_id' => 4,
'weight_type' => 0,
'visibility' => 4,
'price_type' => 1,
'price_view' => 0,
'price' => 1.99,
'has_options' => 1,
'required_options' => 1,
'status' => 1,
'created_at' => strtotime('now'),
'category_ids' => $cats,
'store_id' => 0,
'website_ids' => $websiteIDs,
'weight' => 0,
'weight_type' => 1,
'delivery_time' => '',
'generate_meta' => 1,
'tax_class_id' => 1, //19%
);
$product->setData($p);
*****/
Mage::register('product', $product);
Mage::register('current_product', $product);
$product->setCanSaveConfigurableAttributes(false);
$product->setCanSaveCustomOptions(true);
$product->setBundleOptionsData($items);
$product->setBundleSelectionsData($selections);
$product->setCanSaveCustomOptions(true);
$product->setCanSaveBundleSelections(true);
$product->setAffectBundleProductSelections(true);
$product->save();
$result['product_name'] = $product->getId();
return $result;

This is important for bundled products:
$product->setData("price_type", 0);
You must set this attribute to 0 (Dynamic price) before saving.
Reindexing is then necessary of course.

I had some funky stuff going on with my product index. I deleted all my products and fixed my index and this now works, albeit not well.
So here is what I gleaned from the process:
If you want to take two simple products and bundle them, you'll need to create a new bundled bundled product via the $p = array code above, then add both simple products.
Otherwise, you'll need a bundled product that is premade via the magento gui. then you'll have bring up that product using the $product->load(product_id) command, then add your simple products to that.

Just delete all unneeded options like this:
$optionsselectionsmap = array();
$options = Mage::getModel("bundle/option")->getCollection()->setProductIdFilter($product->getId());
foreach($options as $option){
$selection = Mage::getModel("bundle/selection")->getCollection()->setOptionIdsFilter($option->getId())->getFirstItem();
$tmp = array();
$tmp['option_id'] = $option->getId();
$tmp['selection_id'] = $selection->getData('selection_id');
$optionsselectionsmap[$selection->getData('sku')] = $tmp;
}
$deleteoptionids = array();
foreach($optionsselectionsmap as $k=>$v) $deleteoptionids[] = $v['option_id'];
foreach($product->getTypeInstance(true)->getOptionsCollection($product) as $deleteitem){
$deleteitem = $deleteitem->getData();
$deleteitem['delete'] = 1;
$bundleOptions[] = $deleteitem;
}

Related

I want to add price breakup of total amount of a product and configure the product in Magento

I want to add price breakup of total amount of a product and configure the product in Magento.
Click here to see image reference
Anyone here who can provide me solution for the same?
For example, we have pen option and Madison LX2200 and Madison RX3400 as it’s values. Each one of those pens is a simple product (called ‘selection‘ in admin).
Now that we have gone through the basics, we’ll create the code necessary to create a bundle product with two options – each one containing two values to represent simple products.
$bundleSelections = array();
$bundleSelections = array(
'0' => array( //option ID
'0' => array( //selection ID of the option (first product under this option (option ID) would have ID of 0, second an ID of 1, etc)
'product_id' => '554', //if of a product in selection
'delete' => '',
'selection_price_value' => '10',
'selection_price_type' => 0,
'selection_qty' => 1,
'selection_can_change_qty' => 0,
'position' => 0,
'is_default' => 1
),
'1' => array(
'product_id' => '553',
'delete' => '',
'selection_price_value' => '10',
'selection_price_type' => 0,
'selection_qty' => 1,
'selection_can_change_qty' => 0,
'position' => 0,
'is_default' => 1
)
),

Distinguish between magento product attributes and custom created product attribute

I have my custom product attributes in magento.i want to set the product description dynamically.is their any way in magento so that we can find the attribute is custom created by us not by default magento.
i had searched.but not got any success.
Please Help.
Thanks in Advance.
Let's say you have an attribute with code some_code.
Here is how you can check if it's a system attribute or if it's a custom one.
$attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', 'some_code');
if ($attribute->getIsUserDefined()) {
//then you created the attribute
}
else {
//then it's a system attribute
}
Use the magento soap/rest api for creating a custom attribute for Product and update with values as well,
$proxy = new SoapClient('http://magentohost/api/soap/?wsdl');
$sessionId = $proxy->login('apiUser', 'apiKey');
echo "<pre>";
// Create new attribute
$attributeToCreate = array(
"attribute_code" => "new_attribute",
"scope" => "store",
"frontend_input" => "select",
"is_unique" => 0,
"is_required" => 0,
"is_configurable" => 0,
"is_searchable" => 0,
"is_visible_in_advanced_search" => 0,
"used_in_product_listing" => 0,
"additional_fields" => array(
"is_filterable" => 1,
"is_filterable_in_search" => 1,
"position" => 1,
"used_for_sort_by" => 1
),
"frontend_label" => array(
array( "store_id" => 0,"label" => "A new attribute" )
)
);
$attributeId = $proxy->call($sessionId,"product_attribute.create",
array(
$attributeToCreate
)
);
// Update attribute
$attributeToUpdate = array(
"scope" => "global",
"is_unique" => 1,
"is_required" => 1,
"is_configurable" => 1,
"is_searchable" => 1,
"is_visible_in_advanced_search" => 0,
"used_in_product_listing" => 0,
"additional_fields" => array(
"is_filterable" => 01,
"is_filterable_in_search" => 0,
"position" => 2,
"used_for_sort_by" => 0
),
"frontend_label" => array(
array(
"store_id" => 0,
"label" => "A Test Attribute"
)
)
);
$proxy->call(
$sessionId,
"product_attribute.update",
array(
"new_attribute",
$attributeToUpdate
)
);
I hope this will solve your problem..
You can use Magento default API to get default product list
For more details you can refer to following url:
http://www.magentocommerce.com/api/soap/catalog/catalogProduct/catalog_product.listOfAdditionalAttributes.html
Code used will be:
$proxy = new SoapClient('localhost/api/soap/?wsdl');
$sessionId = $proxy->login('apiUser', 'apiKey');
$listAttributes = $proxy->call($sessionId, 'product.listOfAdditionalAttributes', array( 'simple', 13 ));

How do I create a configurable product with associated products?

The following code does create a configurable product, however, when I open the product in the backend, the following message appears:
Select Configurable Attributes
"Only attributes with scope "Global", input type "Dropdown" and Use To Create Configurable Product "Yes" are available."
A single checkbox is displayed ("Colour Group"), which must be selected before continuing.
When I click "Continue", all of the product data is there as expected EXCEPT for the associated products.
//Mage Product
$mpr = Mage::getModel('catalog/product');
$mpr
->setTypeId(Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE)
->setTaxClassId(5)
->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH)
->setStatus(Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
->setWebsiteIds(array(1))
->setAttributeSetId(4) // You can determine this another way if you need to.
->setSku("C12345")
->setName("C12345")
->setQty(25)
->setShortDescription('short description')
->setDescription('description')
->setPrice(1)
->setStockData(array(
'use_config_manage_stock' => 1,
'is_in_stock' => 1,
'is_salable' => 1,
));
$productData = array(
'7039604' =>
array('0' => array('attribute_id' => '85', 'label' => 'ROYAL','value_index' => '28563', 'is_percent' => 0, 'pricing_value' => '')
,'1' => array('attribute_id' => '192', 'label' => '14', 'value_index' => '28728', 'is_percent' => 0, 'pricing_value' => '')
)
);
$attributeData = array(
'0' => array(
'id' => NULL
,'label' => 'Color'
,'position' => NULL
,'values' => array(
'0' => array('value_index' => 28563, 'label' => 'ROYAL', 'is_percent' => 0, 'pricing_value' => '0', 'attribute_id' => '85')
)
,'attribute_id' => 85
,'attribute_code' => 'color'
,'frontend_label' => 'Color'
,'html_id' => 'config_super_product__attribute_0')
,'1' => array(
'id' => NULL
,'label' => 'Rivers Size'
,'position' => NULL
,'values' => array(
'0' => array('value_index' => 28728, 'label' => '14', 'is_percent' => 0, 'pricing_value' => '0', 'attribute_id' => '192')
)
,'attribute_id' => 192
,'attribute_code' => 'rivers_size'
,'frontend_label' => 'Rivers Size'
,'html_id' => 'config_super_product__attribute_1')
);
$mpr->setConfigurableProductsData($productData);
$mpr->setConfigurableAttributesData($attributeData);
$mpr->setCanSaveConfigurableAttributes(true);
$mpr->save();
Add this code before $mpr->save();
$SKU = "any-simple product sku enter here";
$productid = Mage::getModel('catalog/product')
->getIdBySku(trim($SKU));
$mpr->assignProduct($productid);
And set simple product sku in $SKU variable. and i have check that when i select global variable then after i see associated product in configure product.
Its work fine !!!
If you are getting redirected to select attribute page, this means that attribute data you set in this sample is not saved correctly.
Try viewing catalog_product_super_attribute after script run (new rows should be added).

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.

Add custom options to dropdown via code in Magento

i had to add custom options automatically when a product is added , the code works fine but i need to create a drop down menu with options and i dont know how to add options to the drop down created ,
my code is
public function Add_CustomOptions_Automatically($observer) {
$product = $observer->getEvent()->getProduct();
$save = false; if (!$product->getOptions()) $save = true;
$optionData = array(
'previous_group' => 'text',
'title' => 'Size',
'type' => 'drop_down',
'is_require' => 0,
'sort_order' => 0,
'price' => 0,
'price_type' => 'fixed');
if($save):
$product->setHasOptions(1)->save();
$option = Mage::getModel('catalog/product_option')
->setProductId($product->getId())
->setStoreId($product->getStoreId())
->addData($optionData);
$option->save();
$product->addOption($option);
endif;
}
}
I've created 'type' => 'drop_down' but how can I add options? I have no idea how to add the options, and any help would be very much appreciated.
thanks,
You can supply an array of values to the option array, this will then be added
to the option. as below :-)
$product = Mage::getModel('catalog/product');
$product->load(200); // product id here
$opt = array(
'is_delete' => 0,
'is_require' => false,
'previous_group' => '',
'title' => 'New Example Option',
'type' => 'drop_down',
'price_type' => 'fixed',
'price' => '20.0000',
'sort_order' => 0,
/** array of values for this option **/
'values' => array(
array(
'is_delete' => 0,
'title' => 'Option One Here',
'price_type' => 'fixed',
'price' => 999,
'sku' => 'test-sku-here',
'option_type_id'=> -1,
),
array(
'is_delete' => 0,
'title' => 'Another Option',
'price_type' => 'fixed',
'price' => 999,
'sku' => 'another-sku-here',
'option_type_id'=> -1,
)),
);
$option = Mage::getModel('catalog/product_option')
->setProduct($product)
->addOption($opt)
->saveOptions();
public function Add_CustomOptions_Automatically($observer) {
$product = $observer->getEvent()->getProduct();
$optionData = array(
'previous_group' => 'text',
'title' => 'Size',
'type' => 'drop_down',
'is_require' => 0,
'sort_order' => 0,
'price' => 0,
'price_type' => 'fixed');
if(!(bool)$product->getOptions()):
$product->setHasOptions(true)->save();
$option = Mage::getModel('catalog/product_option')
->setProductId($product->getId())
->setStoreId($product->getStoreId())
->addData($optionData);
// Answer starts here
$value = Mage::getModel('catalog/product_option_value');
$value->setOption($option)
->setTitle('Hello world!');
$option->addValue($value);
// Answer ends here
$option->save();
$product->addOption($option);
endif;
}
As you can see you are adding a Mage_Catalog_Model_Product_Option_Value with a title and associating it with the $option you created. It can also have an SKU, price and sort order. Create as many values as you want in this way.
<!DOCTYPE html PUBLIC "-W3CDTD XHTML 1.0 TransitionalEN" "http:www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http:www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<pre>
<?php
$res = mysql_pconnect('localhost', 'your data base name', 'passward');
mysql_select_db('your database name');
mysql_query("SET NAMES 'utf8';", $res);
mysql_query("SET CHARACTER SET 'utf8';", $res);
$query = 'select entity_id from catalog_product_entity';
$res = mysql_query($query);
$products=array();
while ($ret = mysql_fetch_array($res)) {
$products[]=$ret[0];
$query = "UPDATE catalog_product_entity set has_options=1 where entity_id=$ret[0]";
//echo "$query<br>";
//$res1 = mysql_query($query);
}
echo "Set all products for has_options in catalog_product_entity.<br>";
//$res = mysql_query('DELETE from catalog_product_option');
//$res = mysql_query('DELETE from catalog_product_option_title');
//$res = mysql_query('DELETE from catalog_product_option_type_price');
//$res = mysql_query('DELETE from catalog_product_option_type_title');
//$res = mysql_query('DELETE from catalog_product_option_type_value');
echo "Deleted all rows from catalog_product_option* tables.<br>";
$ress=array();
foreach ($products as $product){
$query = "insert into catalog_product_option (product_id,type,is_require,image_size_x,image_size_y,sort_order) values ($product,'drop_down',0,0,0,0)";
echo "$query<br>";
$res1 = mysql_query($query);
$ress[] = array("option_id" => mysql_insert_id());
}
echo '<pre>';
print_r($ress);
echo "Populated catalog_product_option.<br>";
$option_titles=array('en_US'=> 'Warrenty' );// here change title of option titles #Optional Coating
$res = mysql_query('SELECT * FROM `core_config_data` WHERE path="general/locale/code"');
while ($ret = mysql_fetch_array($res)) {
$stores[$ret['value']][]=$ret['scope_id'];
}
$res = mysql_query('select * from catalog_product_option');// get all product here which agains data inserted
$sort_orders=array(
1,
2,
3,
4);
//while ($ret = mysql_fetch_array($res)) {
foreach ($ress as $key => $ret)
{
//echo '<br>'.$ret[$key]["option_id"];
foreach($stores as $locale=>$scopes){
foreach($scopes as $scope){
$query = "insert into catalog_product_option_title (option_id,store_id,title) values ($ret[option_id],$scope,'$option_titles[$locale]')";
echo "$query<br>";
$res1 = mysql_query($query);
}
}
foreach($sort_orders as $order){
$query = "insert into catalog_product_option_type_value (option_id,sort_order) values ($ret[option_id],$order)";
echo "$query<br>";
$res1 = mysql_query($query);
}
}
echo "Populated catalog_product_option_title.<br>";
echo "Populated catalog_product_option_type_value.<br>";
$prices=array(
0.00,//Standard (12 months)
29.95,//Silver (12 months +loan phone + pic up)
59.95,//Gold(12 months)
89.95//Platinum (24 months +loan phone + pic up)
);
$option_type_titles=array('en_US'=>array(
'Standard (12 months).',
'Silver (12 months +loan phone + pic up).',
'Gold(12 months).',
'Platinum (24 months +loan phone + pic up).'
)
);
$res = mysql_query('select * from catalog_product_option_type_value');
$i = 0;
$j = count($prices)-1;
while ($ret = mysql_fetch_array($res)) {
foreach($stores as $locale=>$scopes){
foreach($scopes as $scope){
$query = "insert into catalog_product_option_type_price (option_type_id,store_id,price,price_type) values ($ret[0],$scope,$prices[$i],'fixed')";
echo "$query<br>";
$res1 = mysql_query($query);
$query = "insert into catalog_product_option_type_title (option_type_id,store_id,title) values ($ret[0],$scope,'{$option_type_titles[$locale][$i]}')";
echo "$query<br>";
$res1 = mysql_query($query);
}
}
($j==$i) ? $i= 0 : $i++ ;
}
echo "<br>Populated catalog_product_option_type_price.<br>";
echo "<br>Populated catalog_product_option_type_title.<br>";
?>
</pre>
</body>
</html>
dear this code is work and i check it . but this code when excute it will add this custom option with all products in your shop. you can change sort ordar and price and option values and also dropdown name . i think its work better.
Try this, its working for me...
$eavSetup->addAttribute(CustomerMetadataInterface::ENTITY_TYPE_CUSTOMER,$attributeCode, [
'type' => 'varchar',
'label' => 'My Code',
'input' => 'select',
'source' => 'Magento\Eav\Model\Entity\Attribute\Source\Table',
'required' => false,
'visible' => true,
'user_defined' => true,
'sort_order' => 101,
'position' => 101,
'system' => 0,
'option' =>
array (
'values' =>
array(
0 => 'January',
1 => 'February',
2 => 'March',
3 => 'April',
4 => 'May',
5 => 'June',
6 => 'July',
7 => 'August',
8 => 'September',
9 => 'October',
10 => 'November',
11 => 'December'
),
),
]);

Resources