【问题标题】:Duplicating a product with Code in Magento在 Magento 中使用代码复制产品
【发布时间】:2011-12-05 09:12:02
【问题描述】:

我正在尝试编写一个自定义模块,该模块能够将一个产品复制到具有不同 SKU 的多个产品中。我尝试在自定义模块中的 /app/code/core/Mage/Catalog/Model/Product.php 下使用function duplicate()。但它不起作用。

我在我的自定义 Obesrever.php 文件中使用以下代码进行复制,但没有发生复制

$product = $observer->getEvent()->getProduct();
$newProduct = $product->duplicate();

谁能给我建议任何链接或任何代码格式会有所帮助。

谢谢

【问题讨论】:

  • 请更准确地定义“不工作”。
  • 我已经在我的问题中简要介绍了。请看一下
  • 您是否已经证明您的自定义观察者确实被调用了?如果是这样,$newProduct 包含什么?是null 还是Mage_Sales_Catalog_Product 的一个实例?如果是null,请检查您的exception.log
  • 是的.. 我可以确认我的自定义观察者被调用了。我通过打印文本并退出观察者来检查它。我刚刚在 productController 中的 duplicateAction() 下找到了这段代码 ($product->duplicate()),并认为它可以帮助我复制产品并使用它。但是没有用..不确定我在代码中缺少什么
  • duplicate() 方法应该可以工作(我自己用过几次)。我的猜测是,duplicate() 引发了一个您不知道的异常。检查$newProduct 包含什么类型的数据。是null,还是Mage_Catalog_Model_Product的实例(我之前的评论写错了类名,抱歉)?

标签: magento


【解决方案1】:

如果您可以发布您尝试调试或创建重复产品和 config.xml(您尝试调用事件的位置)的完整功能,那就太好了。

以下代码在 CE 1.9.2.2 中适用于我,没有任何问题。此函数执行以下任务:

  1. 创建原始产品的副本
  2. 将库存设置为“有货”,将数量设置为“100”(目前为硬编码)
  3. 自动重新索引
public function indexAction() //change the function name
{
    $productId      = $observer->getEvent()->getProduct()->getId();

    $productObject  = Mage::getModel('catalog/product');    
    $_product       = $productObject->load($productId);

    $newProduct     = $_product->duplicate();

    //new product status is disabled - to view in the frontend you will need to set the status as enabled
    $newProduct->setStatus(1);
    $newProduct->setName('Duplicate-' . $_product->getName());
    $newProduct->setSku('value-' . $productId);
    $newProduct->setWebsiteIds($_product->getWebsiteIds());

    //set the product stock and qty to display product in the frontend
    //while creating duplicate product, it will update the new product to have qty 0 and out of stock
    $stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($newProduct->getId());
    if ($stockItem->getId() > 0 && $stockItem->getManageStock())
    {
        $qty = 100;
        $stockItem->setQty($qty);
        $stockItem->setIsInStock((int)($qty > 0));
        $stockItem->save();
    }

    $newProduct->getResource()->save($newProduct);

    //automate reindexing - to display the product in the frontend
    $indexers = Mage::getSingleton('index/indexer')->getProcessesCollection();
    foreach ($indexers as $indexer)
    {
        $indexer->reindexEverything();
    }
}

希望这会有所帮助。

快乐编码...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多