Sunday 4 November 2012

Import Configurable products with their associated products

There are few steps involved: 

1- Create the attributes that will be configurable by the user.
    or our example, we’ll call it “shoe_size

2- Then go to System->Advanced Profiles and create a new profile.Then copy the below code in "Actions XML" field:-

<action type="dataflow/convert_adapter_io" method="load">
    <var name="type">file</var>
    <var name="path">var/import</var>
    <var name="filename"><![CDATA[Product_Amber.csv]]></var>
    <var name="format"><![CDATA[csv]]></var>
</action>

<action type="dataflow/convert_parser_csv" method="parse">
    <var name="delimiter"><![CDATA[,]]></var>
    <var name="enclose"><![CDATA["]]></var>
    <var name="fieldnames">true</var>
    <var name="store"><![CDATA[0]]></var>
    <var name="number_of_records">1</var>
    <var name="decimal_separator"><![CDATA[.]]></var>
    <var name="adapter">catalog/convert_adapter_productwithlinks</var>
    <var name="method">parse</var>
</action>

Save this profile with any Profile Name.Like "ImportConfigurableProduct"

3- Then go to app/code/core/Mage/Catalog/Model/Convert/Adapter
     Create a new file "Productwithlinks.php " and write the below code in this file:-

<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @category   Mage
 * @package    Mage_Catalog
 * @copyright  Copyright (c) 2008 Irubin Consulting Inc. DBA Varien (http://www.varien.com)
 * @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */


class Mage_Catalog_Model_Convert_Adapter_Productwithlinks
    extends Mage_Catalog_Model_Convert_Adapter_Product
{

    /**
     * Save product (import)
     *
     * @param array $importData
     * @throws Mage_Core_Exception
     * @return bool
     */
    public function saveRow(array $importData)
    {
        $product = $this->getProductModel();
        $product->setData(array());
        if ($stockItem = $product->getStockItem()) {
            $stockItem->setData(array());
        }

        if (empty($importData['store'])) {
            if (!is_null($this->getBatchParams('store'))) {
                $store = $this->getStoreById($this->getBatchParams('store'));
            } else {
                $message = Mage::helper('catalog')->__('Skip import row, required field "%s" not defined', 'store');
                Mage::throwException($message);
            }
        } else {
            $store = $this->getStoreByCode($importData['store']);
        }

        if ($store === false) {
            $message = Mage::helper('catalog')->__('Skip import row, store "%s" field not exists', $importData['store']);
            Mage::throwException($message);
        }
        if (empty($importData['sku'])) {
            $message = Mage::helper('catalog')->__('Skip import row, required field "%s" not defined', 'sku');
            Mage::throwException($message);
        }
        $product->setStoreId($store->getId());
        $productId = $product->getIdBySku($importData['sku']);
$new = true; // fix for duplicating attributes error
        if ($productId) {
            $product->load($productId);
$new = false; // fix for duplicating attributes error
        }
        $productTypes = $this->getProductTypes();
        $productAttributeSets = $this->getProductAttributeSets();

        /**
        * Check product define type
        */
        if (empty($importData['type']) || !isset($productTypes[strtolower($importData['type'])])) {
            $value = isset($importData['type']) ? $importData['type'] : '';
            $message = Mage::helper('catalog')->__('Skip import row, is not valid value "%s" for field "%s"', $value, 'type');
            Mage::throwException($message);
        }
        $product->setTypeId($productTypes[strtolower($importData['type'])]);
        /**
        * Check product define attribute set
        */
        if (empty($importData['attribute_set']) || !isset($productAttributeSets[$importData['attribute_set']])) {
            $value = isset($importData['attribute_set']) ? $importData['attribute_set'] : '';
            $message = Mage::helper('catalog')->__('Skip import row, is not valid value "%s" for field "%s"', $value, 'attribute_set');
            Mage::throwException($message);
        }
        $product->setAttributeSetId($productAttributeSets[$importData['attribute_set']]);

        foreach ($this->_requiredFields as $field) {
            $attribute = $this->getAttribute($field);
            if (!isset($importData[$field]) && $attribute && $attribute->getIsRequired()) {
                $message = Mage::helper('catalog')->__('Skip import row, required field "%s" for new products not defined', $field);
                Mage::throwException($message);
            }
        }

//================================================
// this part handles configurable products and links 
//================================================
if ($importData['type'] == 'configurable') {
$product->setCanSaveConfigurableAttributes(true);
$configAttributeCodes = $this->userCSVDataAsArray($importData['config_attributes']);
$usingAttributeIds = array();
foreach($configAttributeCodes as $attributeCode) {
$attribute = $product->getResource()->getAttribute($attributeCode);
if ($product->getTypeInstance()->canUseAttribute($attribute)) {
if ($new) { // fix for duplicating attributes error
$usingAttributeIds[] = $attribute->getAttributeId();
}
}
}
if (!empty($usingAttributeIds)) {
$product->getTypeInstance()->setUsedProductAttributeIds($usingAttributeIds);
$product->setConfigurableAttributesData($product->getTypeInstance()->getConfigurableAttributesAsArray());
$product->setCanSaveConfigurableAttributes(true);
$product->setCanSaveCustomOptions(true);
}
if (isset($importData['associated'])) {
$product->setConfigurableProductsData($this->skusToIds($importData['associated'], $product));
}
}

        /**
         * Init product links data (related, upsell, crosssell, grouped)
         */
if (isset($importData['related'])) {
$linkIds = $this->skusToIds($importData['related'], $product);
if (!empty($linkIds)) {
$product->setRelatedLinkData($linkIds);
}
}
if (isset($importData['upsell'])) {
$linkIds = $this->skusToIds($importData['upsell'], $product);
if (!empty($linkIds)) {
$product->setUpSellLinkData($linkIds);
}
}
if (isset($importData['crosssell'])) {
$linkIds = $this->skusToIds($importData['crosssell'], $product);
if (!empty($linkIds)) {
$product->setCrossSellLinkData($linkIds);
}
}
if (isset($importData['grouped'])) {
$linkIds = $this->skusToIds($importData['grouped'], $product);
if (!empty($linkIds)) {
$product->setGroupedLinkData($linkIds);
}
}
//================================================





        if (isset($importData['category_ids'])) {
            $product->setCategoryIds($importData['category_ids']);
        }

        foreach ($this->_ignoreFields as $field) {
            if (isset($importData[$field])) {
                unset($importData[$field]);
            }
        }

        if ($store->getId() != 0) {
            $websiteIds = $product->getWebsiteIds();
            if (!is_array($websiteIds)) {
                $websiteIds = array();
            }
            if (!in_array($store->getWebsiteId(), $websiteIds)) {
                $websiteIds[] = $store->getWebsiteId();
            }
            $product->setWebsiteIds($websiteIds);
        }

        if (isset($importData['websites'])) {
            $websiteIds = $product->getWebsiteIds();
            if (!is_array($websiteIds)) {
                $websiteIds = array();
            }
            $websiteCodes = split(',', $importData['websites']);
            foreach ($websiteCodes as $websiteCode) {
                try {
                    $website = Mage::app()->getWebsite(trim($websiteCode));
                    if (!in_array($website->getId(), $websiteIds)) {
                        $websiteIds[] = $website->getId();
                    }
                }
                catch (Exception $e) {}
            }
            $product->setWebsiteIds($websiteIds);
            unset($websiteIds);
        }

        foreach ($importData as $field => $value) {
            if (in_array($field, $this->_inventorySimpleFields)) {
                continue;
            }
            if (in_array($field, $this->_imageFields)) {
                continue;
            }

            $attribute = $this->getAttribute($field);
            if (!$attribute) {
                continue;
            }

            $isArray = false;
            $setValue = $value;

            if ($attribute->getFrontendInput() == 'multiselect') {
                $value = split(self::MULTI_DELIMITER, $value);
                $isArray = true;
                $setValue = array();
            }

            if ($value && $attribute->getBackendType() == 'decimal') {
                $setValue = $this->getNumber($value);
            }

            if ($attribute->usesSource()) {
                $options = $attribute->getSource()->getAllOptions(false);

                if ($isArray) {
                    foreach ($options as $item) {
                        if (in_array($item['label'], $value)) {
                            $setValue[] = $item['value'];
                        }
                    }
                }
                else {
                    $setValue = null;
                    foreach ($options as $item) {
                        if ($item['label'] == $value) {
                            $setValue = $item['value'];
                        }
                    }
                }
            }

            $product->setData($field, $setValue);
        }

        if (!$product->getVisibility()) {
            $product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE);
        }

        $stockData = array();
        $inventoryFields = $product->getTypeId() == 'simple' ? $this->_inventorySimpleFields : $this->_inventoryOtherFields;
        foreach ($inventoryFields as $field) {
            if (isset($importData[$field])) {
                if (in_array($field, $this->_toNumber)) {
                    $stockData[$field] = $this->getNumber($importData[$field]);
                }
                else {
                    $stockData[$field] = $importData[$field];
                }
            }
        }
        $product->setStockData($stockData);

        $imageData = array();
        foreach ($this->_imageFields as $field) {
            if (!empty($importData[$field]) && $importData[$field] != 'no_selection') {
                if (!isset($imageData[$importData[$field]])) {
                    $imageData[$importData[$field]] = array();
                }
                $imageData[$importData[$field]][] = $field;
            }
        }

        foreach ($imageData as $file => $fields) {
            try {
                $product->addImageToMediaGallery(Mage::getBaseDir('media') . DS . 'import' . $file, $fields);
            }
            catch (Exception $e) {}
        }

        $product->setIsMassupdate(true);
        $product->setExcludeUrlRewrite(true);

        $product->save();

        return true;
    }



    
    protected function userCSVDataAsArray($data) {
return explode(',', str_replace(" ", "", $data));
}

protected function skusToIds($userData,$product) {
$productIds = array();
foreach ($this->userCSVDataAsArray($userData) as $oneSku) {
if (($a_sku = (int)$product->getIdBySku($oneSku)) > 0) {
parse_str("position=", $productIds[$a_sku]);
}
}
return $productIds;
}

    
}

4- Create a csv  "Product_Amber.csv" with fields:-
websites,type,attribute_set,tax_class_id,weight,name,shoe_size,sku,price,description,short_description,category_ids,has_options,visibility,required_options,is_in_stock,qty,status,associated,config_attributes


5- Go to "var" folder and create a new folder with name "import" .Then copy and paste  "Product_Amber.csv"  in this folder.

6- Then open the new advance profile "ImportConfigurableProduct"

Go to "Run Profile" tab and the click on the button "Run Profile In Popup" 

Now you can check your configurable products import successfully with their associated products but not visible on front-end ,because the quantity of configurable and associated products is not set.


7- Create a new csv file with any name like "importDetails.csv" with fields:-

sku,qty,is_in_stock,_type


8- Then go to System->Profiles->Click on "Import All Products":-
  1. Select "Upload file" tab->Browse "importDetails.csv" and then click "Save and Continue Editing".
  2. Select "Run Profile" tab,select last uploaded file and the click on the button "Run Profile In Popup" 
Now you can see your newly added configurable product on front-end under a category.In our example Category id is 7.

That's all.
Enjoy.. :)


5 comments:

  1. Hi

    I added product as per your instruction but product is not display in my frontend
    could you pleaes let me know what can be issue

    thanks

    ReplyDelete
  2. Thank you for sharing. For people with some technical knowledge it will be very valuable, but for ordinary store owners who do not know where to paste a piece of code or change some lines, here is also article that might be helpful to perform Magento configurable products import without coding -
    http://blog.mag-manager.com/2013/08/import-magento-configurable-products.html

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. Thanks for the code, it works good, but i like to have inventory in same csv and i like to have image upload also. can you help me to do it..

    ReplyDelete
  5. Hi, Very easy with http://www.mlx-store.com/magento-extensions/import-export/export-import-bulk-product-with-configurable-product-bundle-product-grouped-product-downloadable-product-tier-price-group-price-related-products-up-sells-cross-sells-product-tags-magento.html

    ReplyDelete