2013-01-01 34 views
4

我有一個類似萬阿英,蔣達清到Integrity constraint violation creating Product in Magento(未回答),但我創建掛鉤插入catalog_product_save_after事件定製的觀測 - 基於此教程:http://fishpig.co.uk/blog/custom-tabs-magento-product-admin.html完整性約束違反Magento的自定義模塊

但是每當有新產品救了我得到這個錯誤:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '22-1' for key 'UNQ_CATALOGINVENTORY_STOCK_ITEM_PRODUCT_ID_STOCK_ID' 

config.xml文件看起來是這樣的:

<adminhtml> 
    <events> 
     <catalog_product_save_after> 
      <observers> 
       <a1web_save_product_data> 
        <type>singleton</type> 
        <class>metricimperial/observer</class> 
        <method>saveProductData</method> 
       </a1web_save_product_data> 
      </observers> 
     </catalog_product_save_after> 
    </events> 
</adminhtml> 

的outli之類的NE是這樣的:

<?php 

class A1web_MetricImperialConverter_Model_Observer 
{ 
    /** 
    * Flag to stop observer executing more than once 
    * 
    * @var static bool 
    */ 
    static protected $_singletonFlag = false; 

    * @param Varien_Event_Observer $observer 
    */ 
    public function saveProductData(Varien_Event_Observer $observer) 
    { 
     if (!self::$_singletonFlag) { 
       self::$_singletonFlag = true; 

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

       //Custom updates made to product object here 

       $product->save(); 
      } 
      catch (Exception $e) { 
       Mage::getSingleton('adminhtml/session')->addError($e->getMessage()); 
      } 
     } 
    } 

    /** 
    * Retrieve the product model 
    * 
    * @return Mage_Catalog_Model_Product $product 
    */ 
    public function getProduct() 
    { 
     return Mage::registry('product'); 
    } 

    /** 
    * Shortcut to getRequest 
    * 
    */ 
    protected function _getRequest() 
    { 
     return Mage::app()->getRequest(); 
    } 
} 

產品與定製產品數據我加入正確保存 - 而一旦產品被保存在錯誤在後續不會出現同一產品的節省。只是在產品首次創建時發生錯誤。

在此先感謝

+1

在產品保存期間調用產品保存有點奇怪。你的觀察者究竟做了什麼?模塊名稱只是部分揭示其功能。使用屬性後端模型,您嘗試完成的任務可能可能/更好地完成。 – benmarks

+0

基本上@benmark說什麼。進行更改但不要求保存,magento會爲你做。你可能想澄清你想要做什麼。 –

+0

@DanielSloof他必須保存,這是事後觀察保存。 – benmarks

回答

24

而不是使用$product->save()嘗試使用資源模型,一拉$product->getResource()->save($product)

的原因是$product->save()將重新觸發所有保存的事件,因此運行無論是保存cataloginventory_stock並引發錯誤。

+1

這樣做!非常感謝富蘭克林。 –

+0

拯救生命的答案對我來說! –

1

在這種情況下,我建議使用而不是使用catalog_product_save_after事件。相反,嘗試使用catalog_product_prepare_save這是 POST數據應用於產品,但之前->save()被調用。這樣,你不必與保存或醜陋$_singletonFlag

此外,與catalog_product_prepare_save一樣,您將在Observer事件中獲得HTTP請求對象。不需要Mage::app()->getRequest()。活泉!