PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, August 22, 2022

[FIXED] How to Programatically cancel order in magento 2

 August 22, 2022     magento2, php, programmatically     No comments   

Issue

If a customer placed an order of 3 different items with different quantities like

  1. shirt 2 qty
  2. Watch 1qty
  3. pant 3qty

and cancels the order item at different times I have to set the state to order cancelled

here's my code can anyone please tell me where I am wrong

if (isset($_POST['order'])) {
         $_orderCollectionFactory = $objectManager->create('\Magento\Sales\Model\ResourceModel\Order\CollectionFactory');

     $collection = $_orderCollectionFactory->create()

             ->addFieldToSelect('*')
             ->addFieldToFilter('status', ['neq' => 'cancelled']); 
foreach ($collectionFactory as $order)
        {
            $items = $order->getAllVisibleItems();
            foreach ($items as $items) {

                $totalitem = $totalitem + ($item['qty_canceled']);
                $itemcount = $order->getQtyOrdered();
               if ($itemcount == ($totalitem))
                 {
                    $order->setState("canceled");
                    $order->save();
                }

            }    
    }
}

Solution

Finally, I have Solved the issue for the above code

 $_orderCollectionFactory = $objectManager->create('\Magento\Sales\Model\ResourceModel\Order\CollectionFactory');

     $collection = $_orderCollectionFactory->create()
             ->addFieldToSelect('*')
             ->addFieldToFilter('status', ['neq' => 'cancelled']); 
             
foreach ($collection as $order)
        {
            $items = $order->getAllVisibleItems();
            $totalitem=0;
            foreach ($items as $item) {

            //  echo '<pre>';print_r(get_class_methods($item));
            // die();
                 $totalitem = $totalitem + ($item['qty_canceled']);
                $itemcount = $order->getQtyOrdered();

                if ($itemcount == ($totalitem))
                 {
                    echo $order->getIncrementId();
                    $order->setState("canceled");
                    $order->setStatus("canceled");
                    $order->save();
                 }
            }    
    }


Answered By - Aniket Singh
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing