0

Fatal error: Uncaught PDOException: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`m1937`.`catalog_product_entity`, CONSTRAINT `FK_CAT_PRD_ENTT_ATTR_SET_ID_EAV_ATTR_SET_ATTR_SET_ID` FOREIGN KEY (`attribute_set_id`) REFERENCES `eav_attribute_set` (`attribute_set_id`) ON DELE)

1
  • 1
    Please add the code you used to perform the task. Dec 4, 2017 at 12:54

2 Answers 2

1

First create simple product and than we can assign it to configurable product.

Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$simpleProduct = Mage::getModel('catalog/product');
try {
$simpleProduct
//    ->setStoreId(1) //you can set data in store scope
    ->setWebsiteIds(array(1)) //website ID the product is assigned to, as an array
    ->setAttributeSetId(20) //ID of a attribute set named 'default'
    ->setTypeId('simple') //product type
    ->setCreatedAt(strtotime('now')) //product creation time
//    ->setUpdatedAt(strtotime('now')) //product update time
    ->setSku('simple99y') //SKU
    ->setName('test simple product99') //product name
    ->setWeight(4.0000)
    ->setStatus(1) //product status (1 - enabled, 2 - disabled)
    ->setTaxClassId(4) //tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)
    ->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH) //catalog and search visibility
    ->setManufacturer(28) //manufacturer id
    ->setColor(24)
    ->setNewsFromDate('06/26/2014') //product set as new from
    ->setNewsToDate('06/30/2014') //product set as new to
    ->setCountryOfManufacture('AF') //country of manufacture (2-letter country code)
    ->setPrice(11.22) //price in form 11.22
    ->setCost(22.33) //price in form 11.22
    ->setSpecialPrice(00.44) //special price in form 11.22
    ->setSpecialFromDate('06/1/2014') //special price from (MM-DD-YYYY)
    ->setSpecialToDate('06/30/2014') //special price to (MM-DD-YYYY)
    ->setMsrpEnabled(1) //enable MAP
    ->setMsrpDisplayActualPriceType(1) //display actual price (1 - on gesture, 2 - in cart, 3 - before order confirmation, 4 - use config)
    ->setMsrp(99.99) //Manufacturer's Suggested Retail Price
    ->setMetaTitle('test meta title 2')
    ->setMetaKeyword('test meta keyword 2')
    ->setMetaDescription('test meta description 2')
    ->setDescription('This is a long description')
    ->setShortDescription('This is a short description')
    ->setMediaGallery(array('images' => array(), 'values' => array())) //media gallery initialization
    ->setStockData(array(
            'use_config_manage_stock' => 0, //'Use config settings' checkbox
            'manage_stock' => 1, //manage stock
            'min_sale_qty' => 1, //Minimum Qty Allowed in Shopping Cart
            'max_sale_qty' => 2, //Maximum Qty Allowed in Shopping Cart
            'is_in_stock' => 1, //Stock Availability
            'qty' => 999 //qty
        )
    )
    ->setCategoryIds(array(3, 10)); //assign product to categories
    $simpleProduct->save();
} catch (Exception $e) {
    Mage::log($e->getMessage());
    echo $e->getMessage();
}

What we need to do now is create a configurable product and assign this simple product to it.

$configProduct = Mage::getModel('catalog/product');,
try {
$configProduct
//    ->setStoreId(1) //you can set data in store scope
        ->setWebsiteIds(array(1)) //website ID the product is assigned to, as an array
        ->setAttributeSetId(20) //ID of a attribute set named 'default'
        ->setTypeId('configurable') //product type
        ->setCreatedAt(strtotime('now')) //product creation time
//    ->setUpdatedAt(strtotime('now')) //product update time
        ->setSku('configurable96') //SKU
        ->setName('test config product96') //product name
        ->setWeight(4.0000)
        ->setStatus(1) //product status (1 - enabled, 2 - disabled)
        ->setTaxClassId(4) //tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)
        ->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH) //catalog and search visibility
        ->setManufacturer(28) //manufacturer id
        ->setNewsFromDate('06/26/2014') //product set as new from
        ->setNewsToDate('06/30/2014') //product set as new to
        ->setCountryOfManufacture('AF') //country of manufacture (2-letter country code)
        ->setPrice(11.22) //price in form 11.22
        ->setCost(22.33) //price in form 11.22
        ->setSpecialPrice(00.44) //special price in form 11.22
        ->setSpecialFromDate('06/1/2014') //special price from (MM-DD-YYYY)
        ->setSpecialToDate('06/30/2014') //special price to (MM-DD-YYYY)
        ->setMsrpEnabled(1) //enable MAP
        ->setMsrpDisplayActualPriceType(1) //display actual price (1 - on gesture, 2 - in cart, 3 - before order confirmation, 4 - use config)
        ->setMsrp(99.99) //Manufacturer's Suggested Retail Price
        ->setMetaTitle('test meta title 2')
        ->setMetaKeyword('test meta keyword 2')
        ->setMetaDescription('test meta description 2')
        ->setDescription('This is a long description')
        ->setShortDescription('This is a short description')
        ->setMediaGallery(array('images' => array(), 'values' => array())) //media gallery initialization
        ->setStockData(array(
                'use_config_manage_stock' => 0, //'Use config settings' checkbox
                'manage_stock' => 1, //manage stock
                'is_in_stock' => 1, //Stock Availability
            )
        )
        ->setCategoryIds(array(3, 10)) //assign product to categories
    ;
    /**/
    /** assigning associated product to configurable */
    /**/
    $configProduct->getTypeInstance()->setUsedProductAttributeIds(array(92)); //attribute ID of attribute 'color' in my store
    $configurableAttributesData = $configProduct->getTypeInstance()->getConfigurableAttributesAsArray();

    $configProduct->setCanSaveConfigurableAttributes(true);
    $configProduct->setConfigurableAttributesData($configurableAttributesData);

    $configurableProductsData = array();
    $configurableProductsData['920'] = array( //['920'] = id of a simple product associated with this configurable
        '0' => array(
            'label' => 'Green', //attribute label
            'attribute_id' => '92', //attribute ID of attribute 'color' in my store
            'value_index' => '24', //value of 'Green' index of the attribute 'color'
            'is_percent' => '0', //fixed/percent price for this option
            'pricing_value' => '21' //value for the pricing
        )
    );
    $configProduct->setConfigurableProductsData($configurableProductsData);
    $configProduct->save();

    echo 'success';
} catch (Exception $e) {
    Mage::log($e->getMessage());
    echo $e->getMessage();
}

And that’s it! Your configurable product should be properly set up and visible on the frontend!

0

this is my code , but it's create duplicate configurable product

$collection = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect(array('name'))->load();
$productName = array();

foreach($collection as $collection1) {
    $productName[] = $collection1->getName();
}

$getData = array_unique($productName);

$productCollection = Mage::getModel('catalog/product')->getCollection()
        ->addFieldToFilter('name', array('in'=> $getData));
$productCollection->load();

$newArr = array();
foreach ($productCollection->getData() as $val) {
    $newArr[$val[name]] = $val;    
}
$productUniqeArray = array_values($newArr);

foreach ($productUniqeArray as $productData) {

    /* define attribute code */
    $attributeColorCode = 'color';
    $attributeSizeCode = 'size';


    /* return function to getting the attribute color id */
    $attribute_details = Mage::getSingleton("eav/config")->getAttribute('catalog_product', $attributeColorCode);
    $attribute = $attribute_details->getData();
    $attribute_colorid = $attribute['attribute_id'];

    /* return function to getting the attribute size id */
    $attribute_details = Mage::getSingleton("eav/config")->getAttribute('catalog_product', $attributeSizeCode);
    $attribute = $attribute_details->getData();
    $attribute_sizeid = $attribute['attribute_id'];

    $_product = Mage::getModel('catalog/product')->load($productData['entity_id']);
    //echo "<pre>";
    //print_r($_product);
    echo $_product->getName(); //product name
    $configProduct = Mage::getModel('catalog/product');

            $configProduct
    //->setStoreId(1) //you can set data in store scope
    ->setWebsiteIds(array(1)) //website ID the product is assigned to, as an array
    ->setAttributeSetId(4) //ID of a attribute set named 'default'
    ->setTypeId('configurable') //product type
    ->setCreatedAt(strtotime('now')) //product creation time
    ->setUpdatedAt(strtotime('now')) //product update time
    ->setSku($_product->getSku()."_config") //SKU
    ->setName($_product->getName()) //product name
    ->setUrlKey($url)->setWeight(1)->setStatus(1) //product status (1 - enabled, 2 - disabled)
    ->setTaxClassId(2) //tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)
    ->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH) //catalog and search visibility
    ->setNewsFromDate('') //product set as new from
    ->setNewsToDate('') //product set as new to
    ->setPrice($_product->getPrice()) //price in form 11.22
    ->setDescription($_product->getDescription())->setShortDescription($_product->getShortDescription())
    ->setStockData(array(
            'use_config_manage_stock' => 0, //'Use config settings' checkbox
            'manage_stock' => 1, //manage stock
            'is_in_stock' => 1, //Stock Availability
        )
    )

    ->setCategoryIds(array(3)); //assign product to categories

    /* get collection of all simple products gonna assing to configurable products ( I have assigned an attribute value to all simple products to group them and get collection ) */
    $simpleProducts = Mage::getResourceModel('catalog/product_collection')
    ->addIdFilter(array(2,3))
    ->addAttributeToSelect('color')
    ->addAttributeToSelect('size')
    ->addAttributeToSelect('price');

    $configProduct->setCanSaveConfigurableAttributes(true);
    $configProduct->setCanSaveCustomOptions(true);

    /* set attributes from which you need to create configurable product */
    $configProduct->getTypeInstance()->setUsedProductAttributeIds(array($attribute_colorid,$attribute_sizeid));

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

    foreach ($simpleProducts as $simple) {
        $productData = array(
        'label' => $simple->getAttributeText('color'),
        'attribute_id' => $attribute_colorid,
        'value_index' => (int) $simple->getColor(),
        'is_percent' => 0,
        'pricing_value' => $simple->getPrice()
        );

        $configurableProductsData[$simple->getId()] = $productData;
        $configurableAttributesData[0]['values'][] = $productData;

        $productData = array(
        'label' => $simple->getAttributeText('size'),
        'attribute_id' => $attribute_sizeid,
        'value_index' => (int) $simple->getSize(),
        'is_percent' => 0,
        'pricing_value' => $simple->getPrice()
        );

        $configurableProductsData[$simple->getId()] = $productData;
        $configurableAttributesData[1]['values'][] = $productData;
    }

    $configProduct->setConfigurableProductsData($configurableProductsData);
    $configProduct->setConfigurableAttributesData($configurableAttributesData);
    $configProduct->setCanSaveConfigurableAttributes(true);

    Mage::log($configurableProductsData, null, 'configurableProductsData.log', true);
    Mage::log($configurableAttributesData, null, 'configurableAttributesData.log', true);

    $configProduct->save();
    $confId = $configProduct->getId();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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