2

I want to create the simple product from custom option which is already assigned to several simple products and there are the bunch of products so is there any code available who create the simple product from custom option?

  • Can you please explain more if possible with example? – Jaimin Sutariya Sep 12 '17 at 17:33
1
<?php
 ini_set('max_execution_time', 36000);
ini_set('post_max_size', '5000M');
ini_set("memory_limit","4046M");
ini_set('upload_max_filesize', '5000M');
require_once('app/Mage.php'); //Path to Magento
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) 
{
    if($_product->getData('has_options') != 0) 
    {
        $options = Mage::getModel('catalog/product_option')->getProductOptionCollection($_product);
        $main = array();
        $title = array();
        $simpleproductarray = array();
        $simpleproductidlist = array();
        foreach($options as $option)
        {
            $sub = array();
            foreach($option->getValues() as $value) 
            {
                array_push($sub, $value->getTitle());
            } 
            array_push($main,$sub);
            array_push($title, $option->getTitle());
        }
        if(count(combinations($main)) > 0)
        {
            $simpleproductarray = combinations($main);   
            for($l = 0 ;$l < count(combinations($main)); $l++)
            {
                $simpleproductid = simpleproduct($simpleproductarray[$l],$title);
                array_push($simpleproductidlist, $simpleproductid);
            }
        }
        configurableproducts($simpleproductidlist,$_product->getId(),$title);
    }
}             
reindexAll();

function reindexAll()
{
    $indexingProcesses = Mage::getSingleton('index/indexer')->getProcessesCollection(); 
    try
    {
        foreach ($indexingProcesses as $process) 
        {
            $process->reindexEverything();
        }
    }
    catch (Exception $e) 
    {
        Mage::log($e->getMessage());
    }
}

function configurableproducts($simpleproductidlist,$id,$title)
{

    $attributelist = array();
    for($l=0; $l < count($title) ; $l++)
    {
        if (strpos($title[$l], '&') !== false)
        {
            $atributeCode = str_replace("&","",$title[$l]);
            $atributeCode = str_replace(" ","_",strtolower($atributeCode)); 
        }
        else
        {
            $atributeCode = str_replace(" ","_",strtolower($title[$l]));    
        }
        $attribute = Mage::getModel('eav/config')->getAttribute('catalog_product',$atributeCode);
        array_push($attributelist,$attribute->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())
    ;
    $configProduct->getTypeInstance()->setUsedProductAttributeIds($attributelist);
    $configurableAttributesData = $configProduct->getTypeInstance()->getConfigurableAttributesAsArray();
    $configProduct->setCanSaveConfigurableAttributes(true);
    $configProduct->setConfigurableAttributesData($configurableAttributesData);
    try
    {
        $configProduct->save();
        Mage::getResourceSingleton('catalog/product_type_configurable')
        ->saveProducts($configProduct, $simpleproductidlist);
        // $simpleProduct->setStatus(2);
        // $simpleProduct->save();
        echo "Name = ".$configProduct->getName()."</br>";
    }
    catch (Exception $e) 
    {
        Mage::log($e->getMessage());
        echo $e->getMessage();
        exit();
    }
}


function simpleproduct($simpleproductfunction,$title)
{
    $sku = "";
    $rand = rand(1, 9999);
    if(is_array($simpleproductfunction))
    {
        for($k = 0;$k < count($simpleproductfunction); $k++)
        {
            if($sku == "")
            {
                $name = $simpleproductfunction[$k];
                $sku = strtolower($simpleproductfunction[$k]);
            }
            else
            {
                $sku = $sku."_".strtolower($simpleproductfunction[$k]);
                $name = $name ." and ".$simpleproductfunction[$k];
            }
        }
    }
    else
    {
        $name = $simpleproductfunction;
        $sku = strtolower($simpleproductfunction);
    }
    $sku = $sku."_".$rand.date("dmYhis");

    $storeId = Mage::app()->getStore()->getStoreId();
    $websiteId = Mage::app()->getStore()->getWebsiteId();

    $product = Mage::getModel('catalog/product');

    $product
    ->setTypeId('simple')
    ->setAttributeSetId(4)
    ->setSku(str_replace(" ","",$sku))
    ->setWebsiteIDs(array($websiteId))
    ->setStatus(Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
    ->setVisibility(1)
    ->setStockData(array(
        'use_config_manage_stock' => 0, 
        'manage_stock'            => 1, 
        'is_in_stock'             => 1,
        'qty'                     => 5000,
        ))
    ->setName($name) 
    ->setShortDescription($name) 
    ->setDescription($name)
    ->setPrice(0)
    ->setTaxClassId(2)
    ->setWeight(0)
    ;
    for($l=0; $l < count($title) ; $l++)
    {
        if (strpos($title[$l], '&') !== false)
        {
            $atributeCode = str_replace("&","",$title[$l]);
            $atributeCode = str_replace(" ","_",strtolower($atributeCode)); 
        }
        else
        {
            $atributeCode = str_replace(" ","_",strtolower($title[$l]));    
        }
        $attribute = Mage::getModel('eav/config')->getAttribute('catalog_product',$atributeCode);
        $options = $attribute->getSource()->getAllOptions();
        foreach($options as $value)
        {
            if(is_array($simpleproductfunction))
            {
                if(strcasecmp(str_replace("_"," ",$value['label']),str_replace("_"," ",$simpleproductfunction[$l])) == 0)
                {
                    $atrvalue = $value['value'];
                    $product->setData($atributeCode,$atrvalue);
                }    
            }
            else
            {
                if(strcasecmp(str_replace("_"," ",$value['label']),str_replace("_"," ",$simpleproductfunction)) == 0)
                {
                    $atrvalue = str_replace("_"," ",$value['value']);
                    $product->setData($atributeCode,$atrvalue);
                }    
            }
        }
    }
    try
    {
        $product->save();
        $productid = Mage::getModel('catalog/product')->loadByAttribute('sku', str_replace(" ","",$sku));
        return $productid->getId();

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

function combinations($arrays, $i = 0) 
{
    if (!isset($arrays[$i])) {
        return array();
    }
    if ($i == count($arrays) - 1) {
        return $arrays[$i];
    }

    $tmp = combinations($arrays, $i + 1);

    $result = array();

    foreach ($arrays[$i] as $v) {
        foreach ($tmp as $t) {
            $result[] = is_array($t) ? 
            array_merge(array($v), $t) :
            array($v, $t);
        }
    }

    return $result;
}

I tried this in my local as you explain it and work properly but in my code, the image of simple product can not assign to configurable product.

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.