0
votes

I use magento 1.7.
I'm trying to make an ad module with magento.
User can post ads as a product and when he paid the order i want to enable the ad (product). For that i listen to sales_order_invoice_save_after. Everything works but when i try to save the product in the event listener, the save function throws an exception:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails

My function looks like this :

public function onInvoiceSaveAfter(Varien_Event_Observer $observer)
{
    $event = $observer->getEvent();
    $invoice = $event->getInvoice();
    switch($invoice->getState())
    {
       case Mage_Sales_Model_Order_Invoice::STATE_PAID :
       {

          $order = $invoice->getOrder();
          $items = $order->getAllItems();

          //Update the product
          $product = Mage::getModel('catalog/product')->load($item->getEntityId());
          $product->setAdEndDate('2015-10-10 00:00:00');
          $product->getResource()->saveAttribute($product, 'ad_end_date'); //Throws exception
        }
}

Can anyone help me please?
How can i achieve that?

1

1 Answers

0
votes

I believe it's because you don't actually have an item that you're working with (you never use a foreach() loop). Try this:

public function onInvoiceSaveAfter(Varien_Event_Observer $observer)
{
    $event = $observer->getEvent();
    $invoice = $event->getInvoice();
    switch ($invoice->getState()) {
        case Mage_Sales_Model_Order_Invoice::STATE_PAID :
        {

            $order = $invoice->getOrder();
            $items = $order->getAllItems();

            foreach ($items as $item) {
                //Update the product
                $product = Mage::getModel('catalog/product')->load($item->getProductId());
                $product->setAdEndDate('2015-10-10 00:00:00');
                $product->getResource()->saveAttribute($product, 'ad_end_date'); //Throws exception
            }

        }
    }
}

If that doesn't work, try saving the product directly instead of just updating one attribute:

$product->save()