4

I have a script that create new configurable product, but I get an error when I try to save the super attribute price configuration, here's my code:

function createConf(){
//other code before...

$configProduct = Mage::getModel('catalog/product');
//Load the 3 simple products already created
$idIT = 5;
$idEU = 6;
$idRW = 7;
$_productSIT = Mage::getModel('catalog/product')->load($idIT);
$_productSEU = Mage::getModel('catalog/product')->load($idEU);
$_productSRW = Mage::getModel('catalog/product')->load($idRW);
$configProduct
    ->setWebsiteIds(1)
    ->setAttributeSetId(4)
    ->setTypeId('configurable')
    ->setCreatedAt(strtotime('now'))
    ->setSku($skuNew)//I have defined this variable before and it's value it's taken from an external database
    ->setStatus(1)
    ->setTaxClassId(4)
    ->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH)
    ->setPrice($_productSIT->getPrice())
    ->setDescription('descr')
    ->setShortDescription('short descr')
    ->setStockData(array(
            'use_config_manage_stock' => 0,
            'manage_stock' => 1,
            'is_in_stock' => 1,
        )
    );

 // [...] after that I set all the other attributes like name and so on...

$listinoId = Mage::getResourceModel('eav/entity_attribute')
    ->getIdByCode('catalog_product', 'listino');

$configProduct->getTypeInstance()->setUsedProductAttributeIds(array($listinoId));
$configurableAttributesData = $configProduct->getTypeInstance()->getConfigurableAttributesAsArray();
$configProduct->setCanSaveConfigurableAttributes(true);
$configProduct->setConfigurableAttributesData($configurableAttributesData);

$configurableProductsData = array();
$configurableProductsData[$idIT] = array(
    '0' => array(
        'label' => $_productSIT->getAttributeText('listino'),
        'attribute_id' => $listinoId,
        'value_index' => $_productSIT->getListino(),
        'is_percent' => '0',
        'pricing_value' => '0'
    )
);
$configurableProductsData[$idEU] = array(
    '0' => array(
        'label' => $_productSEU->getAttributeText('listino'),
        'attribute_id' => $listinoId,
        'value_index' => $_productSEU->getListino(),
        'pricing_value' => '0'
    )
);
$configurableProductsData[$idRW] = array(
    '0' => array(
        'label' => $_productSRW->getAttributeText('listino'),
        'attribute_id' => $listinoId,
        'value_index' => $_productSRW->getListino(),
        'pricing_value' => '0'
    )
);

$configProduct->setConfigurableProductsData($configurableProductsData);
$configProduct->setConfigurableAttributesData($configurableAttributesData);
$configProduct->save();

//Now I call the function to update the super attribute price
insertPriceConf($configProduct->getId(), $_productSRW->getPrice(), $_productSIT->getPrice(), $_productSEU->getPrice());}

 function insertPriceConf($id, $prezzoRW, $prezzoBase, $prezzoEU){
 $product = Mage::getSingleton("catalog/Product")->load($id);
$associatedProducts = $product->getTypeInstance()->getConfigurableAttributesAsArray(($product));

foreach ($associatedProducts as $attributeData) {
    $idAt = isset($attributeData['id']) ? $attributeData['id'] : null;
    $size = sizeof($attributeData['values']);
    for ($j = 0; $j < $size; $j++) {
        if ($attributeData['values'][$j]['label'] == 'IT') {
            $attributeData['values'][$j]['pricing_value'] = '0';
        }
        if ($attributeData['values'][$j]['label'] == 'RW') {
            $attributeData['values'][$j]['pricing_value'] = $prezzoRW;
        }
        if ($attributeData['values'][$j]['label'] == 'EU') {
            $attributeData['values'][$j]['pricing_value'] = $prezzoEU;
        }

        try {
            Mage::getModel('catalog/product_type_configurable_attribute')
                ->setData($attributeData)
                ->setId($idAt)
                ->setStoreId(1)
                ->setProductId($product->getId())
                ->save();

        } catch (Exception $e) {
            var_dump($e->getMessage());
        }
    }
}
}

My problem is that I use these function in a loop because I need to insert new products taken from an external database, when I run the code the first configurable product is created correctly, with the super attribute price and so on, but from the second one to the last, the product is created, and there are also the associated simple product but I cannot set the price of the super attribute, this is the error given:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '4606-176' for key 'UNQ_CATALOG_PRODUCT_SUPER_ATTRIBUTE_PRODUCT_ID_ATTRIBUTE_ID', query was: UPDATE `catalog_product_super_attribute` SET `product_id` = ?, `attribute_id` = ?, `position` = ? WHERE (product_super_attribute_id='758')

Please help me. I tried everything found on the internet but nothing works

0

The error message states that a row with the given product_id and attribute_id combination already exists (there is a UNIQUE index over these columns).

I see that you use $product = Mage::getSingleton("catalog/Product")->load($id); - not sure if this is the only cause of your problem but it's definitely related.

Never use the product model as a singleton. This way you reuse the same object in each iteration of the loop and it contains cached information which is not reset on load().

Solution: Replace getSingleton() with getModel()

  • reusing the getModel() can bring performance improvements. Requires calling the reset() method before doing another load. – halk Jan 19 '16 at 12:26
  • The performance improvement is negligible in comparision to the possible bugs you introduce because things are reused that you don't want to be reused. – Fabian Schmengler Jan 19 '16 at 12:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.