2016-02-11 43 views
0

在Magento 2編程方式取消訂單:Magento的2取消訂單從我的帳戶頁

我實現了在Magento 1模塊中,我將取消從客戶帳戶頁面掛單。

請參考下面我在Magento的1的實現代碼:

$order = Mage::getModel('sales/order')->load($orderId); 
$order_status=$order->setState(Mage_Sales_Model_Order::STATE_CANCELED, true)->save(); 

我想要實現在Magento 2相同的功能有誰知道如何實現的呢?

我在magento 2中加載了訂單id的訂單,但無法取消訂單。

回答

0

您應該使用API​​(更多關於magento2 API concepts)爲,例如如何使用它在你的類:

<?php 

use Magento\Sales\Api\OrderManagementInterface; 

class A 
{ 
    /** 
    * @var OrderManagementInterface 
    */ 
    private $orderManagement; 

    /** 
    * @param OrderManagementInterface $orderManagement 
    */ 
    public function __construct(OrderManagementInterface $orderManagement) 
    { 
     $this->orderManagement = $orderManagement; 
    } 

    public function cancelOrderOne() 
    { 
     $orderId = 1; 
     $isCanceled = $this->orderManagement->cancel($orderId); 
    } 
} 
+0

工作就像一個魅力..謝謝。 – user3124850

+0

@Anton Ohorodnyk和@ user3124850你可以請提供確切的文件結構應該是。我可以在我的前端控制器中使用此代碼 –

+0

我已經完成了這項工作,它的工作原理非常完美http://magentocodes.blogspot.in/2017/10/how-to-cancel-order-programatically-in.html –

0

請看看下面的代碼,它也將驗證用戶協會的訂貨也

<?php 
Nmaespace\Modulename\Controller\Action; 

class Cancelorder extends \Magento\Framework\App\Action\Action 
{ 
    protected $orderManagement; 
    public function __construct(
    \Magento\Framework\App\Action\Context $context, 
    \Magento\Sales\Api\OrderManagementInterface $orderManagement 

) { 
    $this->orderManagement = $orderManagement; 
    parent::__construct($context); 
} 

public function execute() 
{ 
     $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 

     $customerSession = $objectManager->get('Magento\Customer\Model\Session'); 
     if(!$customerSession->isLoggedIn()) { 
       $this->_redirect('/'); 
       die; 
     } 

     /*get request params */ 
     $get_customer_id = $customerSession->getCustomer()->getId(); 

     $get_order_id = $this->getRequest()->getParam('order_id'); 
     /*get request params */ 
     //die; 
     $order = $objectManager->create('Magento\Sales\Model\Order')->load($get_order_id); 
     $getcustomerid = $get_customer_id; 
     $orderdata = $order->getData(); 
     $order_status = $orderdata["status"]; 
     //print_r($orderdata); 
     $cus_id = $orderdata["customer_id"]; 
     if($getcustomerid != $cus_id){ 
      echo "We cant Cancel this order at this time" ; 
      //die("go back"); 
     } 
     if($order_status == "pending"){ 
      $this->orderManagement->cancel($get_order_id); 
      echo "Order Cancelled successfully" ; 
     } 
     else{ 
      echo "We cant Cancel this order at this time" ; 

     } 
} 


} 
相關問題