Posting in the Magento forums has been disabled pending the implementation of a new and improved forum solution which should better serve the community.

For new questions please post at magento.stackexchange.com, the community-run support site for the Magento community. We will be providing updates on the new forum solution soon. For questions or concerns please email community@magento.com.

Magento Forum

Auto create grouped products after import (HACK!)
 
oldskool73
Jr. Member
 
Total Posts:  9
Joined:  2008-06-25
 

Hi all,

Just had to import a bunch of products that all came in a number of sizes, and found that Magento doesn’t import groups, or rather it imports all the products but doesn’t attach the related simple products to their parent group product. Rather than fix it all by hand I knocked up the script below.

It searches for grouped type products and finds and attaches any related simple products based on a simple ‘LIKE’ match on the sku, e.g grouped product sku="foo", matches all simple products with sku="foo*" i.e “foobar”, “foo-2” “foo-3” etc will all be added to the group.

It’s pretty simple but it worked for me and saved a lot of boring admin work, can’t wait till this is properly fixed…

public function autoGroupAction() {
        
print "AUTO GROUPING....<br/>";
        
        
$resource Mage::getSingleton('core/resource');
        
$read $resource->getConnection('catalog_read');
        
$productTable $resource->getTableName('catalog/product');
        
$productLinkTable $resource->getTableName('catalog/product_link');
        
$productLinkDecimalTable $resource->getTableName('catalog/product_link_attribute_decimal');
        
$productLinkIntTable $resource->getTableName('catalog/product_link_attribute_int');
        
        
$select_g $read->select()
                           ->
from(array('pt'=>$productTable))
                           ->
where('pt.type_id=?'Mage_Catalog_Model_Product_Type::TYPE_GROUPED);
        
        
$groups $read->fetchAll($select_g);
        print 
"examining ".count($groups)." grouped products...<br/>";
        foreach (
$groups as $group{
            
//find similar skus
            
$sku $group["sku"];
            
$pid $group["entity_id"];
            print 
"::check sku..".$sku."<br/>";
            
$select_p $read->select()
                           ->
from(array('pt'=>$productTable))
                           ->
where('pt.type_id=?'Mage_Catalog_Model_Product_Type::TYPE_SIMPLE)
                           ->
where('pt.sku LIKE ?'$sku."%");
            
$products $read->fetchAll($select_p);
            if (
$products{
                
print "---found ".count($products)." related skus...<br/>";
                foreach (
$products as $product{
                    
//check for existing link
                    
$select_i $read->select()
                               ->
from(array('plt'=>$productLinkTable))
                               ->
where('plt.product_id=?',$pid)
                               ->
where('plt.linked_product_id=?'$product["entity_id"])
                               ->
where('plt.link_type_id'3);
                    
$items $read->fetchAll($select_i);
                    print 
"-----prod=".$product["entity_id"].", sku=".$product["sku"]." -- ";
                    if (!
$items{
                        
print "creating new link...";
                        
$insert $read->insert($productLinkTable,Array("product_id"=>$pid,"linked_product_id"=>$product["entity_id"],"link_type_id"=>3));
                        
$last_id $read->lastInsertId();
                        
$insert $read->insert($productLinkDecimalTable,Array("product_link_attribute_id"=>8,"link_id"=>$last_id));
                        
$insert $read->insert($productLinkIntTable,Array("product_link_attribute_id"=>8,"link_id"=>$last_id));
                        print 
"ok<br/>";                    
                    
else {
                        
print "link already exists...<br/>";
                    
}            
                }
            }            
        }
        
    }

Just add this to the bottom of /app/code/core/Mage/Catalog/controllers/ProductController.php then visit http://yourstore/catalog/product/autoGroup to run it after you have completed your product import.

If someone knows how I could place this at the end the import flow for real so it runs every time (is there a callback or something?) that would be great smile

 
Magento Community Magento Community
Magento Community
Magento Community
 
easyc
Jr. Member
 
Total Posts:  9
Joined:  2008-01-16
 

Hi, this looks like it’s precisely what we need!

I’ve followed your advice to the letter but I just cant seem to get the function to fire… I don’t have server rewrites switched on so I presume the URL http://www.mysite.co.uk/catalogue/product/autogroup shouldn’t work - when I try it I get a “The requested URL /mysite/.co/.uk/catalogue/index.php was not found on this server.”

Without server rewrites on a normal URL for a product on my version of Magento is http://www.mysite.co.uk/catalogue/index.php/category/subcategory/product-name.html

If I try http://www.mysite.co.uk/catalogue/index.php/product/autogroup

This produces a 404 - not found error.

I’ve tried various combos of this - browsing to a category and appending the /product/autogroup to the URL but it doesn’t fire the function

When I modified the CatgegoryController.php file I added your function to the end of the class (right above the closing brace for the class ‘Mage_Catalog_CategoryController’

Do you have any further advice on how to get this working?  We’re about to embark on the manual process of converting 6500 products, so your help would be much appreciated!

Regards
Clive

 
Magento Community Magento Community
Magento Community
Magento Community
 
Discovery
Enthusiast
 
Total Posts:  767
Joined:  2007-12-29
 

Very elegant!

It is interesting how different people tackle the same problem, I had products floating about that were not part of configurables, to add them in I started wth the simples, not the groups. I think that looking at the configurables and then finding the simples is a better way.

My less than elegant code was for one off use and sits as a separate file that just gets called. The pattern matching is for a specific sku pattern, one with lots of underscores in it:

<html>
<
head>
<
title>Add Simple Products to Configurables</title>
</
head>
<
body>
<?php {
// Database connection - hope you remembered your user, pass and db
  
$res mysql_pconnect('localhost''user''pass');
  
mysql_select_db('magento');
// Product selector - here all products of type simple with a selection of underscores in the sku
  
$res mysql_query('select entity_id from catalog_product_entity where type_id = \'simple\' and sku like \'%\_%\_%\'');
// Flag to test code set to 1 to modify db
  
$go_for_it=0;
  
$missing=0;
  
$with_parent=0;
// Go through all the products that match the selection
  
while ($o mysql_fetch_array($res)) {
// Get the product images too - we like to keep it visual
    
$image_o =  mysql_query('select value from catalog_product_entity_media_gallery where entity_id='.$o['entity_id']);
    
$image =  mysql_fetch_array($image_o);
    
$result mysql_query('select sku from catalog_product_entity where entity_id='.$o['entity_id']);
    
$row mysql_fetch_assoc($result);
        
$sku=$row['sku'];
        if (
ereg ("([^_]+)_([^_]+)_([^_]+)_([^_]+)"$sku$master)) {
          $configurable
=$master[1].'_'.$master[2].'_'.$master[3];
          
$configurable_row mysql_query('select * from catalog_product_entity where sku=\''.$configurable.'\'');
          
$configurable_product mysql_fetch_array($configurable_row);
          
$configurable_product_id=$configurable_product['entity_id'];
          
$super_row mysql_query('select product_id, parent_id from catalog_product_super_link where product_id='.$o['entity_id']);
          if(
$super_retrieved mysql_fetch_array($super_row)) {
            
echo $row['sku'].' ('.$o['entity_id'].') is part of configurable product '.$configurable.'('.$super_retrieved['parent_id'].')<br />';
            
$with_parent++;
          
else {
            $missing
++;
            echo 
'<b>'.$row['sku'].' ('.$o['entity_id'].') should be part of configurable product '.$configurable.'('.$configurable_product['entity_id'].')'.$super_retrieved['parent_id'].'</b><br />';
            if (
$go_for_it!=0{
              mysql_query
('insert into catalog_product_super_link (product_id, parent_id) values ('.$o['entity_id'].', '.$configurable_product['entity_id'].')');
            
}
          }
        }
        mysql_free_result
($result);
  
}
  $total_products
=$missing+$with_parent;
  echo 
'<b>Simple products that were not attached to configurables '.$missing.' out of a total of '.$total_products.'</b><br />';
}
?>
</body>
</
html>
 
Magento Community Magento Community
Magento Community
Magento Community
 
Darsh
Member
 
Total Posts:  71
Joined:  2008-06-21
 

Will we be seeing anything like this in the CORE or the new commercial version ?

 
Magento Community Magento Community
Magento Community
Magento Community
 
bolasevich
Sr. Member
 
Avatar
Total Posts:  235
Joined:  2008-03-04
Newington, CT USA
 

my module will handle grouped products

http://www.magentocommerce.com/extension/1894

 
Magento Community Magento Community
Magento Community
Magento Community
 
sritter
Jr. Member
 
Total Posts:  2
Joined:  2009-10-17
 

Hey,
I’used your script a couple of times, worked fine....
Right now i Have following problem… Any ideas?

AUTO GROUPING....
examining 9 grouped products…
::check sku..FO 8221
---found 4 related skus…
-----prod=54217, sku=FO 8221 a—creating new link…

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`koebl/catalog_product_link`, CONSTRAINT `FK_PRODUCT_LINK_TYPE` FOREIGN KEY (`link_type_id`) REFERENCES `catalog_product_link_type` (`link_type_id`) ON DELETE CASCADE ON UPDATE CASCADE)

#0 ../lib/Zend/Db/Statement.php(283): Zend_Db_Statement_Pdo->_execute(Array)
#1 ../lib/Zend/Db/Adapter/Abstract.php(457): Zend_Db_Statement->execute(Array)
#2 ../lib/Zend/Db/Adapter/Pdo/Abstract.php(230): Zend_Db_Adapter_Abstract->query(’INSERT INTO `ca...’, Array)
#3 ../lib/Varien/Db/Adapter/Pdo/Mysql.php(281): Zend_Db_Adapter_Pdo_Abstract->query(’INSERT INTO `ca...’, Array)
#4 ../lib/Zend/Db/Adapter/Abstract.php(535): Varien_Db_Adapter_Pdo_Mysql->query(’INSERT INTO `ca...’, Array)
#5..app/code/core/Mage/Catalog/controllers/ProductController.php(248): Zend_Db_Adapter_Abstract->insert(’catalog_product...’, Array)
#6../app/code/core/Mage/Core/Controller/Varien/Action.php(376): Mage_Catalog_ProductController->autoGroupAction()
#7 ../app/code/core/Mage/Core/Controller/Varien/Router/Standard.php(248): Mage_Core_Controller_Varien_Action->dispatch(’autoGroup’)
#8 ../app/code/core/Mage/Core/Controller/Varien/Front.php(158): Mage_Core_Controller_Varien_Router_Standard->match(Object(Mage_Core_Controller_Request_Http))
#9 ../app/Mage.php(459): Mage_Core_Controller_Varien_Front->dispatch()
#10..index.php(65): Mage::run()
#11 {main}

 
Magento Community Magento Community
Magento Community
Magento Community
 
peterjaap
Jr. Member
 
Avatar
Total Posts:  28
Joined:  2010-03-26
Groningen, The Netherlands
 

Thanks, this worked beautifully smile

@sritter; you’ve probably emptied your product catalog once using the queries mentioned on the Magento wiki. There is (was?) a slight error in those queries, therefore not repopulating some critical tables. Run these queries to (amonst others) repopulate the table ‘catalog_product_link_type’:

insert  into `catalog_product_link_type`(`link_type_id`,`code`) values (1,'relation'),(2,'bundle'),(3,'super'),(4,'up_sell'),(5,'cross_sell');
insert  into `catalog_product_link_attribute`(`product_link_attribute_id`,`link_type_id`,`product_link_attribute_code`,`data_type`) values (1,2,'qty','decimal'),(2,1,'position','int'),(3,4,'position','int'),(4,5,'position','int'),(6,1,'qty','decimal'),(7,3,'position','int'),(8,3,'qty','decimal');
insert  into `cataloginventory_stock`(`stock_id`,`stock_name`) values (1,'Default');

Note: if you have table prefix, add it before ‘catalog’. So, if your prefix is ‘magento_’, your queries will look like this;

insert  into `magento_catalog_product_link_type`(`link_type_id`,`code`) values (1,'relation'),(2,'bundle'),(3,'super'),(4,'up_sell'),(5,'cross_sell');
insert  into `magento_catalog_product_link_attribute`(`product_link_attribute_id`,`link_type_id`,`product_link_attribute_code`,`data_type`) values (1,2,'qty','decimal'),(2,1,'position','int'),(3,4,'position','int'),(4,5,'position','int'),(6,1,'qty','decimal'),(7,3,'position','int'),(8,3,'qty','decimal');
insert  into `magento_cataloginventory_stock`(`stock_id`,`stock_name`) values (1,'Default');

Hope this helps grin

 
Magento Community Magento Community
Magento Community
Magento Community
 
mc2prod
Jr. Member
 
Total Posts:  8
Joined:  2010-02-11
 

This works great. The only problem is in 1.4.1.0 I still need to go into each grouped item and press save for it to activate on the front end. Do you have any suggestions on how to fix this?

 
Magento Community Magento Community
Magento Community
Magento Community
 
mc2prod
Jr. Member
 
Total Posts:  8
Joined:  2010-02-11
 

Sorry, answered my own question. I needed to reindex the catalog under System>Index Management to get the products to update. Thanks so much.

 
Magento Community Magento Community
Magento Community
Magento Community
 
alvarpoon
Jr. Member
 
Total Posts:  2
Joined:  2010-01-04
 

Could the scirpt handle the relation of a bundle product with its related simple product?
Thanks!

 
Magento Community Magento Community
Magento Community
Magento Community
 
ArthurCatigbe
Member
 
Total Posts:  34
Joined:  2009-06-02
 

I’m having the same exact issue where I cannot get the function to work after going to the URL. Any idea’s?

 
Magento Community Magento Community
Magento Community
Magento Community
 
ArthurCatigbe
Member
 
Total Posts:  34
Joined:  2009-06-02
 

Can anyone please help? I really need this.

 
Magento Community Magento Community
Magento Community
Magento Community
 
CreationCoast
Jr. Member
 
Total Posts:  9
Joined:  2009-12-15
 

First post here works perfectly for me here, using Magento 1.5.1. Thanks oldskool73 !

What are you getting when you visit the URL, ArthurCatigbe?

 
Magento Community Magento Community
Magento Community
Magento Community
 
JoeAD
Member
 
Total Posts:  47
Joined:  2008-02-27
 

It’s unbelievable Magento still can’t do this via it’s own import / export

 
Magento Community Magento Community
Magento Community
Magento Community
 
Ranjit Dhami
Jr. Member
 
Total Posts:  1
Joined:  2011-08-22
 

When i try to run the .php code through SSH I get the following error : Class ‘Mage_Core_Controller_Front_Action’ not found in magento ....

Any one know what this means? I am a complete noob at this stuff.

 
Magento Community Magento Community
Magento Community
Magento Community
 
moshsom
Jr. Member
 
Total Posts:  1
Joined:  2011-12-22
 

I so need this to work! I installed this and ran it but the process stops right after checking for skus. I don’t get an error, but nothing happens. Any help would be appreciated! This seems like the only easy way to associate products. Thanks!

AUTO GROUPING....
examining 317 grouped products…
::check sku..testgroup
::check sku..Annularis-Angel-group
::check sku..Bicolor-Angel-group

 
Magento Community Magento Community
Magento Community
Magento Community
Magento Community
Magento Community
Back to top