2

I am using sales_order_status_history_save_after event for store data in my custom table.

I need also update comment with a prefix of commentId (entity_id) in to sales_order_status_history table.

While I am doing setComment data in observer than two times data stored in my custom table.

also, I have added log in to the observer file I found that my event call two times. I did not understand why its call two times and my data stored 2 times in my custom table.

is anyone knows how we can solve this issue??

here is the code:

public function execute(Observer $observer)
{
    try {
         $statusHistory = $observer->getEvent()->getStatusHistory();
         $orderId = $statusHistory->getParentId();
         $commentId = $statusHistory->getId();
         $post = $this->request->getPostValue();

         $oldComment = $statusHistory->getComment();

         $newComment = "Comment Id : ".$commentId. $oldComment;

         $statusHistory->setComment($newComment);

         $_orderstatusdata = $post['order_reprint'];
         $bulkInsert = [];

         foreach ($_orderstatusdata as $orderstatusdata) {
            if($orderstatusdata['is_reprint']){

                $customdata = [];
                $customdata['key1'] = 'val1';
                $customdata['key2'] = 'val2';
                $customdata['key3'] = 'val3';
                $customdata['key4'] = 'val4';

                $bulkInsert[] = $customdata;

            }               
         }

        $connection->insertMultiple('custom_table',$bulkInsert);

    } catch (\Exception $e) {
        $this->logger->error($e);
    }
}
6
  • could you please post your code here ? Commented Oct 3, 2018 at 7:05
  • @DharmendraJadav: I have edit question with code. Please check Commented Oct 3, 2018 at 9:13
  • @KetanPanchal are you able to stop calling 2 times events ? Commented Aug 6, 2020 at 13:15
  • Yes @sumeetbajaj Commented Aug 17, 2020 at 14:59
  • @KetanPanchal can you please let me know how you can stop to calling two times same event ? Commented Aug 25, 2020 at 14:16

1 Answer 1

5

For Prevention i have used registry in my code.

if (!$this->registry->registry('comment_save_after')) 
{
   $this->registry->register('comment_save_after', 'Executed');
   
   try{
   
   }
   catch (\Exception $e)
   {
       echo $e->getMessage();
   }
}
   

Let me know if you are facing same issue after using registry.

2
  • great it will help to others too. Commented Aug 27, 2020 at 13:35
  • great this help me
    – Mujahidh
    Commented Aug 16, 2022 at 15:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.