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

Problem with saving configurable product programmatically (Magento 1.3.1)
 
kolexndr
Jr. Member
 
Total Posts:  4
Joined:  2008-05-31
 

I’ve wrote script for batch products creation about a year ago. Since version 1.0.19870.1 it worked fine.  In version 1.3.1 it doesn’t.
it seems version 1.3.1 has a lot changes in classes behaviour.
The problem is in save configuable product.
programmatically i’m creating all simple products but then i cannt link them to parent.

$parentProduct   Mage::getModel('catalog/product')->load($productParentId);
...... 
// here is some lines to prepare $data 
...... // $data is simulated associative array identical what we get after decoding Json from save action from admin area
$parentProduct->setConfigurableProductsData($data);
$parentProduct->save();

save() method of product rises with error Invalid argument supplied for foreach() in /home/thegreen/public_html/magento/app/code/core/Mage/Eav/Model/Entity/Abstract.php on line 957
it means $origData is empty after execution this line
$origData = $this->_getOrigObject($newObject)->getOrigData();

i did a lot of data dumps during scripts flow.  It seems everything looks similar to the save action from Admin side.

Could someone advise me how to do correct save call for configurable product in the new version of magento?

thanks

 
Magento Community Magento Community
Magento Community
Magento Community
 
juice1492
Jr. Member
 
Total Posts:  20
Joined:  2009-02-18
 

I’m running 1.3.2.1 and also working on a script to import products.  In testing, I created a new attribute Media Format that can have values of either VHS or DVD.  I then created a new attribute set called Videos that used the new attribute.  I then used the admin interface to create two simple products: a dvd video and a vhs video.  After some tracing thtough the code I came up with this to create a configurable product based on the Videos attribute set with the Media Format as the configurable parameter.

<?php
define
('MAGENTO'realpath('/var/www/magento'));
ini_set('memory_limit''128M');

require_once 
MAGENTO '/app/Mage.php';

Mage::app();

$title 'Test Video';
$description 'Test Video';
$bodyContent='This is a test video';
$itemNum='testVideo2.1';
$price='129.95';
$product Mage::getModel('catalog/product');
$product->setTypeId('configurable');  //
$product->setTaxClassId(0); //none
$product->setWebsiteIds(array(1));  // store id
$product->setAttributeSetId(26); //Videos Attribute Set Id
    /*    Media Format Values
               <option value="6">dvd</option>7
        <option value="5">vhs</option> */
$product->setSku($itemNum);
$product->setName($title);
$product->setDescription($description);
$product->setInDepth($bodyContent);    
$product->setPrice($price);
$product->setShortDescription(ereg_replace("\n","",$description));
$product->setWeight(0);
$product->setStatus(1); //enabled
$product->setVisibilty(4); //catalog and search
$product->setMetaDescription(ereg_replace("\n","",$description));
$product->setMetaTitle($title);
$product->getTypeInstance()->setUsedProductAttributeIds(array(491)); //491 is the attribute id for Media Format
/* configurable product data; 
5791 and 5792 are the product ids of the two simple products that I crated throug the admin interface;
you can change the pricing value if the configured product costs more or less than the parent
*/
$data = array('5791'=>array('0'=>array('attribute_id'=>'491','label'=>'vhs','value_index'=>'5','is_percent'=>0,'pricing_value'=>'')),'5792'=>array('0'=>
            array(
'attribute_id'=>'491','label'=>'dvd','value_index'=>'6','is_percent'=>0,'pricing_value'=>'')));
$product->setConfigurableProductsData($data);
/* configurable attributes */
$data = array('0'=>array('id'=>NULL,'label'=>'Media Format','position'=> NULL,'values'=>array('0'=>array('value_index'=>5,'label'=>'vhs','is_percent'=>0,
            
'pricing_value'=>'0','attribute_id'=>'491'),'1'=>array('value_index'=>6,'label'=>'dvd',
            
'is_percent'=>0,'pricing_value'=>'0','attribute_id'=>'491')
            ),
'attribute_id'=>491,'attribute_code'=>'media_format','frontend_label'=>'Media Format',
            
'html_id'=>'config_super_product__attribute_0'));

        
$product->setConfigurableAttributesData($data);
        
$product->setCanSaveConfigurableAttributes(1);
        
try{
            $product
->save();
            echo 
"$price$itemNum added\n";
        
}
        
catch (Exception $e){         
            
echo "$price$itemNum not added\n";
        echo 
"exception:$e";
        

?>

I’ve harcoded the values for my associated products and attribute data.  You can get attribute data by viewing the source through the admin interface and using Firebug for Firefox.

A more detailed explanation and code can be found on my blog

 
Magento Community Magento Community
Magento Community
Magento Community
 
Shili
Jr. Member
 
Total Posts:  3
Joined:  2009-05-12
 

Hi,

I’m also trying to add programmatically configurable products (what I want to do is add them through api).
Adding, assigning with simple products, setting configurable attributes look just fine, but products are not seen at the frontend. Of course there are no errors, no warnings.
I must log in to Admin Panel, edit each configurable products, make no changes at all and save them to make them show.

I’m pretty sure I must do some mistake, but I can’t see it. I’m working on Magento ver. 1.4.0.0-rc1

The fragment of code I use:

$attributeSets $soap->call($session_id'product_attribute_set.list');
$set current($attributeSets);

$newProductData some simple product data;
$newProductData2 some simple product data;

$newProductData3 = array(
    
'name' => 'name of product',
    
'websites' => 1,
    
'short_description' => 'short description',
    
'description' => 'description',
    
'price' => 12.05
    
'visibility' => 4,  // catalog, search
    
'status' => 1// enabled
    
'category_ids' => array(13),
    
'tax_class_id' => 'None'
);

$data configurable attributes data;

// Create new products
$id $soap->call($session_id'product.create', array('configurable'$set['set_id']'1afafaf'$newProductData3)); 
$soap->call($session_id'product_stock.update', array('1afafaf', array('is_in_stock'=>1'use_config_manage_stock'=>0))); 
$soap->call($session_id'product.create', array('simple'$set['set_id']'1afafaf-1'$newProductData)); 
$soap->call($session_id'product_stock.update', array('1afafaf-1', array('qty'=>1'is_in_stock'=>10'use_config_manage_stock'=>1)));
$soap->call($session_id'product.create', array('simple'$set['set_id']'1afafaf-2'$newProductData2)); 
$soap->call($session_id'product_stock.update', array('1afafaf-2', array('qty'=>1'is_in_stock'=>1'use_config_manage_stock'=>1))); 

echo 
$soap->call($session_id'configurable.addSuperAttributes', array('1afafaf'$data'sku'));
$soap->call($session_id'configurable.assign', array('configurable''1afafaf''1afafaf-1', array('position'=>0), 'sku'));
$soap->call($session_id'configurable.assign', array('configurable''1afafaf''1afafaf-2', array('position'=>1), 'sku'));

And my own Api:

<?php
class Companyname_Modulename_Model_Product_Api extends Mage_Catalog_Model_Product_Link_Api
{
    
    
    
public function addSuperAttributes($productId$data = array(), $identifierType 'sku')
    
{
        
        $product 
$this->_initProduct($productId);
        
        
$res1 $product->setConfigurableAttributesData($data);
        
$res2 $product->setCanSaveConfigurableAttributes(true);
        
$product->setStatus(1);
        
$product->setCreatedAt(strtotime('now'));
        
        try    
{
            $product
->save();
        
}
        
catch (Exception $e){         
            
echo "exception:$e";
        
}
        
        
return($res1 && $res2);
        
    
}
    
    
public function assign($type$productId$linkedProductIds$data = array(), $identifierType null)
    
{
        

        
if(array_key_exists($type,$this->_typeMap))
        
{
            
return parent::assign($type$productId$linkedProductIds$data$identifierType null);
        
}
        
        
if($type=="configurable"{
            
            $product 
$this->_initProduct($productId$identifierType);
            
            if(
$identifierType == 'sku'{
                $linkedProductIds 
$product->getIdBySku($linkedProductIds);
                
$productId $product->getIdBySku($productId);
            
}
            
            $tmpProductIds 
$product->getTypeInstance()->getUsedProductIds();
            
            
$productIds = array();
            
            foreach(
$tmpProductIds as $key => $prodId)
            
{    
                $productIds[$prodId] 
$prodId;
            
}
    
            
if(is_array($linkedProductIds))    {
                
foreach($linkedProductIds as $prodId)
                
{
                    
if(!key_exists($prodId,$productIds)) {$productIds[$prodId] $prodId;}
                }
            } 
elseif(is_numeric($linkedProductIds))    {
                
if(!key_exists($linkedProductIds,$productIds)) {$productIds[$linkedProductIds] $linkedProductIds;}
            } 
else {
                
return false;
            
}
            
            $product
->setConfigurableProductsData($productIds);
            
            try    
{
                $product
->save();
            
}
            
catch (Exception $e){         
                
echo "exception:$e";
            
}
            
            
return true;
        
}
        
        
return false;    
    
}
}
?>

Sorry for my poor English, but I hope you understand what the problem is.
Thanks in advance.

 
Magento Community Magento Community
Magento Community
Magento Community
 
juice1492
Jr. Member
 
Total Posts:  20
Joined:  2009-02-18
 

Try setting the product weight and tax class.  I believe one, if not both is required.

 
Magento Community Magento Community
Magento Community
Magento Community
 
Shili
Jr. Member
 
Total Posts:  3
Joined:  2009-05-12
 

I’ve already tried product weight, and there was no difference. (maybe cause configurable product has no weight at all).
And tax class is set properly in the backend by the last element of array $newProductData3

Setting quantity (qty), or setting ‘use_config_manage_stock’ to 1 also does not work.

 
Magento Community Magento Community
Magento Community
Magento Community
 
juice1492
Jr. Member
 
Total Posts:  20
Joined:  2009-02-18
 

Are you sure tax_class_id is being correctly set?  I don’t know if

‘tax_class_id’ => ‘None’

is the same as

$product->setTaxClassId(0)

I had the same problem while working with php.  If you look in the db (I don’t remember exactly what tables), you can see if the attributes are being set correctly.

 
Magento Community Magento Community
Magento Community
Magento Community
 
Shili
Jr. Member
 
Total Posts:  3
Joined:  2009-05-12
 

@juice1492
I tried setting this as you suggested, but nothing happened.
I think I will look into Magento’s database, maybe i will find the solution.

Thank you very much.

But i still will be very grateful for every hint anyone could provide smile

 
Magento Community Magento Community
Magento Community
Magento Community
 
ddofborg
Jr. Member
 
Total Posts:  4
Joined:  2008-09-12
 

Is is possible to create a configurable product using the SOAP API? Any help is welcome. Thanks.

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

@kolexndr

Try replacing \’Mage::app()\’ with \’Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);\’.

That\’ll sort it out.

 
Magento Community Magento Community
Magento Community
Magento Community
 
dtrain
Jr. Member
 
Total Posts:  8
Joined:  2010-04-30
 
Shili - 03 February 2010 11:34 PM

Hi,

I’m also trying to add programmatically configurable products (what I want to do is add them through api).
Adding, assigning with simple products, setting configurable attributes look just fine, but products are not seen at the frontend. Of course there are no errors, no warnings.
I must log in to Admin Panel, edit each configurable products, make no changes at all and save them to make them show.

I’m pretty sure I must do some mistake, but I can’t see it. I’m working on Magento ver. 1.4.0.0-rc1

.........snip........

And my own Api:

<?php
class Companyname_Modulename_Model_Product_Api extends Mage_Catalog_Model_Product_Link_Api
{
    
    
    
public function addSuperAttributes($productId$data = array(), $identifierType 'sku')
    
{
        
        $product 
$this->_initProduct($productId);
        
        
$res1 $product->setConfigurableAttributesData($data);
        
$res2 $product->setCanSaveConfigurableAttributes(true);
        
$product->setStatus(1);
        
$product->setCreatedAt(strtotime('now'));
        
        try    
{
            $product
->save();
        
}
        
catch (Exception $e){         
            
echo "exception:$e";
        
}
        
        
return($res1 && $res2);
        
    
}
    
    
public function assign($type$productId$linkedProductIds$data = array(), $identifierType null)
    
{
        

        
if(array_key_exists($type,$this->_typeMap))
        
{
            
return parent::assign($type$productId$linkedProductIds$data$identifierType null);
        
}
        
        
if($type=="configurable"{
            
            $product 
$this->_initProduct($productId$identifierType);
            
            if(
$identifierType == 'sku'{
                $linkedProductIds 
$product->getIdBySku($linkedProductIds);
                
$productId $product->getIdBySku($productId);
            
}
            
            $tmpProductIds 
$product->getTypeInstance()->getUsedProductIds();
            
            
$productIds = array();
            
            foreach(
$tmpProductIds as $key => $prodId)
            
{    
                $productIds[$prodId] 
$prodId;
            
}
    
            
if(is_array($linkedProductIds))    {
                
foreach($linkedProductIds as $prodId)
                
{
                    
if(!key_exists($prodId,$productIds)) {$productIds[$prodId] $prodId;}
                }
            } 
elseif(is_numeric($linkedProductIds))    {
                
if(!key_exists($linkedProductIds,$productIds)) {$productIds[$linkedProductIds] $linkedProductIds;}
            } 
else {
                
return false;
            
}
            
            $product
->setConfigurableProductsData($productIds);
            
            try    
{
                $product
->save();
            
}
            
catch (Exception $e){         
                
echo "exception:$e";
            
}
            
            
return true;
        
}
        
        
return false;    
    
}
}
?>

Sorry for my poor English, but I hope you understand what the problem is.
Thanks in advance.

In case anyone else is attempting to create and link configurable products to simple products I thought I’d pass this along. The reason that the newly created configurable product does not appear in the front-end is that the indexes need to be rebuilt. You can either do so programmatically ( see Mage/Adminhtml/controllers/System/CacheController.php) or wait for your indexing cron job to run.

Cheers

 
Magento Community Magento Community
Magento Community
Magento Community
 
jlary
Jr. Member
 
Total Posts:  7
Joined:  2011-03-23
 

@kolexndr

could you please tell me how do you get/construct configurable products ‘data’ programmatically.

$parentProduct->setConfigurableProductsData($data);
?

Once I have created simple products, I want to construct that famous array, but how ?? and which values are required in it ?

Thank you

@juice1492

Any other way than hardcoding ids and values ?

 
Magento Community Magento Community
Magento Community
Magento Community
 
dtrain
Jr. Member
 
Total Posts:  8
Joined:  2010-04-30
 

Take a look at this thread:

http://www.magentocommerce.com/boards/viewthread/46844/#t151510

It should help you along your way.

 
Magento Community Magento Community
Magento Community
Magento Community
 
Hadifarnoud
Sr. Member
 
Total Posts:  210
Joined:  2007-10-07
Guildford, Surrey, UK
 

I remember seeing an extension doing exactly that. and now I can’t find it again.

anyone knows where I can find it?

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