Sri February 2016

Magento duplicating a product programtically is not displaying in the frontend

I am new to magneto I have tried to duplicate a product programmatically and I have succeeded problem is the duplicated product is showing in magneto admin side while in the frontend the product is not displaying below is my code could you please tell me what is the issue it will be very helpful for me. I have created a separate module for it below is my code.

class Magentotutorial_Helloworld_IndexController extends Mage_Core_Controller_Front_Action {        
    public function indexAction() {
        $final = $_POST['value'];
        $obj = Mage::getModel('catalog/product');
        $_product = $obj->load($final); 
        $newProduct = $_product->duplicate();

        $newProduct->setStatus(1);


        $newProduct->setSku('value'.$final);
         $newProduct->setWebsiteIds($_product->getWebsiteIds());
        $newProduct->getResource()->save($newProduct);
    }

}

Answers


Shivani February 2016

This function posted by you very well creates Duplicate product. However, it does not set the below attribute (due to which it's not VISIBLE in the frontend):

  1. Navigate to Catalog > Manage Products > Duplicated Product > Inventory

Qty is 0 and Stock is "Out of Stock" - You will need to write below piece of code in the function to set this product to Stock: "In Stock" and Qty: [some default value] say, 100.

After the line which calls out $newProduct->setWebsiteIds($_product->getWebsiteIds());, you can insert the below lines:

$stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($newProduct->getId());
if ($stockItem->getId() > 0 && $stockItem->getManageStock())
{
    $qty = 100; //set a default max value
    $stockItem->setQty($qty);
    $stockItem->setIsInStock((int)($qty > 0));
    $stockItem->save();
}
  1. You will need to run a Re-Index either Manually or Automate it

The product will display in the frontend. See Screenshot below:

enter image description here

[EDIT]

Use the below code and let me know if it works for you:

public function indexAction()
{
    $productId      = $this->getRequest()->getParam('value');
    $productObject  = Mage::getModel('catalog/product');

    $_product   = $productObject->load($productId);

    $newProduct = $_product->duplicate();

    $newProduct->setStatus(1);
    //$newProduct->setName('Duplicate-' . $_product->getName());
    $newProduct->setSku('value' . $productId);
    $newProduct->setWebsiteIds($_product->getWebsiteIds()) 

Post Status

Asked in February 2016
Viewed 2,668 times
Voted 6
Answered 1 times

Search




Leave an answer