Wednesday 12 September 2012

Display multiple image for particular product

I’ve seen some solutions out there that modify core code, some that just take a file and move it to your /app/code/local/ retaining the same directory structure, so as to just override the file. I don’t recommend either of these methods (especially the first), as with a true module you are setting up a much better environment over time for this to last. And a module allows you to ONLY override the methods you need to modify, instead of entire classes. Plus, you can easily disable the module right in the admin (Admin >> System >> Configuration >> Advanced).

Be sure you replace all of the “YOURSTUFF” with your name or company name.

I have only tested this with 1.3.2.4
Step 1:

Create the file: /app/etc/modules/YOURSTUFF_ImportMultipleImages.xml. This file tells Magento that you have this module and where it is located.

<?xml version="1.0"?>
<config>
    <modules>
        <yourstuff_ImportMultipleImages>
            <active>true</active>
            <codePool>local</codePool>
        </yourstuff_ImportMultipleImages>
    </modules>
</config>



Step 2:

Create the file: /app/code/local/YOURSTUFF/ImportMultipleImages/etc/config.xml. This file is the configuration file for your module. It tells Magento which class we are going to override.

<?xml version="1.0"?>
<config>
    <modules>
        <yourstuff_ImportMultipleImages>
            <version>0.1.0</version>
        </yourstuff_ImportMultipleImages>
    </modules>
    <global>
        <models>
            <catalog>
                <rewrite>
                    <!-- Override Mage_Catalog_Model_Convert_Adapter_Product -->
                    <convert_adapter_product>YOURSTUFF_ImportMultipleImages_Model_Convert_Adapter_Product</convert_adapter_product>
                </rewrite>
            </catalog>
        </models>
    </global>
</config>

Step 3:

Create the file: /app/code/local/YOURSTUFF/ImportMultipleImages/Model/Convert/Adapter/Product.php. Important note: When creating a module, you only want to include the methods that you are actually modifying. As you can see, we are extending the original class, so we’ll have all of the methods from the original, but since we have the saveRow() method in our class, ours will take precedence. We do it this way because when you upgrade Magento, you’ll only need to make sure you check the one method for changes, instead of the entire class.

Again, be sure to replace the “YOURSTUFF” in the class name to your name or company name.

<?php
/**
 * Import Multiple Images during Product Import
 *
 */

class YOURSTUFF_ImportMultipleImages_Model_Convert_Adapter_Product 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()
            ->reset();

        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']);

        if ($productId) {
            $product->load($productId);
        }
        else {
            $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->setProductTypeInstance($product);

        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->_inventoryFields)) {
                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 = isset($this->_inventoryFieldsProductTypes[$product->getTypeId()])
            ? $this->_inventoryFieldsProductTypes[$product->getTypeId()]
            : array();
        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) {}
        }

  /**
   * Allows you to import multiple images for each product.
   * Simply add a 'gallery' column to the import file, and separate
   * each image with a semi-colon.
   */
         try {
                 $galleryData = explode(';',$importData["gallery"]);
                 foreach($galleryData as $gallery_img)
     /**
      * @param directory where import image resides
      * @param leave 'null' so that it isn't imported as thumbnail, base, or small
      * @param false = the image is copied, not moved from the import directory to it's new location
      * @param false = not excluded from the front end gallery
      */
                 {
                         $product->addImageToMediaGallery(Mage::getBaseDir('media') . DS . 'import' . $gallery_img, null, false, false);
                 }
             }
         catch (Exception $e) {}
  /* End Modification */

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

        $product->save();

        return true;
    }
}

Step 4:

Test it out! This is how it works: Use the Magento product import functionality (Admin >> System >> Import/Export >> Profiles >> Import All Products). Add a column to your CSV called ‘gallery’. In that column, simply put all the images you’d like that product to have, separated by semi-colons. The same exact rules apply for these images as do the ‘image’, ‘small_image’, and ‘thumbnail’ columns, in that if you are putting all your images in the /media/import/ directory, you’ll have to include the forward-slash in the image names. Here’s an example (be sure to leave out any spaces):

Your gallery column could look like: /image1.jpg;/image2.jpg;/image3.jpg

These images will all show up just as if you were to go into the product edit in the admin and upload them. They’ll be copied from the /media/import/ directory into the proper media directory structure, and they’ll show up as thumbnails below your main product image on the product view page.

I’ve seen some solutions out there that modify core code, some that just take a file and move it to your /app/code/local/ retaining the same directory structure, so as to just override the file. I don’t recommend either of these methods (especially the first), as with a true module you are setting up a much better environment over time for this to last. And a module allows you to ONLY override the methods you need to modify, instead of entire classes. Plus, you can easily disable the module right in the admin (Admin >> System >> Configuration >> Advanced).

Be sure you replace all of the “YOURSTUFF” with your name or company name.

I have only tested this with 1.3.2.4
Step 1:

Create the file: /app/etc/modules/YOURSTUFF_ImportMultipleImages.xml. This file tells Magento that you have this module and where it is located.

<?xml version="1.0"?>
<config>
    <modules>
        <yourstuff_ImportMultipleImages>
            <active>true</active>
            <codePool>local</codePool>
        </yourstuff_ImportMultipleImages>
    </modules>
</config>

Step 2:

Create the file: /app/code/local/YOURSTUFF/ImportMultipleImages/etc/config.xml. This file is the configuration file for your module. It tells Magento which class we are going to override.

<?xml version="1.0"?>
<config>
    <modules>
        <yourstuff_ImportMultipleImages>
            <version>0.1.0</version>
        </yourstuff_ImportMultipleImages>
    </modules>
    <global>
        <models>
            <catalog>
                <rewrite>
                    <!-- Override Mage_Catalog_Model_Convert_Adapter_Product -->
                    <convert_adapter_product>YOURSTUFF_ImportMultipleImages_Model_Convert_Adapter_Product</convert_adapter_product>
                </rewrite>
            </catalog>
        </models>
    </global>
</config>

Step 3:

Create the file: /app/code/local/YOURSTUFF/ImportMultipleImages/Model/Convert/Adapter/Product.php. Important note: When creating a module, you only want to include the methods that you are actually modifying. As you can see, we are extending the original class, so we’ll have all of the methods from the original, but since we have the saveRow() method in our class, ours will take precedence. We do it this way because when you upgrade Magento, you’ll only need to make sure you check the one method for changes, instead of the entire class.

Again, be sure to replace the “YOURSTUFF” in the class name to your name or company name.

<?php
/**
 * Import Multiple Images during Product Import
 *
 */

class YOURSTUFF_ImportMultipleImages_Model_Convert_Adapter_Product 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()
            ->reset();

        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']);

        if ($productId) {
            $product->load($productId);
        }
        else {
            $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->setProductTypeInstance($product);

        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->_inventoryFields)) {
                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 = isset($this->_inventoryFieldsProductTypes[$product->getTypeId()])
            ? $this->_inventoryFieldsProductTypes[$product->getTypeId()]
            : array();
        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) {}
        }

  /**
   * Allows you to import multiple images for each product.
   * Simply add a 'gallery' column to the import file, and separate
   * each image with a semi-colon.
   */
         try {
                 $galleryData = explode(';',$importData["gallery"]);
                 foreach($galleryData as $gallery_img)
     /**
      * @param directory where import image resides
      * @param leave 'null' so that it isn't imported as thumbnail, base, or small
      * @param false = the image is copied, not moved from the import directory to it's new location
      * @param false = not excluded from the front end gallery
      */
                 {
                         $product->addImageToMediaGallery(Mage::getBaseDir('media') . DS . 'import' . $gallery_img, null, false, false);
                 }
             }
         catch (Exception $e) {}
  /* End Modification */

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

        $product->save();

        return true;
    }
}

Step 4:

Test it out! This is how it works: Use the Magento product import functionality (Admin >> System >> Import/Export >> Profiles >> Import All Products). Add a column to your CSV called ‘gallery’. In that column, simply put all the images you’d like that product to have, separated by semi-colons. The same exact rules apply for these images as do the ‘image’, ‘small_image’, and ‘thumbnail’ columns, in that if you are putting all your images in the /media/import/ directory, you’ll have to include the forward-slash in the image names. Here’s an example (be sure to leave out any spaces):

Your gallery column could look like: /image1.jpg;/image2.jpg;/image3.jpg

These images will all show up just as if you were to go into the product edit in the admin and upload them. They’ll be copied from the /media/import/ directory into the proper media directory structure, and they’ll show up as thumbnails below your main product image on the product view page.

I’ve seen some solutions out there that modify core code, some that just take a file and move it to your /app/code/local/ retaining the same directory structure, so as to just override the file. I don’t recommend either of these methods (especially the first), as with a true module you are setting up a much better environment over time for this to last. And a module allows you to ONLY override the methods you need to modify, instead of entire classes. Plus, you can easily disable the module right in the admin (Admin >> System >> Configuration >> Advanced).

Be sure you replace all of the “YOURSTUFF” with your name or company name.

I have only tested this with 1.3.2.4
Step 1:

Create the file: /app/etc/modules/YOURSTUFF_ImportMultipleImages.xml. This file tells Magento that you have this module and where it is located.

<?xml version="1.0"?>
<config>
    <modules>
        <yourstuff_ImportMultipleImages>
            <active>true</active>
            <codePool>local</codePool>
        </yourstuff_ImportMultipleImages>
    </modules>
</config>

Step 2:

Create the file: /app/code/local/YOURSTUFF/ImportMultipleImages/etc/config.xml. This file is the configuration file for your module. It tells Magento which class we are going to override.

<?xml version="1.0"?>
<config>
    <modules>
        <yourstuff_ImportMultipleImages>
            <version>0.1.0</version>
        </yourstuff_ImportMultipleImages>
    </modules>
    <global>
        <models>
            <catalog>
                <rewrite>
                    <!-- Override Mage_Catalog_Model_Convert_Adapter_Product -->
                    <convert_adapter_product>YOURSTUFF_ImportMultipleImages_Model_Convert_Adapter_Product</convert_adapter_product>
                </rewrite>
            </catalog>
        </models>
    </global>
</config>

Step 3:

Create the file: /app/code/local/YOURSTUFF/ImportMultipleImages/Model/Convert/Adapter/Product.php. Important note: When creating a module, you only want to include the methods that you are actually modifying. As you can see, we are extending the original class, so we’ll have all of the methods from the original, but since we have the saveRow() method in our class, ours will take precedence. We do it this way because when you upgrade Magento, you’ll only need to make sure you check the one method for changes, instead of the entire class.

Again, be sure to replace the “YOURSTUFF” in the class name to your name or company name.

<?php
/**
 * Import Multiple Images during Product Import
 *
 */

class YOURSTUFF_ImportMultipleImages_Model_Convert_Adapter_Product 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()
            ->reset();

        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']);

        if ($productId) {
            $product->load($productId);
        }
        else {
            $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->setProductTypeInstance($product);

        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->_inventoryFields)) {
                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 = isset($this->_inventoryFieldsProductTypes[$product->getTypeId()])
            ? $this->_inventoryFieldsProductTypes[$product->getTypeId()]
            : array();
        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) {}
        }

  /**
   * Allows you to import multiple images for each product.
   * Simply add a 'gallery' column to the import file, and separate
   * each image with a semi-colon.
   */
         try {
                 $galleryData = explode(';',$importData["gallery"]);
                 foreach($galleryData as $gallery_img)
     /**
      * @param directory where import image resides
      * @param leave 'null' so that it isn't imported as thumbnail, base, or small
      * @param false = the image is copied, not moved from the import directory to it's new location
      * @param false = not excluded from the front end gallery
      */
                 {
                         $product->addImageToMediaGallery(Mage::getBaseDir('media') . DS . 'import' . $gallery_img, null, false, false);
                 }
             }
         catch (Exception $e) {}
  /* End Modification */

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

        $product->save();

        return true;
    }
}

Step 4:

Test it out! This is how it works: Use the Magento product import functionality (Admin >> System >> Import/Export >> Profiles >> Import All Products). Add a column to your CSV called ‘gallery’. In that column, simply put all the images you’d like that product to have, separated by semi-colons. The same exact rules apply for these images as do the ‘image’, ‘small_image’, and ‘thumbnail’ columns, in that if you are putting all your images in the /media/import/ directory, you’ll have to include the forward-slash in the image names. Here’s an example (be sure to leave out any spaces):

Your gallery column could look like: /image1.jpg;/image2.jpg;/image3.jpg

These images will all show up just as if you were to go into the product edit in the admin and upload them. They’ll be copied from the /media/import/ directory into the proper media directory structure, and they’ll show up as thumbnails below your main product image on the product view page.

Reffered in : http://prattski.com/2009/10/09/magento-import-multiple-images-for-products-module/

No comments:

Post a Comment