5

I made this code for assigning simple product detail to configurable product but in this code, I can not set the image so please help me on that

<?php
require_once('app/Mage.php'); 
umask(0);
Mage::app('default');
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$_productCollection = Mage::getModel('catalog/product')
    ->getCollection()
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('type_id', array('eq' => 'simple'))
    ->addAttributeToFilter('status', array('eq' => 1));
foreach ($_productCollection as $_product) 
{
    $id = $_product->getId();
    $simpleProduct = Mage::getModel('catalog/product')->load($id);
    $configProduct = Mage::getModel('catalog/product');
    $configProduct
    ->setWebsiteIds($simpleProduct->getWebsiteIds())
    ->setAttributeSetId(4)
    ->setTypeId('configurable')
    ->setSku(str_replace(" ","",$simpleProduct->getSku()."_new"))
    ->setName($simpleProduct->getName())
    ->setWeight($simpleProduct->getWeight())
    ->setStatus(1)
    ->setTaxClassId($simpleProduct->getTaxClassId())
    ->setVisibility($simpleProduct->getVisibility())
    ->setPrice($simpleProduct->getPrice())
    ->setCost($simpleProduct->getCost())
    ->setSpecialPrice($simpleProduct->getSpecialPrice())
    ->setSpecialFromDate($simpleProduct->getSpecialFromDate())
    ->setSpecialToDate($simpleProduct->getSpecialToDate())
    ->setDescription($simpleProduct->getDescription())
    ->setShortDescription($simpleProduct->getShortDescription())
    ->setMediaGallery($simpleProduct->getMediaGallery())
    // ->setImage($simpleProduct->getImage())
    // ->setSmallImage($simpleProduct->getSmallImage())
    // ->setThumbnail($simpleProduct->getThumbnail())
    ->setStockData(array(
        'use_config_manage_stock' => 0,
        'manage_stock' => 1,
        'is_in_stock' => 1,
        )
    )
    ->setCategoryIds($simpleProduct->getCategoryIds())
    ;
    try
    {
        $configProduct->save();
    }
    catch (Exception $e) 
    {
        Mage::log($e->getMessage());
        echo $e->getMessage();
        exit();
    }
}
2
  • Why would you not just do this through Dataflow import with the following headers sku, image, thumbnail, small_image this is the easiest way to do it Sep 13, 2017 at 21:25
  • @Kushal if the given answers are not sufficient for your needs you may consider providing more details about what your looking for. Jan 10, 2018 at 5:29

2 Answers 2

4
+50

Assuming, that the loaded simple product does hold an image you can do it like so (see addImageToMediaGallery()):

<?php
require_once('app/Mage.php'); 
umask(0);
Mage::app('default');
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$_productCollection = Mage::getModel('catalog/product')
    ->getCollection()
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('type_id', array('eq' => 'simple'))
    ->addAttributeToFilter('status', array('eq' => 1));
foreach ($_productCollection as $_product) 
{
    $id = $_product->getId();
    $simpleProduct = Mage::getModel('catalog/product')->load($id);
    $configProduct = Mage::getModel('catalog/product');
    $configProduct
    ->setWebsiteIds($simpleProduct->getWebsiteIds())
    ->setAttributeSetId(4)
    ->setTypeId('configurable')
    ->setSku(str_replace(" ","",$simpleProduct->getSku()."_new"))
    ->setName($simpleProduct->getName())
    ->setWeight($simpleProduct->getWeight())
    ->setStatus(1)
    ->setTaxClassId($simpleProduct->getTaxClassId())
    ->setVisibility($simpleProduct->getVisibility())
    ->setPrice($simpleProduct->getPrice())
    ->setCost($simpleProduct->getCost())
    ->setSpecialPrice($simpleProduct->getSpecialPrice())
    ->setSpecialFromDate($simpleProduct->getSpecialFromDate())
    ->setSpecialToDate($simpleProduct->getSpecialToDate())
    ->setDescription($simpleProduct->getDescription())
    ->setShortDescription($simpleProduct->getShortDescription())
    ->addImageToMediaGallery(Mage::getBaseDir('media').DS.'catalog'.DS.'product'.$simpleProduct->getImage(), 'image', false, false)
    ->setStockData(array(
        'use_config_manage_stock' => 0,
        'manage_stock' => 1,
        'is_in_stock' => 1,
        )
    )
    ->setCategoryIds($simpleProduct->getCategoryIds())
    ;
    try
    {
        $configProduct->save();
    }
    catch (Exception $e) 
    {
        Mage::log($e->getMessage());
        echo $e->getMessage();
        exit();
    }
}

Take a look at Mage_Catalog_Model_Product for further details (see snippet below). In the above mentioned function (addImageToMediaGallery()) you have four parameters:

  1. $file ... which specifies the image file path
  2. $mediaAttribute ... with which you can specify whether you'd like to set the given image as (main-)image, small image or thumbnail - or none of these to just add it to the gallery. You can pass an array such as array('image','small_image','thumbnail'), a single var such as image or null to add it to the gallery only.
  3. $move ... handle with care - in your case, since your fetching the image from an existing simple product, this will lead to a broken link in your simple product (hence should be kept as false here)
  4. set $exclude to true in case you don't want the image to be visible in the frontend gallery (seems not to be indented here either)

Also, in order to successfully assign an image you must make sure, that the given path (image) actually exists (via some cross-checking for example). The image path given by $simpleProduct->getImage() will return something like this only: /M/y/My-fancy-image-file.jpg. However, the actual image location is media/catalog/product/M/y/My-fancy-image-file.jpg - so you will have to add Mage::getBaseDir('media').DS.'catalog'.DS.'product' as a prefix to the simple product's path.

Relevant snippet of app/code/core/Mage/Catalog/Model/Product.php for reference:

/**
 * Add image to media gallery
 *
 * @param string        $file              file path of image in file system
 * @param string|array  $mediaAttribute    code of attribute with type 'media_image',
 *                                          leave blank if image should be only in gallery
 * @param boolean       $move              if true, it will move source file
 * @param boolean       $exclude           mark image as disabled in product page view
 * @return Mage_Catalog_Model_Product
 */
public function addImageToMediaGallery($file, $mediaAttribute=null, $move=false, $exclude=true)
{
    $attributes = $this->getTypeInstance(true)->getSetAttributes($this);
    if (!isset($attributes['media_gallery'])) {
        return $this;
    }
    $mediaGalleryAttribute = $attributes['media_gallery'];
    /* @var $mediaGalleryAttribute Mage_Catalog_Model_Resource_Eav_Attribute */
    $mediaGalleryAttribute->getBackend()->addImage($this, $file, $mediaAttribute, $move, $exclude);
    return $this;
}
0

add for simple product get images.

     $productImages = Mage::getBaseDir(). DS .'media'. DS .'catalog'. 
     DS .  'product';

 foreach ($simpleProduct->getMediaGallery() as $imagesSimple) {

          $countSimple = count($imagesSimple[0]);

          $imageFilePath = array_values($imagesSimple[0]);

          break;

 }

in try section add code

 try
   {
    if(count($imageFilePath)){

          $filename = $productImages.$imageFilePath[1];  

          if(file_exists($filename)) {   

          $configProduct->addImageToMediaGallery($filename, 
         array('image','thumbnail','small_image'), false, false);     
          $configProduct->save();  
        } 

       }

   }

Your Answer

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

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